1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/Template.h" 45 using namespace clang; 46 using namespace sema; 47 48 /// \brief Determine whether the use of this declaration is valid, without 49 /// emitting diagnostics. 50 bool Sema::CanUseDecl(NamedDecl *D) { 51 // See if this is an auto-typed variable whose initializer we are parsing. 52 if (ParsingInitForAutoVars.count(D)) 53 return false; 54 55 // See if this is a deleted function. 56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 57 if (FD->isDeleted()) 58 return false; 59 60 // If the function has a deduced return type, and we can't deduce it, 61 // then we can't use it either. 62 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() && 63 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 64 return false; 65 } 66 67 // See if this function is unavailable. 68 if (D->getAvailability() == AR_Unavailable && 69 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 70 return false; 71 72 return true; 73 } 74 75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 76 // Warn if this is used but marked unused. 77 if (D->hasAttr<UnusedAttr>()) { 78 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 79 if (!DC->hasAttr<UnusedAttr>()) 80 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 81 } 82 } 83 84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 85 NamedDecl *D, SourceLocation Loc, 86 const ObjCInterfaceDecl *UnknownObjCClass) { 87 // See if this declaration is unavailable or deprecated. 88 std::string Message; 89 AvailabilityResult Result = D->getAvailability(&Message); 90 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 91 if (Result == AR_Available) { 92 const DeclContext *DC = ECD->getDeclContext(); 93 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 94 Result = TheEnumDecl->getAvailability(&Message); 95 } 96 97 const ObjCPropertyDecl *ObjCPDecl = 0; 98 if (Result == AR_Deprecated || Result == AR_Unavailable) { 99 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 100 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 101 AvailabilityResult PDeclResult = PD->getAvailability(0); 102 if (PDeclResult == Result) 103 ObjCPDecl = PD; 104 } 105 } 106 } 107 108 switch (Result) { 109 case AR_Available: 110 case AR_NotYetIntroduced: 111 break; 112 113 case AR_Deprecated: 114 if (S.getCurContextAvailability() != AR_Deprecated) 115 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 116 D, Message, Loc, UnknownObjCClass, ObjCPDecl); 117 break; 118 119 case AR_Unavailable: 120 if (S.getCurContextAvailability() != AR_Unavailable) 121 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 122 D, Message, Loc, UnknownObjCClass, ObjCPDecl); 123 break; 124 125 } 126 return Result; 127 } 128 129 /// \brief Emit a note explaining that this function is deleted. 130 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 131 assert(Decl->isDeleted()); 132 133 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 134 135 if (Method && Method->isDeleted() && Method->isDefaulted()) { 136 // If the method was explicitly defaulted, point at that declaration. 137 if (!Method->isImplicit()) 138 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 139 140 // Try to diagnose why this special member function was implicitly 141 // deleted. This might fail, if that reason no longer applies. 142 CXXSpecialMember CSM = getSpecialMember(Method); 143 if (CSM != CXXInvalid) 144 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 145 146 return; 147 } 148 149 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 150 if (CXXConstructorDecl *BaseCD = 151 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 152 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 153 if (BaseCD->isDeleted()) { 154 NoteDeletedFunction(BaseCD); 155 } else { 156 // FIXME: An explanation of why exactly it can't be inherited 157 // would be nice. 158 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 159 } 160 return; 161 } 162 } 163 164 Diag(Decl->getLocation(), diag::note_availability_specified_here) 165 << Decl << true; 166 } 167 168 /// \brief Determine whether a FunctionDecl was ever declared with an 169 /// explicit storage class. 170 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 171 for (auto I : D->redecls()) { 172 if (I->getStorageClass() != SC_None) 173 return true; 174 } 175 return false; 176 } 177 178 /// \brief Check whether we're in an extern inline function and referring to a 179 /// variable or function with internal linkage (C11 6.7.4p3). 180 /// 181 /// This is only a warning because we used to silently accept this code, but 182 /// in many cases it will not behave correctly. This is not enabled in C++ mode 183 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 184 /// and so while there may still be user mistakes, most of the time we can't 185 /// prove that there are errors. 186 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 187 const NamedDecl *D, 188 SourceLocation Loc) { 189 // This is disabled under C++; there are too many ways for this to fire in 190 // contexts where the warning is a false positive, or where it is technically 191 // correct but benign. 192 if (S.getLangOpts().CPlusPlus) 193 return; 194 195 // Check if this is an inlined function or method. 196 FunctionDecl *Current = S.getCurFunctionDecl(); 197 if (!Current) 198 return; 199 if (!Current->isInlined()) 200 return; 201 if (!Current->isExternallyVisible()) 202 return; 203 204 // Check if the decl has internal linkage. 205 if (D->getFormalLinkage() != InternalLinkage) 206 return; 207 208 // Downgrade from ExtWarn to Extension if 209 // (1) the supposedly external inline function is in the main file, 210 // and probably won't be included anywhere else. 211 // (2) the thing we're referencing is a pure function. 212 // (3) the thing we're referencing is another inline function. 213 // This last can give us false negatives, but it's better than warning on 214 // wrappers for simple C library functions. 215 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 216 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 217 if (!DowngradeWarning && UsedFn) 218 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 219 220 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 221 : diag::warn_internal_in_extern_inline) 222 << /*IsVar=*/!UsedFn << D; 223 224 S.MaybeSuggestAddingStaticToDecl(Current); 225 226 S.Diag(D->getCanonicalDecl()->getLocation(), 227 diag::note_internal_decl_declared_here) 228 << D; 229 } 230 231 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 232 const FunctionDecl *First = Cur->getFirstDecl(); 233 234 // Suggest "static" on the function, if possible. 235 if (!hasAnyExplicitStorageClass(First)) { 236 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 237 Diag(DeclBegin, diag::note_convert_inline_to_static) 238 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 239 } 240 } 241 242 /// \brief Determine whether the use of this declaration is valid, and 243 /// emit any corresponding diagnostics. 244 /// 245 /// This routine diagnoses various problems with referencing 246 /// declarations that can occur when using a declaration. For example, 247 /// it might warn if a deprecated or unavailable declaration is being 248 /// used, or produce an error (and return true) if a C++0x deleted 249 /// function is being used. 250 /// 251 /// \returns true if there was an error (this declaration cannot be 252 /// referenced), false otherwise. 253 /// 254 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 255 const ObjCInterfaceDecl *UnknownObjCClass) { 256 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 257 // If there were any diagnostics suppressed by template argument deduction, 258 // emit them now. 259 SuppressedDiagnosticsMap::iterator 260 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 261 if (Pos != SuppressedDiagnostics.end()) { 262 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 263 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 264 Diag(Suppressed[I].first, Suppressed[I].second); 265 266 // Clear out the list of suppressed diagnostics, so that we don't emit 267 // them again for this specialization. However, we don't obsolete this 268 // entry from the table, because we want to avoid ever emitting these 269 // diagnostics again. 270 Suppressed.clear(); 271 } 272 273 // C++ [basic.start.main]p3: 274 // The function 'main' shall not be used within a program. 275 if (cast<FunctionDecl>(D)->isMain()) 276 Diag(Loc, diag::ext_main_used); 277 } 278 279 // See if this is an auto-typed variable whose initializer we are parsing. 280 if (ParsingInitForAutoVars.count(D)) { 281 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 282 << D->getDeclName(); 283 return true; 284 } 285 286 // See if this is a deleted function. 287 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 288 if (FD->isDeleted()) { 289 Diag(Loc, diag::err_deleted_function_use); 290 NoteDeletedFunction(FD); 291 return true; 292 } 293 294 // If the function has a deduced return type, and we can't deduce it, 295 // then we can't use it either. 296 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() && 297 DeduceReturnType(FD, Loc)) 298 return true; 299 } 300 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 301 302 DiagnoseUnusedOfDecl(*this, D, Loc); 303 304 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 305 306 return false; 307 } 308 309 /// \brief Retrieve the message suffix that should be added to a 310 /// diagnostic complaining about the given function being deleted or 311 /// unavailable. 312 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 313 std::string Message; 314 if (FD->getAvailability(&Message)) 315 return ": " + Message; 316 317 return std::string(); 318 } 319 320 /// DiagnoseSentinelCalls - This routine checks whether a call or 321 /// message-send is to a declaration with the sentinel attribute, and 322 /// if so, it checks that the requirements of the sentinel are 323 /// satisfied. 324 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 325 ArrayRef<Expr *> Args) { 326 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 327 if (!attr) 328 return; 329 330 // The number of formal parameters of the declaration. 331 unsigned numFormalParams; 332 333 // The kind of declaration. This is also an index into a %select in 334 // the diagnostic. 335 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 336 337 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 338 numFormalParams = MD->param_size(); 339 calleeType = CT_Method; 340 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 341 numFormalParams = FD->param_size(); 342 calleeType = CT_Function; 343 } else if (isa<VarDecl>(D)) { 344 QualType type = cast<ValueDecl>(D)->getType(); 345 const FunctionType *fn = 0; 346 if (const PointerType *ptr = type->getAs<PointerType>()) { 347 fn = ptr->getPointeeType()->getAs<FunctionType>(); 348 if (!fn) return; 349 calleeType = CT_Function; 350 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 351 fn = ptr->getPointeeType()->castAs<FunctionType>(); 352 calleeType = CT_Block; 353 } else { 354 return; 355 } 356 357 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 358 numFormalParams = proto->getNumParams(); 359 } else { 360 numFormalParams = 0; 361 } 362 } else { 363 return; 364 } 365 366 // "nullPos" is the number of formal parameters at the end which 367 // effectively count as part of the variadic arguments. This is 368 // useful if you would prefer to not have *any* formal parameters, 369 // but the language forces you to have at least one. 370 unsigned nullPos = attr->getNullPos(); 371 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 372 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 373 374 // The number of arguments which should follow the sentinel. 375 unsigned numArgsAfterSentinel = attr->getSentinel(); 376 377 // If there aren't enough arguments for all the formal parameters, 378 // the sentinel, and the args after the sentinel, complain. 379 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 380 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 381 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 382 return; 383 } 384 385 // Otherwise, find the sentinel expression. 386 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 387 if (!sentinelExpr) return; 388 if (sentinelExpr->isValueDependent()) return; 389 if (Context.isSentinelNullExpr(sentinelExpr)) return; 390 391 // Pick a reasonable string to insert. Optimistically use 'nil' or 392 // 'NULL' if those are actually defined in the context. Only use 393 // 'nil' for ObjC methods, where it's much more likely that the 394 // variadic arguments form a list of object pointers. 395 SourceLocation MissingNilLoc 396 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 397 std::string NullValue; 398 if (calleeType == CT_Method && 399 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 400 NullValue = "nil"; 401 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 402 NullValue = "NULL"; 403 else 404 NullValue = "(void*) 0"; 405 406 if (MissingNilLoc.isInvalid()) 407 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 408 else 409 Diag(MissingNilLoc, diag::warn_missing_sentinel) 410 << int(calleeType) 411 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 412 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 413 } 414 415 SourceRange Sema::getExprRange(Expr *E) const { 416 return E ? E->getSourceRange() : SourceRange(); 417 } 418 419 //===----------------------------------------------------------------------===// 420 // Standard Promotions and Conversions 421 //===----------------------------------------------------------------------===// 422 423 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 424 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 425 // Handle any placeholder expressions which made it here. 426 if (E->getType()->isPlaceholderType()) { 427 ExprResult result = CheckPlaceholderExpr(E); 428 if (result.isInvalid()) return ExprError(); 429 E = result.take(); 430 } 431 432 QualType Ty = E->getType(); 433 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 434 435 if (Ty->isFunctionType()) { 436 // If we are here, we are not calling a function but taking 437 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 438 if (getLangOpts().OpenCL) { 439 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 440 return ExprError(); 441 } 442 E = ImpCastExprToType(E, Context.getPointerType(Ty), 443 CK_FunctionToPointerDecay).take(); 444 } else if (Ty->isArrayType()) { 445 // In C90 mode, arrays only promote to pointers if the array expression is 446 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 447 // type 'array of type' is converted to an expression that has type 'pointer 448 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 449 // that has type 'array of type' ...". The relevant change is "an lvalue" 450 // (C90) to "an expression" (C99). 451 // 452 // C++ 4.2p1: 453 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 454 // T" can be converted to an rvalue of type "pointer to T". 455 // 456 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 457 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 458 CK_ArrayToPointerDecay).take(); 459 } 460 return Owned(E); 461 } 462 463 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 464 // Check to see if we are dereferencing a null pointer. If so, 465 // and if not volatile-qualified, this is undefined behavior that the 466 // optimizer will delete, so warn about it. People sometimes try to use this 467 // to get a deterministic trap and are surprised by clang's behavior. This 468 // only handles the pattern "*null", which is a very syntactic check. 469 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 470 if (UO->getOpcode() == UO_Deref && 471 UO->getSubExpr()->IgnoreParenCasts()-> 472 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 473 !UO->getType().isVolatileQualified()) { 474 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 475 S.PDiag(diag::warn_indirection_through_null) 476 << UO->getSubExpr()->getSourceRange()); 477 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 478 S.PDiag(diag::note_indirection_through_null)); 479 } 480 } 481 482 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 483 SourceLocation AssignLoc, 484 const Expr* RHS) { 485 const ObjCIvarDecl *IV = OIRE->getDecl(); 486 if (!IV) 487 return; 488 489 DeclarationName MemberName = IV->getDeclName(); 490 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 491 if (!Member || !Member->isStr("isa")) 492 return; 493 494 const Expr *Base = OIRE->getBase(); 495 QualType BaseType = Base->getType(); 496 if (OIRE->isArrow()) 497 BaseType = BaseType->getPointeeType(); 498 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 499 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 500 ObjCInterfaceDecl *ClassDeclared = 0; 501 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 502 if (!ClassDeclared->getSuperClass() 503 && (*ClassDeclared->ivar_begin()) == IV) { 504 if (RHS) { 505 NamedDecl *ObjectSetClass = 506 S.LookupSingleName(S.TUScope, 507 &S.Context.Idents.get("object_setClass"), 508 SourceLocation(), S.LookupOrdinaryName); 509 if (ObjectSetClass) { 510 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 511 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 512 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 513 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 514 AssignLoc), ",") << 515 FixItHint::CreateInsertion(RHSLocEnd, ")"); 516 } 517 else 518 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 519 } else { 520 NamedDecl *ObjectGetClass = 521 S.LookupSingleName(S.TUScope, 522 &S.Context.Idents.get("object_getClass"), 523 SourceLocation(), S.LookupOrdinaryName); 524 if (ObjectGetClass) 525 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 526 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 527 FixItHint::CreateReplacement( 528 SourceRange(OIRE->getOpLoc(), 529 OIRE->getLocEnd()), ")"); 530 else 531 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 532 } 533 S.Diag(IV->getLocation(), diag::note_ivar_decl); 534 } 535 } 536 } 537 538 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 539 // Handle any placeholder expressions which made it here. 540 if (E->getType()->isPlaceholderType()) { 541 ExprResult result = CheckPlaceholderExpr(E); 542 if (result.isInvalid()) return ExprError(); 543 E = result.take(); 544 } 545 546 // C++ [conv.lval]p1: 547 // A glvalue of a non-function, non-array type T can be 548 // converted to a prvalue. 549 if (!E->isGLValue()) return Owned(E); 550 551 QualType T = E->getType(); 552 assert(!T.isNull() && "r-value conversion on typeless expression?"); 553 554 // We don't want to throw lvalue-to-rvalue casts on top of 555 // expressions of certain types in C++. 556 if (getLangOpts().CPlusPlus && 557 (E->getType() == Context.OverloadTy || 558 T->isDependentType() || 559 T->isRecordType())) 560 return Owned(E); 561 562 // The C standard is actually really unclear on this point, and 563 // DR106 tells us what the result should be but not why. It's 564 // generally best to say that void types just doesn't undergo 565 // lvalue-to-rvalue at all. Note that expressions of unqualified 566 // 'void' type are never l-values, but qualified void can be. 567 if (T->isVoidType()) 568 return Owned(E); 569 570 // OpenCL usually rejects direct accesses to values of 'half' type. 571 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 572 T->isHalfType()) { 573 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 574 << 0 << T; 575 return ExprError(); 576 } 577 578 CheckForNullPointerDereference(*this, E); 579 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 580 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 581 &Context.Idents.get("object_getClass"), 582 SourceLocation(), LookupOrdinaryName); 583 if (ObjectGetClass) 584 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 585 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 586 FixItHint::CreateReplacement( 587 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 588 else 589 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 590 } 591 else if (const ObjCIvarRefExpr *OIRE = 592 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 593 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 594 595 // C++ [conv.lval]p1: 596 // [...] If T is a non-class type, the type of the prvalue is the 597 // cv-unqualified version of T. Otherwise, the type of the 598 // rvalue is T. 599 // 600 // C99 6.3.2.1p2: 601 // If the lvalue has qualified type, the value has the unqualified 602 // version of the type of the lvalue; otherwise, the value has the 603 // type of the lvalue. 604 if (T.hasQualifiers()) 605 T = T.getUnqualifiedType(); 606 607 UpdateMarkingForLValueToRValue(E); 608 609 // Loading a __weak object implicitly retains the value, so we need a cleanup to 610 // balance that. 611 if (getLangOpts().ObjCAutoRefCount && 612 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 613 ExprNeedsCleanups = true; 614 615 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 616 E, 0, VK_RValue)); 617 618 // C11 6.3.2.1p2: 619 // ... if the lvalue has atomic type, the value has the non-atomic version 620 // of the type of the lvalue ... 621 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 622 T = Atomic->getValueType().getUnqualifiedType(); 623 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 624 Res.get(), 0, VK_RValue)); 625 } 626 627 return Res; 628 } 629 630 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 631 ExprResult Res = DefaultFunctionArrayConversion(E); 632 if (Res.isInvalid()) 633 return ExprError(); 634 Res = DefaultLvalueConversion(Res.take()); 635 if (Res.isInvalid()) 636 return ExprError(); 637 return Res; 638 } 639 640 /// CallExprUnaryConversions - a special case of an unary conversion 641 /// performed on a function designator of a call expression. 642 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 643 QualType Ty = E->getType(); 644 ExprResult Res = E; 645 // Only do implicit cast for a function type, but not for a pointer 646 // to function type. 647 if (Ty->isFunctionType()) { 648 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 649 CK_FunctionToPointerDecay).take(); 650 if (Res.isInvalid()) 651 return ExprError(); 652 } 653 Res = DefaultLvalueConversion(Res.take()); 654 if (Res.isInvalid()) 655 return ExprError(); 656 return Owned(Res.take()); 657 } 658 659 /// UsualUnaryConversions - Performs various conversions that are common to most 660 /// operators (C99 6.3). The conversions of array and function types are 661 /// sometimes suppressed. For example, the array->pointer conversion doesn't 662 /// apply if the array is an argument to the sizeof or address (&) operators. 663 /// In these instances, this routine should *not* be called. 664 ExprResult Sema::UsualUnaryConversions(Expr *E) { 665 // First, convert to an r-value. 666 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 667 if (Res.isInvalid()) 668 return ExprError(); 669 E = Res.take(); 670 671 QualType Ty = E->getType(); 672 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 673 674 // Half FP have to be promoted to float unless it is natively supported 675 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 676 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 677 678 // Try to perform integral promotions if the object has a theoretically 679 // promotable type. 680 if (Ty->isIntegralOrUnscopedEnumerationType()) { 681 // C99 6.3.1.1p2: 682 // 683 // The following may be used in an expression wherever an int or 684 // unsigned int may be used: 685 // - an object or expression with an integer type whose integer 686 // conversion rank is less than or equal to the rank of int 687 // and unsigned int. 688 // - A bit-field of type _Bool, int, signed int, or unsigned int. 689 // 690 // If an int can represent all values of the original type, the 691 // value is converted to an int; otherwise, it is converted to an 692 // unsigned int. These are called the integer promotions. All 693 // other types are unchanged by the integer promotions. 694 695 QualType PTy = Context.isPromotableBitField(E); 696 if (!PTy.isNull()) { 697 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 698 return Owned(E); 699 } 700 if (Ty->isPromotableIntegerType()) { 701 QualType PT = Context.getPromotedIntegerType(Ty); 702 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 703 return Owned(E); 704 } 705 } 706 return Owned(E); 707 } 708 709 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 710 /// do not have a prototype. Arguments that have type float or __fp16 711 /// are promoted to double. All other argument types are converted by 712 /// UsualUnaryConversions(). 713 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 714 QualType Ty = E->getType(); 715 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 716 717 ExprResult Res = UsualUnaryConversions(E); 718 if (Res.isInvalid()) 719 return ExprError(); 720 E = Res.take(); 721 722 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 723 // double. 724 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 725 if (BTy && (BTy->getKind() == BuiltinType::Half || 726 BTy->getKind() == BuiltinType::Float)) 727 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 728 729 // C++ performs lvalue-to-rvalue conversion as a default argument 730 // promotion, even on class types, but note: 731 // C++11 [conv.lval]p2: 732 // When an lvalue-to-rvalue conversion occurs in an unevaluated 733 // operand or a subexpression thereof the value contained in the 734 // referenced object is not accessed. Otherwise, if the glvalue 735 // has a class type, the conversion copy-initializes a temporary 736 // of type T from the glvalue and the result of the conversion 737 // is a prvalue for the temporary. 738 // FIXME: add some way to gate this entire thing for correctness in 739 // potentially potentially evaluated contexts. 740 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 741 ExprResult Temp = PerformCopyInitialization( 742 InitializedEntity::InitializeTemporary(E->getType()), 743 E->getExprLoc(), 744 Owned(E)); 745 if (Temp.isInvalid()) 746 return ExprError(); 747 E = Temp.get(); 748 } 749 750 return Owned(E); 751 } 752 753 /// Determine the degree of POD-ness for an expression. 754 /// Incomplete types are considered POD, since this check can be performed 755 /// when we're in an unevaluated context. 756 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 757 if (Ty->isIncompleteType()) { 758 // C++11 [expr.call]p7: 759 // After these conversions, if the argument does not have arithmetic, 760 // enumeration, pointer, pointer to member, or class type, the program 761 // is ill-formed. 762 // 763 // Since we've already performed array-to-pointer and function-to-pointer 764 // decay, the only such type in C++ is cv void. This also handles 765 // initializer lists as variadic arguments. 766 if (Ty->isVoidType()) 767 return VAK_Invalid; 768 769 if (Ty->isObjCObjectType()) 770 return VAK_Invalid; 771 return VAK_Valid; 772 } 773 774 if (Ty.isCXX98PODType(Context)) 775 return VAK_Valid; 776 777 // C++11 [expr.call]p7: 778 // Passing a potentially-evaluated argument of class type (Clause 9) 779 // having a non-trivial copy constructor, a non-trivial move constructor, 780 // or a non-trivial destructor, with no corresponding parameter, 781 // is conditionally-supported with implementation-defined semantics. 782 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 783 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 784 if (!Record->hasNonTrivialCopyConstructor() && 785 !Record->hasNonTrivialMoveConstructor() && 786 !Record->hasNonTrivialDestructor()) 787 return VAK_ValidInCXX11; 788 789 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 790 return VAK_Valid; 791 792 if (Ty->isObjCObjectType()) 793 return VAK_Invalid; 794 795 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 796 // permitted to reject them. We should consider doing so. 797 return VAK_Undefined; 798 } 799 800 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 801 // Don't allow one to pass an Objective-C interface to a vararg. 802 const QualType &Ty = E->getType(); 803 VarArgKind VAK = isValidVarArgType(Ty); 804 805 // Complain about passing non-POD types through varargs. 806 switch (VAK) { 807 case VAK_ValidInCXX11: 808 DiagRuntimeBehavior( 809 E->getLocStart(), 0, 810 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 811 << Ty << CT); 812 // Fall through. 813 case VAK_Valid: 814 if (Ty->isRecordType()) { 815 // This is unlikely to be what the user intended. If the class has a 816 // 'c_str' member function, the user probably meant to call that. 817 DiagRuntimeBehavior(E->getLocStart(), 0, 818 PDiag(diag::warn_pass_class_arg_to_vararg) 819 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 820 } 821 break; 822 823 case VAK_Undefined: 824 DiagRuntimeBehavior( 825 E->getLocStart(), 0, 826 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 827 << getLangOpts().CPlusPlus11 << Ty << CT); 828 break; 829 830 case VAK_Invalid: 831 if (Ty->isObjCObjectType()) 832 DiagRuntimeBehavior( 833 E->getLocStart(), 0, 834 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 835 << Ty << CT); 836 else 837 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 838 << isa<InitListExpr>(E) << Ty << CT; 839 break; 840 } 841 } 842 843 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 844 /// will create a trap if the resulting type is not a POD type. 845 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 846 FunctionDecl *FDecl) { 847 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 848 // Strip the unbridged-cast placeholder expression off, if applicable. 849 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 850 (CT == VariadicMethod || 851 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 852 E = stripARCUnbridgedCast(E); 853 854 // Otherwise, do normal placeholder checking. 855 } else { 856 ExprResult ExprRes = CheckPlaceholderExpr(E); 857 if (ExprRes.isInvalid()) 858 return ExprError(); 859 E = ExprRes.take(); 860 } 861 } 862 863 ExprResult ExprRes = DefaultArgumentPromotion(E); 864 if (ExprRes.isInvalid()) 865 return ExprError(); 866 E = ExprRes.take(); 867 868 // Diagnostics regarding non-POD argument types are 869 // emitted along with format string checking in Sema::CheckFunctionCall(). 870 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 871 // Turn this into a trap. 872 CXXScopeSpec SS; 873 SourceLocation TemplateKWLoc; 874 UnqualifiedId Name; 875 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 876 E->getLocStart()); 877 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 878 Name, true, false); 879 if (TrapFn.isInvalid()) 880 return ExprError(); 881 882 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 883 E->getLocStart(), None, 884 E->getLocEnd()); 885 if (Call.isInvalid()) 886 return ExprError(); 887 888 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 889 Call.get(), E); 890 if (Comma.isInvalid()) 891 return ExprError(); 892 return Comma.get(); 893 } 894 895 if (!getLangOpts().CPlusPlus && 896 RequireCompleteType(E->getExprLoc(), E->getType(), 897 diag::err_call_incomplete_argument)) 898 return ExprError(); 899 900 return Owned(E); 901 } 902 903 /// \brief Converts an integer to complex float type. Helper function of 904 /// UsualArithmeticConversions() 905 /// 906 /// \return false if the integer expression is an integer type and is 907 /// successfully converted to the complex type. 908 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 909 ExprResult &ComplexExpr, 910 QualType IntTy, 911 QualType ComplexTy, 912 bool SkipCast) { 913 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 914 if (SkipCast) return false; 915 if (IntTy->isIntegerType()) { 916 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 917 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 918 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 919 CK_FloatingRealToComplex); 920 } else { 921 assert(IntTy->isComplexIntegerType()); 922 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 923 CK_IntegralComplexToFloatingComplex); 924 } 925 return false; 926 } 927 928 /// \brief Takes two complex float types and converts them to the same type. 929 /// Helper function of UsualArithmeticConversions() 930 static QualType 931 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 932 ExprResult &RHS, QualType LHSType, 933 QualType RHSType, 934 bool IsCompAssign) { 935 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 936 937 if (order < 0) { 938 // _Complex float -> _Complex double 939 if (!IsCompAssign) 940 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 941 return RHSType; 942 } 943 if (order > 0) 944 // _Complex float -> _Complex double 945 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 946 return LHSType; 947 } 948 949 /// \brief Converts otherExpr to complex float and promotes complexExpr if 950 /// necessary. Helper function of UsualArithmeticConversions() 951 static QualType handleOtherComplexFloatConversion(Sema &S, 952 ExprResult &ComplexExpr, 953 ExprResult &OtherExpr, 954 QualType ComplexTy, 955 QualType OtherTy, 956 bool ConvertComplexExpr, 957 bool ConvertOtherExpr) { 958 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 959 960 // If just the complexExpr is complex, the otherExpr needs to be converted, 961 // and the complexExpr might need to be promoted. 962 if (order > 0) { // complexExpr is wider 963 // float -> _Complex double 964 if (ConvertOtherExpr) { 965 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 966 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 967 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 968 CK_FloatingRealToComplex); 969 } 970 return ComplexTy; 971 } 972 973 // otherTy is at least as wide. Find its corresponding complex type. 974 QualType result = (order == 0 ? ComplexTy : 975 S.Context.getComplexType(OtherTy)); 976 977 // double -> _Complex double 978 if (ConvertOtherExpr) 979 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 980 CK_FloatingRealToComplex); 981 982 // _Complex float -> _Complex double 983 if (ConvertComplexExpr && order < 0) 984 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 985 CK_FloatingComplexCast); 986 987 return result; 988 } 989 990 /// \brief Handle arithmetic conversion with complex types. Helper function of 991 /// UsualArithmeticConversions() 992 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 993 ExprResult &RHS, QualType LHSType, 994 QualType RHSType, 995 bool IsCompAssign) { 996 // if we have an integer operand, the result is the complex type. 997 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 998 /*skipCast*/false)) 999 return LHSType; 1000 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1001 /*skipCast*/IsCompAssign)) 1002 return RHSType; 1003 1004 // This handles complex/complex, complex/float, or float/complex. 1005 // When both operands are complex, the shorter operand is converted to the 1006 // type of the longer, and that is the type of the result. This corresponds 1007 // to what is done when combining two real floating-point operands. 1008 // The fun begins when size promotion occur across type domains. 1009 // From H&S 6.3.4: When one operand is complex and the other is a real 1010 // floating-point type, the less precise type is converted, within it's 1011 // real or complex domain, to the precision of the other type. For example, 1012 // when combining a "long double" with a "double _Complex", the 1013 // "double _Complex" is promoted to "long double _Complex". 1014 1015 bool LHSComplexFloat = LHSType->isComplexType(); 1016 bool RHSComplexFloat = RHSType->isComplexType(); 1017 1018 // If both are complex, just cast to the more precise type. 1019 if (LHSComplexFloat && RHSComplexFloat) 1020 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 1021 LHSType, RHSType, 1022 IsCompAssign); 1023 1024 // If only one operand is complex, promote it if necessary and convert the 1025 // other operand to complex. 1026 if (LHSComplexFloat) 1027 return handleOtherComplexFloatConversion( 1028 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1029 /*convertOtherExpr*/ true); 1030 1031 assert(RHSComplexFloat); 1032 return handleOtherComplexFloatConversion( 1033 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1034 /*convertOtherExpr*/ !IsCompAssign); 1035 } 1036 1037 /// \brief Hande arithmetic conversion from integer to float. Helper function 1038 /// of UsualArithmeticConversions() 1039 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1040 ExprResult &IntExpr, 1041 QualType FloatTy, QualType IntTy, 1042 bool ConvertFloat, bool ConvertInt) { 1043 if (IntTy->isIntegerType()) { 1044 if (ConvertInt) 1045 // Convert intExpr to the lhs floating point type. 1046 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 1047 CK_IntegralToFloating); 1048 return FloatTy; 1049 } 1050 1051 // Convert both sides to the appropriate complex float. 1052 assert(IntTy->isComplexIntegerType()); 1053 QualType result = S.Context.getComplexType(FloatTy); 1054 1055 // _Complex int -> _Complex float 1056 if (ConvertInt) 1057 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 1058 CK_IntegralComplexToFloatingComplex); 1059 1060 // float -> _Complex float 1061 if (ConvertFloat) 1062 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1063 CK_FloatingRealToComplex); 1064 1065 return result; 1066 } 1067 1068 /// \brief Handle arithmethic conversion with floating point types. Helper 1069 /// function of UsualArithmeticConversions() 1070 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1071 ExprResult &RHS, QualType LHSType, 1072 QualType RHSType, bool IsCompAssign) { 1073 bool LHSFloat = LHSType->isRealFloatingType(); 1074 bool RHSFloat = RHSType->isRealFloatingType(); 1075 1076 // If we have two real floating types, convert the smaller operand 1077 // to the bigger result. 1078 if (LHSFloat && RHSFloat) { 1079 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1080 if (order > 0) { 1081 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1082 return LHSType; 1083 } 1084 1085 assert(order < 0 && "illegal float comparison"); 1086 if (!IsCompAssign) 1087 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1088 return RHSType; 1089 } 1090 1091 if (LHSFloat) 1092 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1093 /*convertFloat=*/!IsCompAssign, 1094 /*convertInt=*/ true); 1095 assert(RHSFloat); 1096 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1097 /*convertInt=*/ true, 1098 /*convertFloat=*/!IsCompAssign); 1099 } 1100 1101 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1102 1103 namespace { 1104 /// These helper callbacks are placed in an anonymous namespace to 1105 /// permit their use as function template parameters. 1106 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1107 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1108 } 1109 1110 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1111 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1112 CK_IntegralComplexCast); 1113 } 1114 } 1115 1116 /// \brief Handle integer arithmetic conversions. Helper function of 1117 /// UsualArithmeticConversions() 1118 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1119 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1120 ExprResult &RHS, QualType LHSType, 1121 QualType RHSType, bool IsCompAssign) { 1122 // The rules for this case are in C99 6.3.1.8 1123 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1124 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1125 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1126 if (LHSSigned == RHSSigned) { 1127 // Same signedness; use the higher-ranked type 1128 if (order >= 0) { 1129 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1130 return LHSType; 1131 } else if (!IsCompAssign) 1132 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1133 return RHSType; 1134 } else if (order != (LHSSigned ? 1 : -1)) { 1135 // The unsigned type has greater than or equal rank to the 1136 // signed type, so use the unsigned type 1137 if (RHSSigned) { 1138 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1139 return LHSType; 1140 } else if (!IsCompAssign) 1141 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1142 return RHSType; 1143 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1144 // The two types are different widths; if we are here, that 1145 // means the signed type is larger than the unsigned type, so 1146 // use the signed type. 1147 if (LHSSigned) { 1148 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1149 return LHSType; 1150 } else if (!IsCompAssign) 1151 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1152 return RHSType; 1153 } else { 1154 // The signed type is higher-ranked than the unsigned type, 1155 // but isn't actually any bigger (like unsigned int and long 1156 // on most 32-bit systems). Use the unsigned type corresponding 1157 // to the signed type. 1158 QualType result = 1159 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1160 RHS = (*doRHSCast)(S, RHS.take(), result); 1161 if (!IsCompAssign) 1162 LHS = (*doLHSCast)(S, LHS.take(), result); 1163 return result; 1164 } 1165 } 1166 1167 /// \brief Handle conversions with GCC complex int extension. Helper function 1168 /// of UsualArithmeticConversions() 1169 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1170 ExprResult &RHS, QualType LHSType, 1171 QualType RHSType, 1172 bool IsCompAssign) { 1173 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1174 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1175 1176 if (LHSComplexInt && RHSComplexInt) { 1177 QualType LHSEltType = LHSComplexInt->getElementType(); 1178 QualType RHSEltType = RHSComplexInt->getElementType(); 1179 QualType ScalarType = 1180 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1181 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1182 1183 return S.Context.getComplexType(ScalarType); 1184 } 1185 1186 if (LHSComplexInt) { 1187 QualType LHSEltType = LHSComplexInt->getElementType(); 1188 QualType ScalarType = 1189 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1190 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1191 QualType ComplexType = S.Context.getComplexType(ScalarType); 1192 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1193 CK_IntegralRealToComplex); 1194 1195 return ComplexType; 1196 } 1197 1198 assert(RHSComplexInt); 1199 1200 QualType RHSEltType = RHSComplexInt->getElementType(); 1201 QualType ScalarType = 1202 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1203 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1204 QualType ComplexType = S.Context.getComplexType(ScalarType); 1205 1206 if (!IsCompAssign) 1207 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1208 CK_IntegralRealToComplex); 1209 return ComplexType; 1210 } 1211 1212 /// UsualArithmeticConversions - Performs various conversions that are common to 1213 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1214 /// routine returns the first non-arithmetic type found. The client is 1215 /// responsible for emitting appropriate error diagnostics. 1216 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1217 bool IsCompAssign) { 1218 if (!IsCompAssign) { 1219 LHS = UsualUnaryConversions(LHS.take()); 1220 if (LHS.isInvalid()) 1221 return QualType(); 1222 } 1223 1224 RHS = UsualUnaryConversions(RHS.take()); 1225 if (RHS.isInvalid()) 1226 return QualType(); 1227 1228 // For conversion purposes, we ignore any qualifiers. 1229 // For example, "const float" and "float" are equivalent. 1230 QualType LHSType = 1231 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1232 QualType RHSType = 1233 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1234 1235 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1236 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1237 LHSType = AtomicLHS->getValueType(); 1238 1239 // If both types are identical, no conversion is needed. 1240 if (LHSType == RHSType) 1241 return LHSType; 1242 1243 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1244 // The caller can deal with this (e.g. pointer + int). 1245 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1246 return QualType(); 1247 1248 // Apply unary and bitfield promotions to the LHS's type. 1249 QualType LHSUnpromotedType = LHSType; 1250 if (LHSType->isPromotableIntegerType()) 1251 LHSType = Context.getPromotedIntegerType(LHSType); 1252 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1253 if (!LHSBitfieldPromoteTy.isNull()) 1254 LHSType = LHSBitfieldPromoteTy; 1255 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1256 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1257 1258 // If both types are identical, no conversion is needed. 1259 if (LHSType == RHSType) 1260 return LHSType; 1261 1262 // At this point, we have two different arithmetic types. 1263 1264 // Handle complex types first (C99 6.3.1.8p1). 1265 if (LHSType->isComplexType() || RHSType->isComplexType()) 1266 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1267 IsCompAssign); 1268 1269 // Now handle "real" floating types (i.e. float, double, long double). 1270 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1271 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1272 IsCompAssign); 1273 1274 // Handle GCC complex int extension. 1275 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1276 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1277 IsCompAssign); 1278 1279 // Finally, we have two differing integer types. 1280 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1281 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1282 } 1283 1284 1285 //===----------------------------------------------------------------------===// 1286 // Semantic Analysis for various Expression Types 1287 //===----------------------------------------------------------------------===// 1288 1289 1290 ExprResult 1291 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1292 SourceLocation DefaultLoc, 1293 SourceLocation RParenLoc, 1294 Expr *ControllingExpr, 1295 ArrayRef<ParsedType> ArgTypes, 1296 ArrayRef<Expr *> ArgExprs) { 1297 unsigned NumAssocs = ArgTypes.size(); 1298 assert(NumAssocs == ArgExprs.size()); 1299 1300 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1301 for (unsigned i = 0; i < NumAssocs; ++i) { 1302 if (ArgTypes[i]) 1303 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1304 else 1305 Types[i] = 0; 1306 } 1307 1308 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1309 ControllingExpr, 1310 llvm::makeArrayRef(Types, NumAssocs), 1311 ArgExprs); 1312 delete [] Types; 1313 return ER; 1314 } 1315 1316 ExprResult 1317 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1318 SourceLocation DefaultLoc, 1319 SourceLocation RParenLoc, 1320 Expr *ControllingExpr, 1321 ArrayRef<TypeSourceInfo *> Types, 1322 ArrayRef<Expr *> Exprs) { 1323 unsigned NumAssocs = Types.size(); 1324 assert(NumAssocs == Exprs.size()); 1325 if (ControllingExpr->getType()->isPlaceholderType()) { 1326 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1327 if (result.isInvalid()) return ExprError(); 1328 ControllingExpr = result.take(); 1329 } 1330 1331 bool TypeErrorFound = false, 1332 IsResultDependent = ControllingExpr->isTypeDependent(), 1333 ContainsUnexpandedParameterPack 1334 = ControllingExpr->containsUnexpandedParameterPack(); 1335 1336 for (unsigned i = 0; i < NumAssocs; ++i) { 1337 if (Exprs[i]->containsUnexpandedParameterPack()) 1338 ContainsUnexpandedParameterPack = true; 1339 1340 if (Types[i]) { 1341 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1342 ContainsUnexpandedParameterPack = true; 1343 1344 if (Types[i]->getType()->isDependentType()) { 1345 IsResultDependent = true; 1346 } else { 1347 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1348 // complete object type other than a variably modified type." 1349 unsigned D = 0; 1350 if (Types[i]->getType()->isIncompleteType()) 1351 D = diag::err_assoc_type_incomplete; 1352 else if (!Types[i]->getType()->isObjectType()) 1353 D = diag::err_assoc_type_nonobject; 1354 else if (Types[i]->getType()->isVariablyModifiedType()) 1355 D = diag::err_assoc_type_variably_modified; 1356 1357 if (D != 0) { 1358 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1359 << Types[i]->getTypeLoc().getSourceRange() 1360 << Types[i]->getType(); 1361 TypeErrorFound = true; 1362 } 1363 1364 // C11 6.5.1.1p2 "No two generic associations in the same generic 1365 // selection shall specify compatible types." 1366 for (unsigned j = i+1; j < NumAssocs; ++j) 1367 if (Types[j] && !Types[j]->getType()->isDependentType() && 1368 Context.typesAreCompatible(Types[i]->getType(), 1369 Types[j]->getType())) { 1370 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1371 diag::err_assoc_compatible_types) 1372 << Types[j]->getTypeLoc().getSourceRange() 1373 << Types[j]->getType() 1374 << Types[i]->getType(); 1375 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1376 diag::note_compat_assoc) 1377 << Types[i]->getTypeLoc().getSourceRange() 1378 << Types[i]->getType(); 1379 TypeErrorFound = true; 1380 } 1381 } 1382 } 1383 } 1384 if (TypeErrorFound) 1385 return ExprError(); 1386 1387 // If we determined that the generic selection is result-dependent, don't 1388 // try to compute the result expression. 1389 if (IsResultDependent) 1390 return Owned(new (Context) GenericSelectionExpr( 1391 Context, KeyLoc, ControllingExpr, 1392 Types, Exprs, 1393 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1394 1395 SmallVector<unsigned, 1> CompatIndices; 1396 unsigned DefaultIndex = -1U; 1397 for (unsigned i = 0; i < NumAssocs; ++i) { 1398 if (!Types[i]) 1399 DefaultIndex = i; 1400 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1401 Types[i]->getType())) 1402 CompatIndices.push_back(i); 1403 } 1404 1405 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1406 // type compatible with at most one of the types named in its generic 1407 // association list." 1408 if (CompatIndices.size() > 1) { 1409 // We strip parens here because the controlling expression is typically 1410 // parenthesized in macro definitions. 1411 ControllingExpr = ControllingExpr->IgnoreParens(); 1412 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1413 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1414 << (unsigned) CompatIndices.size(); 1415 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1416 E = CompatIndices.end(); I != E; ++I) { 1417 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1418 diag::note_compat_assoc) 1419 << Types[*I]->getTypeLoc().getSourceRange() 1420 << Types[*I]->getType(); 1421 } 1422 return ExprError(); 1423 } 1424 1425 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1426 // its controlling expression shall have type compatible with exactly one of 1427 // the types named in its generic association list." 1428 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1429 // We strip parens here because the controlling expression is typically 1430 // parenthesized in macro definitions. 1431 ControllingExpr = ControllingExpr->IgnoreParens(); 1432 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1433 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1434 return ExprError(); 1435 } 1436 1437 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1438 // type name that is compatible with the type of the controlling expression, 1439 // then the result expression of the generic selection is the expression 1440 // in that generic association. Otherwise, the result expression of the 1441 // generic selection is the expression in the default generic association." 1442 unsigned ResultIndex = 1443 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1444 1445 return Owned(new (Context) GenericSelectionExpr( 1446 Context, KeyLoc, ControllingExpr, 1447 Types, Exprs, 1448 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1449 ResultIndex)); 1450 } 1451 1452 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1453 /// location of the token and the offset of the ud-suffix within it. 1454 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1455 unsigned Offset) { 1456 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1457 S.getLangOpts()); 1458 } 1459 1460 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1461 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1462 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1463 IdentifierInfo *UDSuffix, 1464 SourceLocation UDSuffixLoc, 1465 ArrayRef<Expr*> Args, 1466 SourceLocation LitEndLoc) { 1467 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1468 1469 QualType ArgTy[2]; 1470 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1471 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1472 if (ArgTy[ArgIdx]->isArrayType()) 1473 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1474 } 1475 1476 DeclarationName OpName = 1477 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1478 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1479 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1480 1481 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1482 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1483 /*AllowRaw*/false, /*AllowTemplate*/false, 1484 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1485 return ExprError(); 1486 1487 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1488 } 1489 1490 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1491 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1492 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1493 /// multiple tokens. However, the common case is that StringToks points to one 1494 /// string. 1495 /// 1496 ExprResult 1497 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1498 Scope *UDLScope) { 1499 assert(NumStringToks && "Must have at least one string!"); 1500 1501 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1502 if (Literal.hadError) 1503 return ExprError(); 1504 1505 SmallVector<SourceLocation, 4> StringTokLocs; 1506 for (unsigned i = 0; i != NumStringToks; ++i) 1507 StringTokLocs.push_back(StringToks[i].getLocation()); 1508 1509 QualType CharTy = Context.CharTy; 1510 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1511 if (Literal.isWide()) { 1512 CharTy = Context.getWideCharType(); 1513 Kind = StringLiteral::Wide; 1514 } else if (Literal.isUTF8()) { 1515 Kind = StringLiteral::UTF8; 1516 } else if (Literal.isUTF16()) { 1517 CharTy = Context.Char16Ty; 1518 Kind = StringLiteral::UTF16; 1519 } else if (Literal.isUTF32()) { 1520 CharTy = Context.Char32Ty; 1521 Kind = StringLiteral::UTF32; 1522 } else if (Literal.isPascal()) { 1523 CharTy = Context.UnsignedCharTy; 1524 } 1525 1526 QualType CharTyConst = CharTy; 1527 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1528 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1529 CharTyConst.addConst(); 1530 1531 // Get an array type for the string, according to C99 6.4.5. This includes 1532 // the nul terminator character as well as the string length for pascal 1533 // strings. 1534 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1535 llvm::APInt(32, Literal.GetNumStringChars()+1), 1536 ArrayType::Normal, 0); 1537 1538 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1539 if (getLangOpts().OpenCL) { 1540 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1541 } 1542 1543 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1544 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1545 Kind, Literal.Pascal, StrTy, 1546 &StringTokLocs[0], 1547 StringTokLocs.size()); 1548 if (Literal.getUDSuffix().empty()) 1549 return Owned(Lit); 1550 1551 // We're building a user-defined literal. 1552 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1553 SourceLocation UDSuffixLoc = 1554 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1555 Literal.getUDSuffixOffset()); 1556 1557 // Make sure we're allowed user-defined literals here. 1558 if (!UDLScope) 1559 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1560 1561 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1562 // operator "" X (str, len) 1563 QualType SizeType = Context.getSizeType(); 1564 1565 DeclarationName OpName = 1566 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1567 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1568 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1569 1570 QualType ArgTy[] = { 1571 Context.getArrayDecayedType(StrTy), SizeType 1572 }; 1573 1574 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1575 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1576 /*AllowRaw*/false, /*AllowTemplate*/false, 1577 /*AllowStringTemplate*/true)) { 1578 1579 case LOLR_Cooked: { 1580 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1581 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1582 StringTokLocs[0]); 1583 Expr *Args[] = { Lit, LenArg }; 1584 1585 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1586 } 1587 1588 case LOLR_StringTemplate: { 1589 TemplateArgumentListInfo ExplicitArgs; 1590 1591 unsigned CharBits = Context.getIntWidth(CharTy); 1592 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1593 llvm::APSInt Value(CharBits, CharIsUnsigned); 1594 1595 TemplateArgument TypeArg(CharTy); 1596 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1597 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1598 1599 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1600 Value = Lit->getCodeUnit(I); 1601 TemplateArgument Arg(Context, Value, CharTy); 1602 TemplateArgumentLocInfo ArgInfo; 1603 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1604 } 1605 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1606 &ExplicitArgs); 1607 } 1608 case LOLR_Raw: 1609 case LOLR_Template: 1610 llvm_unreachable("unexpected literal operator lookup result"); 1611 case LOLR_Error: 1612 return ExprError(); 1613 } 1614 llvm_unreachable("unexpected literal operator lookup result"); 1615 } 1616 1617 ExprResult 1618 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1619 SourceLocation Loc, 1620 const CXXScopeSpec *SS) { 1621 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1622 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1623 } 1624 1625 /// BuildDeclRefExpr - Build an expression that references a 1626 /// declaration that does not require a closure capture. 1627 ExprResult 1628 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1629 const DeclarationNameInfo &NameInfo, 1630 const CXXScopeSpec *SS, NamedDecl *FoundD, 1631 const TemplateArgumentListInfo *TemplateArgs) { 1632 if (getLangOpts().CUDA) 1633 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1634 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1635 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1636 CalleeTarget = IdentifyCUDATarget(Callee); 1637 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1638 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1639 << CalleeTarget << D->getIdentifier() << CallerTarget; 1640 Diag(D->getLocation(), diag::note_previous_decl) 1641 << D->getIdentifier(); 1642 return ExprError(); 1643 } 1644 } 1645 1646 bool refersToEnclosingScope = 1647 (CurContext != D->getDeclContext() && 1648 D->getDeclContext()->isFunctionOrMethod()) || 1649 (isa<VarDecl>(D) && 1650 cast<VarDecl>(D)->isInitCapture()); 1651 1652 DeclRefExpr *E; 1653 if (isa<VarTemplateSpecializationDecl>(D)) { 1654 VarTemplateSpecializationDecl *VarSpec = 1655 cast<VarTemplateSpecializationDecl>(D); 1656 1657 E = DeclRefExpr::Create( 1658 Context, 1659 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1660 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1661 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1662 } else { 1663 assert(!TemplateArgs && "No template arguments for non-variable" 1664 " template specialization references"); 1665 E = DeclRefExpr::Create( 1666 Context, 1667 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1668 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1669 } 1670 1671 MarkDeclRefReferenced(E); 1672 1673 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1674 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1675 DiagnosticsEngine::Level Level = 1676 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1677 E->getLocStart()); 1678 if (Level != DiagnosticsEngine::Ignored) 1679 recordUseOfEvaluatedWeak(E); 1680 } 1681 1682 // Just in case we're building an illegal pointer-to-member. 1683 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1684 if (FD && FD->isBitField()) 1685 E->setObjectKind(OK_BitField); 1686 1687 return Owned(E); 1688 } 1689 1690 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1691 /// possibly a list of template arguments. 1692 /// 1693 /// If this produces template arguments, it is permitted to call 1694 /// DecomposeTemplateName. 1695 /// 1696 /// This actually loses a lot of source location information for 1697 /// non-standard name kinds; we should consider preserving that in 1698 /// some way. 1699 void 1700 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1701 TemplateArgumentListInfo &Buffer, 1702 DeclarationNameInfo &NameInfo, 1703 const TemplateArgumentListInfo *&TemplateArgs) { 1704 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1705 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1706 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1707 1708 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1709 Id.TemplateId->NumArgs); 1710 translateTemplateArguments(TemplateArgsPtr, Buffer); 1711 1712 TemplateName TName = Id.TemplateId->Template.get(); 1713 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1714 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1715 TemplateArgs = &Buffer; 1716 } else { 1717 NameInfo = GetNameFromUnqualifiedId(Id); 1718 TemplateArgs = 0; 1719 } 1720 } 1721 1722 /// Diagnose an empty lookup. 1723 /// 1724 /// \return false if new lookup candidates were found 1725 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1726 CorrectionCandidateCallback &CCC, 1727 TemplateArgumentListInfo *ExplicitTemplateArgs, 1728 ArrayRef<Expr *> Args) { 1729 DeclarationName Name = R.getLookupName(); 1730 1731 unsigned diagnostic = diag::err_undeclared_var_use; 1732 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1733 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1734 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1735 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1736 diagnostic = diag::err_undeclared_use; 1737 diagnostic_suggest = diag::err_undeclared_use_suggest; 1738 } 1739 1740 // If the original lookup was an unqualified lookup, fake an 1741 // unqualified lookup. This is useful when (for example) the 1742 // original lookup would not have found something because it was a 1743 // dependent name. 1744 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1745 ? CurContext : 0; 1746 while (DC) { 1747 if (isa<CXXRecordDecl>(DC)) { 1748 LookupQualifiedName(R, DC); 1749 1750 if (!R.empty()) { 1751 // Don't give errors about ambiguities in this lookup. 1752 R.suppressDiagnostics(); 1753 1754 // During a default argument instantiation the CurContext points 1755 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1756 // function parameter list, hence add an explicit check. 1757 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1758 ActiveTemplateInstantiations.back().Kind == 1759 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1760 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1761 bool isInstance = CurMethod && 1762 CurMethod->isInstance() && 1763 DC == CurMethod->getParent() && !isDefaultArgument; 1764 1765 1766 // Give a code modification hint to insert 'this->'. 1767 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1768 // Actually quite difficult! 1769 if (getLangOpts().MSVCCompat) 1770 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1771 if (isInstance) { 1772 Diag(R.getNameLoc(), diagnostic) << Name 1773 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1774 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1775 CallsUndergoingInstantiation.back()->getCallee()); 1776 1777 CXXMethodDecl *DepMethod; 1778 if (CurMethod->isDependentContext()) 1779 DepMethod = CurMethod; 1780 else if (CurMethod->getTemplatedKind() == 1781 FunctionDecl::TK_FunctionTemplateSpecialization) 1782 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1783 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1784 else 1785 DepMethod = cast<CXXMethodDecl>( 1786 CurMethod->getInstantiatedFromMemberFunction()); 1787 assert(DepMethod && "No template pattern found"); 1788 1789 QualType DepThisType = DepMethod->getThisType(Context); 1790 CheckCXXThisCapture(R.getNameLoc()); 1791 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1792 R.getNameLoc(), DepThisType, false); 1793 TemplateArgumentListInfo TList; 1794 if (ULE->hasExplicitTemplateArgs()) 1795 ULE->copyTemplateArgumentsInto(TList); 1796 1797 CXXScopeSpec SS; 1798 SS.Adopt(ULE->getQualifierLoc()); 1799 CXXDependentScopeMemberExpr *DepExpr = 1800 CXXDependentScopeMemberExpr::Create( 1801 Context, DepThis, DepThisType, true, SourceLocation(), 1802 SS.getWithLocInContext(Context), 1803 ULE->getTemplateKeywordLoc(), 0, 1804 R.getLookupNameInfo(), 1805 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1806 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1807 } else { 1808 Diag(R.getNameLoc(), diagnostic) << Name; 1809 } 1810 1811 // Do we really want to note all of these? 1812 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1813 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1814 1815 // Return true if we are inside a default argument instantiation 1816 // and the found name refers to an instance member function, otherwise 1817 // the function calling DiagnoseEmptyLookup will try to create an 1818 // implicit member call and this is wrong for default argument. 1819 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1820 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1821 return true; 1822 } 1823 1824 // Tell the callee to try to recover. 1825 return false; 1826 } 1827 1828 R.clear(); 1829 } 1830 1831 // In Microsoft mode, if we are performing lookup from within a friend 1832 // function definition declared at class scope then we must set 1833 // DC to the lexical parent to be able to search into the parent 1834 // class. 1835 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1836 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1837 DC->getLexicalParent()->isRecord()) 1838 DC = DC->getLexicalParent(); 1839 else 1840 DC = DC->getParent(); 1841 } 1842 1843 // We didn't find anything, so try to correct for a typo. 1844 TypoCorrection Corrected; 1845 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1846 S, &SS, CCC))) { 1847 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1848 bool DroppedSpecifier = 1849 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1850 R.setLookupName(Corrected.getCorrection()); 1851 1852 bool AcceptableWithRecovery = false; 1853 bool AcceptableWithoutRecovery = false; 1854 NamedDecl *ND = Corrected.getCorrectionDecl(); 1855 if (ND) { 1856 if (Corrected.isOverloaded()) { 1857 OverloadCandidateSet OCS(R.getNameLoc()); 1858 OverloadCandidateSet::iterator Best; 1859 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1860 CDEnd = Corrected.end(); 1861 CD != CDEnd; ++CD) { 1862 if (FunctionTemplateDecl *FTD = 1863 dyn_cast<FunctionTemplateDecl>(*CD)) 1864 AddTemplateOverloadCandidate( 1865 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1866 Args, OCS); 1867 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1868 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1869 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1870 Args, OCS); 1871 } 1872 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1873 case OR_Success: 1874 ND = Best->Function; 1875 Corrected.setCorrectionDecl(ND); 1876 break; 1877 default: 1878 // FIXME: Arbitrarily pick the first declaration for the note. 1879 Corrected.setCorrectionDecl(ND); 1880 break; 1881 } 1882 } 1883 R.addDecl(ND); 1884 1885 AcceptableWithRecovery = 1886 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1887 // FIXME: If we ended up with a typo for a type name or 1888 // Objective-C class name, we're in trouble because the parser 1889 // is in the wrong place to recover. Suggest the typo 1890 // correction, but don't make it a fix-it since we're not going 1891 // to recover well anyway. 1892 AcceptableWithoutRecovery = 1893 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1894 } else { 1895 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1896 // because we aren't able to recover. 1897 AcceptableWithoutRecovery = true; 1898 } 1899 1900 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1901 unsigned NoteID = (Corrected.getCorrectionDecl() && 1902 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1903 ? diag::note_implicit_param_decl 1904 : diag::note_previous_decl; 1905 if (SS.isEmpty()) 1906 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1907 PDiag(NoteID), AcceptableWithRecovery); 1908 else 1909 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1910 << Name << computeDeclContext(SS, false) 1911 << DroppedSpecifier << SS.getRange(), 1912 PDiag(NoteID), AcceptableWithRecovery); 1913 1914 // Tell the callee whether to try to recover. 1915 return !AcceptableWithRecovery; 1916 } 1917 } 1918 R.clear(); 1919 1920 // Emit a special diagnostic for failed member lookups. 1921 // FIXME: computing the declaration context might fail here (?) 1922 if (!SS.isEmpty()) { 1923 Diag(R.getNameLoc(), diag::err_no_member) 1924 << Name << computeDeclContext(SS, false) 1925 << SS.getRange(); 1926 return true; 1927 } 1928 1929 // Give up, we can't recover. 1930 Diag(R.getNameLoc(), diagnostic) << Name; 1931 return true; 1932 } 1933 1934 ExprResult Sema::ActOnIdExpression(Scope *S, 1935 CXXScopeSpec &SS, 1936 SourceLocation TemplateKWLoc, 1937 UnqualifiedId &Id, 1938 bool HasTrailingLParen, 1939 bool IsAddressOfOperand, 1940 CorrectionCandidateCallback *CCC, 1941 bool IsInlineAsmIdentifier) { 1942 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1943 "cannot be direct & operand and have a trailing lparen"); 1944 if (SS.isInvalid()) 1945 return ExprError(); 1946 1947 TemplateArgumentListInfo TemplateArgsBuffer; 1948 1949 // Decompose the UnqualifiedId into the following data. 1950 DeclarationNameInfo NameInfo; 1951 const TemplateArgumentListInfo *TemplateArgs; 1952 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1953 1954 DeclarationName Name = NameInfo.getName(); 1955 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1956 SourceLocation NameLoc = NameInfo.getLoc(); 1957 1958 // C++ [temp.dep.expr]p3: 1959 // An id-expression is type-dependent if it contains: 1960 // -- an identifier that was declared with a dependent type, 1961 // (note: handled after lookup) 1962 // -- a template-id that is dependent, 1963 // (note: handled in BuildTemplateIdExpr) 1964 // -- a conversion-function-id that specifies a dependent type, 1965 // -- a nested-name-specifier that contains a class-name that 1966 // names a dependent type. 1967 // Determine whether this is a member of an unknown specialization; 1968 // we need to handle these differently. 1969 bool DependentID = false; 1970 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1971 Name.getCXXNameType()->isDependentType()) { 1972 DependentID = true; 1973 } else if (SS.isSet()) { 1974 if (DeclContext *DC = computeDeclContext(SS, false)) { 1975 if (RequireCompleteDeclContext(SS, DC)) 1976 return ExprError(); 1977 } else { 1978 DependentID = true; 1979 } 1980 } 1981 1982 if (DependentID) 1983 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1984 IsAddressOfOperand, TemplateArgs); 1985 1986 // Perform the required lookup. 1987 LookupResult R(*this, NameInfo, 1988 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1989 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1990 if (TemplateArgs) { 1991 // Lookup the template name again to correctly establish the context in 1992 // which it was found. This is really unfortunate as we already did the 1993 // lookup to determine that it was a template name in the first place. If 1994 // this becomes a performance hit, we can work harder to preserve those 1995 // results until we get here but it's likely not worth it. 1996 bool MemberOfUnknownSpecialization; 1997 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1998 MemberOfUnknownSpecialization); 1999 2000 if (MemberOfUnknownSpecialization || 2001 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2002 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2003 IsAddressOfOperand, TemplateArgs); 2004 } else { 2005 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2006 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2007 2008 // If the result might be in a dependent base class, this is a dependent 2009 // id-expression. 2010 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2011 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2012 IsAddressOfOperand, TemplateArgs); 2013 2014 // If this reference is in an Objective-C method, then we need to do 2015 // some special Objective-C lookup, too. 2016 if (IvarLookupFollowUp) { 2017 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2018 if (E.isInvalid()) 2019 return ExprError(); 2020 2021 if (Expr *Ex = E.takeAs<Expr>()) 2022 return Owned(Ex); 2023 } 2024 } 2025 2026 if (R.isAmbiguous()) 2027 return ExprError(); 2028 2029 // Determine whether this name might be a candidate for 2030 // argument-dependent lookup. 2031 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2032 2033 if (R.empty() && !ADL) { 2034 2035 // Otherwise, this could be an implicitly declared function reference (legal 2036 // in C90, extension in C99, forbidden in C++). 2037 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2038 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2039 if (D) R.addDecl(D); 2040 } 2041 2042 // If this name wasn't predeclared and if this is not a function 2043 // call, diagnose the problem. 2044 if (R.empty()) { 2045 // In Microsoft mode, if we are inside a template class member function 2046 // whose parent class has dependent base classes, and we can't resolve 2047 // an identifier, then assume the identifier is a member of a dependent 2048 // base class. The goal is to postpone name lookup to instantiation time 2049 // to be able to search into the type dependent base classes. 2050 // FIXME: If we want 100% compatibility with MSVC, we will have delay all 2051 // unqualified name lookup. Any name lookup during template parsing means 2052 // clang might find something that MSVC doesn't. For now, we only handle 2053 // the common case of members of a dependent base class. 2054 if (getLangOpts().MSVCCompat) { 2055 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 2056 if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) { 2057 assert(SS.isEmpty() && "qualifiers should be already handled"); 2058 QualType ThisType = MD->getThisType(Context); 2059 // Since the 'this' expression is synthesized, we don't need to 2060 // perform the double-lookup check. 2061 NamedDecl *FirstQualifierInScope = 0; 2062 return Owned(CXXDependentScopeMemberExpr::Create( 2063 Context, /*This=*/0, ThisType, /*IsArrow=*/true, 2064 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), 2065 TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs)); 2066 } 2067 } 2068 2069 // Don't diagnose an empty lookup for inline assmebly. 2070 if (IsInlineAsmIdentifier) 2071 return ExprError(); 2072 2073 CorrectionCandidateCallback DefaultValidator; 2074 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2075 return ExprError(); 2076 2077 assert(!R.empty() && 2078 "DiagnoseEmptyLookup returned false but added no results"); 2079 2080 // If we found an Objective-C instance variable, let 2081 // LookupInObjCMethod build the appropriate expression to 2082 // reference the ivar. 2083 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2084 R.clear(); 2085 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2086 // In a hopelessly buggy code, Objective-C instance variable 2087 // lookup fails and no expression will be built to reference it. 2088 if (!E.isInvalid() && !E.get()) 2089 return ExprError(); 2090 return E; 2091 } 2092 } 2093 } 2094 2095 // This is guaranteed from this point on. 2096 assert(!R.empty() || ADL); 2097 2098 // Check whether this might be a C++ implicit instance member access. 2099 // C++ [class.mfct.non-static]p3: 2100 // When an id-expression that is not part of a class member access 2101 // syntax and not used to form a pointer to member is used in the 2102 // body of a non-static member function of class X, if name lookup 2103 // resolves the name in the id-expression to a non-static non-type 2104 // member of some class C, the id-expression is transformed into a 2105 // class member access expression using (*this) as the 2106 // postfix-expression to the left of the . operator. 2107 // 2108 // But we don't actually need to do this for '&' operands if R 2109 // resolved to a function or overloaded function set, because the 2110 // expression is ill-formed if it actually works out to be a 2111 // non-static member function: 2112 // 2113 // C++ [expr.ref]p4: 2114 // Otherwise, if E1.E2 refers to a non-static member function. . . 2115 // [t]he expression can be used only as the left-hand operand of a 2116 // member function call. 2117 // 2118 // There are other safeguards against such uses, but it's important 2119 // to get this right here so that we don't end up making a 2120 // spuriously dependent expression if we're inside a dependent 2121 // instance method. 2122 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2123 bool MightBeImplicitMember; 2124 if (!IsAddressOfOperand) 2125 MightBeImplicitMember = true; 2126 else if (!SS.isEmpty()) 2127 MightBeImplicitMember = false; 2128 else if (R.isOverloadedResult()) 2129 MightBeImplicitMember = false; 2130 else if (R.isUnresolvableResult()) 2131 MightBeImplicitMember = true; 2132 else 2133 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2134 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2135 isa<MSPropertyDecl>(R.getFoundDecl()); 2136 2137 if (MightBeImplicitMember) 2138 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2139 R, TemplateArgs); 2140 } 2141 2142 if (TemplateArgs || TemplateKWLoc.isValid()) { 2143 2144 // In C++1y, if this is a variable template id, then check it 2145 // in BuildTemplateIdExpr(). 2146 // The single lookup result must be a variable template declaration. 2147 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2148 Id.TemplateId->Kind == TNK_Var_template) { 2149 assert(R.getAsSingle<VarTemplateDecl>() && 2150 "There should only be one declaration found."); 2151 } 2152 2153 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2154 } 2155 2156 return BuildDeclarationNameExpr(SS, R, ADL); 2157 } 2158 2159 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2160 /// declaration name, generally during template instantiation. 2161 /// There's a large number of things which don't need to be done along 2162 /// this path. 2163 ExprResult 2164 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2165 const DeclarationNameInfo &NameInfo, 2166 bool IsAddressOfOperand) { 2167 DeclContext *DC = computeDeclContext(SS, false); 2168 if (!DC) 2169 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2170 NameInfo, /*TemplateArgs=*/0); 2171 2172 if (RequireCompleteDeclContext(SS, DC)) 2173 return ExprError(); 2174 2175 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2176 LookupQualifiedName(R, DC); 2177 2178 if (R.isAmbiguous()) 2179 return ExprError(); 2180 2181 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2182 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2183 NameInfo, /*TemplateArgs=*/0); 2184 2185 if (R.empty()) { 2186 Diag(NameInfo.getLoc(), diag::err_no_member) 2187 << NameInfo.getName() << DC << SS.getRange(); 2188 return ExprError(); 2189 } 2190 2191 // Defend against this resolving to an implicit member access. We usually 2192 // won't get here if this might be a legitimate a class member (we end up in 2193 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2194 // a pointer-to-member or in an unevaluated context in C++11. 2195 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2196 return BuildPossibleImplicitMemberExpr(SS, 2197 /*TemplateKWLoc=*/SourceLocation(), 2198 R, /*TemplateArgs=*/0); 2199 2200 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2201 } 2202 2203 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2204 /// detected that we're currently inside an ObjC method. Perform some 2205 /// additional lookup. 2206 /// 2207 /// Ideally, most of this would be done by lookup, but there's 2208 /// actually quite a lot of extra work involved. 2209 /// 2210 /// Returns a null sentinel to indicate trivial success. 2211 ExprResult 2212 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2213 IdentifierInfo *II, bool AllowBuiltinCreation) { 2214 SourceLocation Loc = Lookup.getNameLoc(); 2215 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2216 2217 // Check for error condition which is already reported. 2218 if (!CurMethod) 2219 return ExprError(); 2220 2221 // There are two cases to handle here. 1) scoped lookup could have failed, 2222 // in which case we should look for an ivar. 2) scoped lookup could have 2223 // found a decl, but that decl is outside the current instance method (i.e. 2224 // a global variable). In these two cases, we do a lookup for an ivar with 2225 // this name, if the lookup sucedes, we replace it our current decl. 2226 2227 // If we're in a class method, we don't normally want to look for 2228 // ivars. But if we don't find anything else, and there's an 2229 // ivar, that's an error. 2230 bool IsClassMethod = CurMethod->isClassMethod(); 2231 2232 bool LookForIvars; 2233 if (Lookup.empty()) 2234 LookForIvars = true; 2235 else if (IsClassMethod) 2236 LookForIvars = false; 2237 else 2238 LookForIvars = (Lookup.isSingleResult() && 2239 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2240 ObjCInterfaceDecl *IFace = 0; 2241 if (LookForIvars) { 2242 IFace = CurMethod->getClassInterface(); 2243 ObjCInterfaceDecl *ClassDeclared; 2244 ObjCIvarDecl *IV = 0; 2245 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2246 // Diagnose using an ivar in a class method. 2247 if (IsClassMethod) 2248 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2249 << IV->getDeclName()); 2250 2251 // If we're referencing an invalid decl, just return this as a silent 2252 // error node. The error diagnostic was already emitted on the decl. 2253 if (IV->isInvalidDecl()) 2254 return ExprError(); 2255 2256 // Check if referencing a field with __attribute__((deprecated)). 2257 if (DiagnoseUseOfDecl(IV, Loc)) 2258 return ExprError(); 2259 2260 // Diagnose the use of an ivar outside of the declaring class. 2261 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2262 !declaresSameEntity(ClassDeclared, IFace) && 2263 !getLangOpts().DebuggerSupport) 2264 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2265 2266 // FIXME: This should use a new expr for a direct reference, don't 2267 // turn this into Self->ivar, just return a BareIVarExpr or something. 2268 IdentifierInfo &II = Context.Idents.get("self"); 2269 UnqualifiedId SelfName; 2270 SelfName.setIdentifier(&II, SourceLocation()); 2271 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2272 CXXScopeSpec SelfScopeSpec; 2273 SourceLocation TemplateKWLoc; 2274 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2275 SelfName, false, false); 2276 if (SelfExpr.isInvalid()) 2277 return ExprError(); 2278 2279 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2280 if (SelfExpr.isInvalid()) 2281 return ExprError(); 2282 2283 MarkAnyDeclReferenced(Loc, IV, true); 2284 2285 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2286 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2287 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2288 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2289 2290 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2291 Loc, IV->getLocation(), 2292 SelfExpr.take(), 2293 true, true); 2294 2295 if (getLangOpts().ObjCAutoRefCount) { 2296 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2297 DiagnosticsEngine::Level Level = 2298 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2299 if (Level != DiagnosticsEngine::Ignored) 2300 recordUseOfEvaluatedWeak(Result); 2301 } 2302 if (CurContext->isClosure()) 2303 Diag(Loc, diag::warn_implicitly_retains_self) 2304 << FixItHint::CreateInsertion(Loc, "self->"); 2305 } 2306 2307 return Owned(Result); 2308 } 2309 } else if (CurMethod->isInstanceMethod()) { 2310 // We should warn if a local variable hides an ivar. 2311 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2312 ObjCInterfaceDecl *ClassDeclared; 2313 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2314 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2315 declaresSameEntity(IFace, ClassDeclared)) 2316 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2317 } 2318 } 2319 } else if (Lookup.isSingleResult() && 2320 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2321 // If accessing a stand-alone ivar in a class method, this is an error. 2322 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2323 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2324 << IV->getDeclName()); 2325 } 2326 2327 if (Lookup.empty() && II && AllowBuiltinCreation) { 2328 // FIXME. Consolidate this with similar code in LookupName. 2329 if (unsigned BuiltinID = II->getBuiltinID()) { 2330 if (!(getLangOpts().CPlusPlus && 2331 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2332 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2333 S, Lookup.isForRedeclaration(), 2334 Lookup.getNameLoc()); 2335 if (D) Lookup.addDecl(D); 2336 } 2337 } 2338 } 2339 // Sentinel value saying that we didn't do anything special. 2340 return Owned((Expr*) 0); 2341 } 2342 2343 /// \brief Cast a base object to a member's actual type. 2344 /// 2345 /// Logically this happens in three phases: 2346 /// 2347 /// * First we cast from the base type to the naming class. 2348 /// The naming class is the class into which we were looking 2349 /// when we found the member; it's the qualifier type if a 2350 /// qualifier was provided, and otherwise it's the base type. 2351 /// 2352 /// * Next we cast from the naming class to the declaring class. 2353 /// If the member we found was brought into a class's scope by 2354 /// a using declaration, this is that class; otherwise it's 2355 /// the class declaring the member. 2356 /// 2357 /// * Finally we cast from the declaring class to the "true" 2358 /// declaring class of the member. This conversion does not 2359 /// obey access control. 2360 ExprResult 2361 Sema::PerformObjectMemberConversion(Expr *From, 2362 NestedNameSpecifier *Qualifier, 2363 NamedDecl *FoundDecl, 2364 NamedDecl *Member) { 2365 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2366 if (!RD) 2367 return Owned(From); 2368 2369 QualType DestRecordType; 2370 QualType DestType; 2371 QualType FromRecordType; 2372 QualType FromType = From->getType(); 2373 bool PointerConversions = false; 2374 if (isa<FieldDecl>(Member)) { 2375 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2376 2377 if (FromType->getAs<PointerType>()) { 2378 DestType = Context.getPointerType(DestRecordType); 2379 FromRecordType = FromType->getPointeeType(); 2380 PointerConversions = true; 2381 } else { 2382 DestType = DestRecordType; 2383 FromRecordType = FromType; 2384 } 2385 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2386 if (Method->isStatic()) 2387 return Owned(From); 2388 2389 DestType = Method->getThisType(Context); 2390 DestRecordType = DestType->getPointeeType(); 2391 2392 if (FromType->getAs<PointerType>()) { 2393 FromRecordType = FromType->getPointeeType(); 2394 PointerConversions = true; 2395 } else { 2396 FromRecordType = FromType; 2397 DestType = DestRecordType; 2398 } 2399 } else { 2400 // No conversion necessary. 2401 return Owned(From); 2402 } 2403 2404 if (DestType->isDependentType() || FromType->isDependentType()) 2405 return Owned(From); 2406 2407 // If the unqualified types are the same, no conversion is necessary. 2408 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2409 return Owned(From); 2410 2411 SourceRange FromRange = From->getSourceRange(); 2412 SourceLocation FromLoc = FromRange.getBegin(); 2413 2414 ExprValueKind VK = From->getValueKind(); 2415 2416 // C++ [class.member.lookup]p8: 2417 // [...] Ambiguities can often be resolved by qualifying a name with its 2418 // class name. 2419 // 2420 // If the member was a qualified name and the qualified referred to a 2421 // specific base subobject type, we'll cast to that intermediate type 2422 // first and then to the object in which the member is declared. That allows 2423 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2424 // 2425 // class Base { public: int x; }; 2426 // class Derived1 : public Base { }; 2427 // class Derived2 : public Base { }; 2428 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2429 // 2430 // void VeryDerived::f() { 2431 // x = 17; // error: ambiguous base subobjects 2432 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2433 // } 2434 if (Qualifier && Qualifier->getAsType()) { 2435 QualType QType = QualType(Qualifier->getAsType(), 0); 2436 assert(QType->isRecordType() && "lookup done with non-record type"); 2437 2438 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2439 2440 // In C++98, the qualifier type doesn't actually have to be a base 2441 // type of the object type, in which case we just ignore it. 2442 // Otherwise build the appropriate casts. 2443 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2444 CXXCastPath BasePath; 2445 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2446 FromLoc, FromRange, &BasePath)) 2447 return ExprError(); 2448 2449 if (PointerConversions) 2450 QType = Context.getPointerType(QType); 2451 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2452 VK, &BasePath).take(); 2453 2454 FromType = QType; 2455 FromRecordType = QRecordType; 2456 2457 // If the qualifier type was the same as the destination type, 2458 // we're done. 2459 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2460 return Owned(From); 2461 } 2462 } 2463 2464 bool IgnoreAccess = false; 2465 2466 // If we actually found the member through a using declaration, cast 2467 // down to the using declaration's type. 2468 // 2469 // Pointer equality is fine here because only one declaration of a 2470 // class ever has member declarations. 2471 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2472 assert(isa<UsingShadowDecl>(FoundDecl)); 2473 QualType URecordType = Context.getTypeDeclType( 2474 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2475 2476 // We only need to do this if the naming-class to declaring-class 2477 // conversion is non-trivial. 2478 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2479 assert(IsDerivedFrom(FromRecordType, URecordType)); 2480 CXXCastPath BasePath; 2481 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2482 FromLoc, FromRange, &BasePath)) 2483 return ExprError(); 2484 2485 QualType UType = URecordType; 2486 if (PointerConversions) 2487 UType = Context.getPointerType(UType); 2488 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2489 VK, &BasePath).take(); 2490 FromType = UType; 2491 FromRecordType = URecordType; 2492 } 2493 2494 // We don't do access control for the conversion from the 2495 // declaring class to the true declaring class. 2496 IgnoreAccess = true; 2497 } 2498 2499 CXXCastPath BasePath; 2500 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2501 FromLoc, FromRange, &BasePath, 2502 IgnoreAccess)) 2503 return ExprError(); 2504 2505 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2506 VK, &BasePath); 2507 } 2508 2509 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2510 const LookupResult &R, 2511 bool HasTrailingLParen) { 2512 // Only when used directly as the postfix-expression of a call. 2513 if (!HasTrailingLParen) 2514 return false; 2515 2516 // Never if a scope specifier was provided. 2517 if (SS.isSet()) 2518 return false; 2519 2520 // Only in C++ or ObjC++. 2521 if (!getLangOpts().CPlusPlus) 2522 return false; 2523 2524 // Turn off ADL when we find certain kinds of declarations during 2525 // normal lookup: 2526 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2527 NamedDecl *D = *I; 2528 2529 // C++0x [basic.lookup.argdep]p3: 2530 // -- a declaration of a class member 2531 // Since using decls preserve this property, we check this on the 2532 // original decl. 2533 if (D->isCXXClassMember()) 2534 return false; 2535 2536 // C++0x [basic.lookup.argdep]p3: 2537 // -- a block-scope function declaration that is not a 2538 // using-declaration 2539 // NOTE: we also trigger this for function templates (in fact, we 2540 // don't check the decl type at all, since all other decl types 2541 // turn off ADL anyway). 2542 if (isa<UsingShadowDecl>(D)) 2543 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2544 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2545 return false; 2546 2547 // C++0x [basic.lookup.argdep]p3: 2548 // -- a declaration that is neither a function or a function 2549 // template 2550 // And also for builtin functions. 2551 if (isa<FunctionDecl>(D)) { 2552 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2553 2554 // But also builtin functions. 2555 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2556 return false; 2557 } else if (!isa<FunctionTemplateDecl>(D)) 2558 return false; 2559 } 2560 2561 return true; 2562 } 2563 2564 2565 /// Diagnoses obvious problems with the use of the given declaration 2566 /// as an expression. This is only actually called for lookups that 2567 /// were not overloaded, and it doesn't promise that the declaration 2568 /// will in fact be used. 2569 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2570 if (isa<TypedefNameDecl>(D)) { 2571 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2572 return true; 2573 } 2574 2575 if (isa<ObjCInterfaceDecl>(D)) { 2576 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2577 return true; 2578 } 2579 2580 if (isa<NamespaceDecl>(D)) { 2581 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2582 return true; 2583 } 2584 2585 return false; 2586 } 2587 2588 ExprResult 2589 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2590 LookupResult &R, 2591 bool NeedsADL) { 2592 // If this is a single, fully-resolved result and we don't need ADL, 2593 // just build an ordinary singleton decl ref. 2594 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2595 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2596 R.getRepresentativeDecl()); 2597 2598 // We only need to check the declaration if there's exactly one 2599 // result, because in the overloaded case the results can only be 2600 // functions and function templates. 2601 if (R.isSingleResult() && 2602 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2603 return ExprError(); 2604 2605 // Otherwise, just build an unresolved lookup expression. Suppress 2606 // any lookup-related diagnostics; we'll hash these out later, when 2607 // we've picked a target. 2608 R.suppressDiagnostics(); 2609 2610 UnresolvedLookupExpr *ULE 2611 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2612 SS.getWithLocInContext(Context), 2613 R.getLookupNameInfo(), 2614 NeedsADL, R.isOverloadedResult(), 2615 R.begin(), R.end()); 2616 2617 return Owned(ULE); 2618 } 2619 2620 /// \brief Complete semantic analysis for a reference to the given declaration. 2621 ExprResult Sema::BuildDeclarationNameExpr( 2622 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2623 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2624 assert(D && "Cannot refer to a NULL declaration"); 2625 assert(!isa<FunctionTemplateDecl>(D) && 2626 "Cannot refer unambiguously to a function template"); 2627 2628 SourceLocation Loc = NameInfo.getLoc(); 2629 if (CheckDeclInExpr(*this, Loc, D)) 2630 return ExprError(); 2631 2632 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2633 // Specifically diagnose references to class templates that are missing 2634 // a template argument list. 2635 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2636 << Template << SS.getRange(); 2637 Diag(Template->getLocation(), diag::note_template_decl_here); 2638 return ExprError(); 2639 } 2640 2641 // Make sure that we're referring to a value. 2642 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2643 if (!VD) { 2644 Diag(Loc, diag::err_ref_non_value) 2645 << D << SS.getRange(); 2646 Diag(D->getLocation(), diag::note_declared_at); 2647 return ExprError(); 2648 } 2649 2650 // Check whether this declaration can be used. Note that we suppress 2651 // this check when we're going to perform argument-dependent lookup 2652 // on this function name, because this might not be the function 2653 // that overload resolution actually selects. 2654 if (DiagnoseUseOfDecl(VD, Loc)) 2655 return ExprError(); 2656 2657 // Only create DeclRefExpr's for valid Decl's. 2658 if (VD->isInvalidDecl()) 2659 return ExprError(); 2660 2661 // Handle members of anonymous structs and unions. If we got here, 2662 // and the reference is to a class member indirect field, then this 2663 // must be the subject of a pointer-to-member expression. 2664 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2665 if (!indirectField->isCXXClassMember()) 2666 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2667 indirectField); 2668 2669 { 2670 QualType type = VD->getType(); 2671 ExprValueKind valueKind = VK_RValue; 2672 2673 switch (D->getKind()) { 2674 // Ignore all the non-ValueDecl kinds. 2675 #define ABSTRACT_DECL(kind) 2676 #define VALUE(type, base) 2677 #define DECL(type, base) \ 2678 case Decl::type: 2679 #include "clang/AST/DeclNodes.inc" 2680 llvm_unreachable("invalid value decl kind"); 2681 2682 // These shouldn't make it here. 2683 case Decl::ObjCAtDefsField: 2684 case Decl::ObjCIvar: 2685 llvm_unreachable("forming non-member reference to ivar?"); 2686 2687 // Enum constants are always r-values and never references. 2688 // Unresolved using declarations are dependent. 2689 case Decl::EnumConstant: 2690 case Decl::UnresolvedUsingValue: 2691 valueKind = VK_RValue; 2692 break; 2693 2694 // Fields and indirect fields that got here must be for 2695 // pointer-to-member expressions; we just call them l-values for 2696 // internal consistency, because this subexpression doesn't really 2697 // exist in the high-level semantics. 2698 case Decl::Field: 2699 case Decl::IndirectField: 2700 assert(getLangOpts().CPlusPlus && 2701 "building reference to field in C?"); 2702 2703 // These can't have reference type in well-formed programs, but 2704 // for internal consistency we do this anyway. 2705 type = type.getNonReferenceType(); 2706 valueKind = VK_LValue; 2707 break; 2708 2709 // Non-type template parameters are either l-values or r-values 2710 // depending on the type. 2711 case Decl::NonTypeTemplateParm: { 2712 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2713 type = reftype->getPointeeType(); 2714 valueKind = VK_LValue; // even if the parameter is an r-value reference 2715 break; 2716 } 2717 2718 // For non-references, we need to strip qualifiers just in case 2719 // the template parameter was declared as 'const int' or whatever. 2720 valueKind = VK_RValue; 2721 type = type.getUnqualifiedType(); 2722 break; 2723 } 2724 2725 case Decl::Var: 2726 case Decl::VarTemplateSpecialization: 2727 case Decl::VarTemplatePartialSpecialization: 2728 // In C, "extern void blah;" is valid and is an r-value. 2729 if (!getLangOpts().CPlusPlus && 2730 !type.hasQualifiers() && 2731 type->isVoidType()) { 2732 valueKind = VK_RValue; 2733 break; 2734 } 2735 // fallthrough 2736 2737 case Decl::ImplicitParam: 2738 case Decl::ParmVar: { 2739 // These are always l-values. 2740 valueKind = VK_LValue; 2741 type = type.getNonReferenceType(); 2742 2743 // FIXME: Does the addition of const really only apply in 2744 // potentially-evaluated contexts? Since the variable isn't actually 2745 // captured in an unevaluated context, it seems that the answer is no. 2746 if (!isUnevaluatedContext()) { 2747 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2748 if (!CapturedType.isNull()) 2749 type = CapturedType; 2750 } 2751 2752 break; 2753 } 2754 2755 case Decl::Function: { 2756 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2757 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2758 type = Context.BuiltinFnTy; 2759 valueKind = VK_RValue; 2760 break; 2761 } 2762 } 2763 2764 const FunctionType *fty = type->castAs<FunctionType>(); 2765 2766 // If we're referring to a function with an __unknown_anytype 2767 // result type, make the entire expression __unknown_anytype. 2768 if (fty->getReturnType() == Context.UnknownAnyTy) { 2769 type = Context.UnknownAnyTy; 2770 valueKind = VK_RValue; 2771 break; 2772 } 2773 2774 // Functions are l-values in C++. 2775 if (getLangOpts().CPlusPlus) { 2776 valueKind = VK_LValue; 2777 break; 2778 } 2779 2780 // C99 DR 316 says that, if a function type comes from a 2781 // function definition (without a prototype), that type is only 2782 // used for checking compatibility. Therefore, when referencing 2783 // the function, we pretend that we don't have the full function 2784 // type. 2785 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2786 isa<FunctionProtoType>(fty)) 2787 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2788 fty->getExtInfo()); 2789 2790 // Functions are r-values in C. 2791 valueKind = VK_RValue; 2792 break; 2793 } 2794 2795 case Decl::MSProperty: 2796 valueKind = VK_LValue; 2797 break; 2798 2799 case Decl::CXXMethod: 2800 // If we're referring to a method with an __unknown_anytype 2801 // result type, make the entire expression __unknown_anytype. 2802 // This should only be possible with a type written directly. 2803 if (const FunctionProtoType *proto 2804 = dyn_cast<FunctionProtoType>(VD->getType())) 2805 if (proto->getReturnType() == Context.UnknownAnyTy) { 2806 type = Context.UnknownAnyTy; 2807 valueKind = VK_RValue; 2808 break; 2809 } 2810 2811 // C++ methods are l-values if static, r-values if non-static. 2812 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2813 valueKind = VK_LValue; 2814 break; 2815 } 2816 // fallthrough 2817 2818 case Decl::CXXConversion: 2819 case Decl::CXXDestructor: 2820 case Decl::CXXConstructor: 2821 valueKind = VK_RValue; 2822 break; 2823 } 2824 2825 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2826 TemplateArgs); 2827 } 2828 } 2829 2830 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2831 PredefinedExpr::IdentType IT) { 2832 // Pick the current block, lambda, captured statement or function. 2833 Decl *currentDecl = 0; 2834 if (const BlockScopeInfo *BSI = getCurBlock()) 2835 currentDecl = BSI->TheDecl; 2836 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2837 currentDecl = LSI->CallOperator; 2838 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2839 currentDecl = CSI->TheCapturedDecl; 2840 else 2841 currentDecl = getCurFunctionOrMethodDecl(); 2842 2843 if (!currentDecl) { 2844 Diag(Loc, diag::ext_predef_outside_function); 2845 currentDecl = Context.getTranslationUnitDecl(); 2846 } 2847 2848 QualType ResTy; 2849 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2850 ResTy = Context.DependentTy; 2851 else { 2852 // Pre-defined identifiers are of type char[x], where x is the length of 2853 // the string. 2854 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2855 2856 llvm::APInt LengthI(32, Length + 1); 2857 if (IT == PredefinedExpr::LFunction) 2858 ResTy = Context.WideCharTy.withConst(); 2859 else 2860 ResTy = Context.CharTy.withConst(); 2861 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2862 } 2863 2864 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2865 } 2866 2867 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2868 PredefinedExpr::IdentType IT; 2869 2870 switch (Kind) { 2871 default: llvm_unreachable("Unknown simple primary expr!"); 2872 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2873 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2874 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 2875 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2876 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2877 } 2878 2879 return BuildPredefinedExpr(Loc, IT); 2880 } 2881 2882 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2883 SmallString<16> CharBuffer; 2884 bool Invalid = false; 2885 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2886 if (Invalid) 2887 return ExprError(); 2888 2889 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2890 PP, Tok.getKind()); 2891 if (Literal.hadError()) 2892 return ExprError(); 2893 2894 QualType Ty; 2895 if (Literal.isWide()) 2896 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2897 else if (Literal.isUTF16()) 2898 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2899 else if (Literal.isUTF32()) 2900 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2901 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2902 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2903 else 2904 Ty = Context.CharTy; // 'x' -> char in C++ 2905 2906 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2907 if (Literal.isWide()) 2908 Kind = CharacterLiteral::Wide; 2909 else if (Literal.isUTF16()) 2910 Kind = CharacterLiteral::UTF16; 2911 else if (Literal.isUTF32()) 2912 Kind = CharacterLiteral::UTF32; 2913 2914 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2915 Tok.getLocation()); 2916 2917 if (Literal.getUDSuffix().empty()) 2918 return Owned(Lit); 2919 2920 // We're building a user-defined literal. 2921 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2922 SourceLocation UDSuffixLoc = 2923 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2924 2925 // Make sure we're allowed user-defined literals here. 2926 if (!UDLScope) 2927 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2928 2929 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2930 // operator "" X (ch) 2931 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2932 Lit, Tok.getLocation()); 2933 } 2934 2935 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2936 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2937 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2938 Context.IntTy, Loc)); 2939 } 2940 2941 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2942 QualType Ty, SourceLocation Loc) { 2943 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2944 2945 using llvm::APFloat; 2946 APFloat Val(Format); 2947 2948 APFloat::opStatus result = Literal.GetFloatValue(Val); 2949 2950 // Overflow is always an error, but underflow is only an error if 2951 // we underflowed to zero (APFloat reports denormals as underflow). 2952 if ((result & APFloat::opOverflow) || 2953 ((result & APFloat::opUnderflow) && Val.isZero())) { 2954 unsigned diagnostic; 2955 SmallString<20> buffer; 2956 if (result & APFloat::opOverflow) { 2957 diagnostic = diag::warn_float_overflow; 2958 APFloat::getLargest(Format).toString(buffer); 2959 } else { 2960 diagnostic = diag::warn_float_underflow; 2961 APFloat::getSmallest(Format).toString(buffer); 2962 } 2963 2964 S.Diag(Loc, diagnostic) 2965 << Ty 2966 << StringRef(buffer.data(), buffer.size()); 2967 } 2968 2969 bool isExact = (result == APFloat::opOK); 2970 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2971 } 2972 2973 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2974 // Fast path for a single digit (which is quite common). A single digit 2975 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2976 if (Tok.getLength() == 1) { 2977 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2978 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2979 } 2980 2981 SmallString<128> SpellingBuffer; 2982 // NumericLiteralParser wants to overread by one character. Add padding to 2983 // the buffer in case the token is copied to the buffer. If getSpelling() 2984 // returns a StringRef to the memory buffer, it should have a null char at 2985 // the EOF, so it is also safe. 2986 SpellingBuffer.resize(Tok.getLength() + 1); 2987 2988 // Get the spelling of the token, which eliminates trigraphs, etc. 2989 bool Invalid = false; 2990 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2991 if (Invalid) 2992 return ExprError(); 2993 2994 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2995 if (Literal.hadError) 2996 return ExprError(); 2997 2998 if (Literal.hasUDSuffix()) { 2999 // We're building a user-defined literal. 3000 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3001 SourceLocation UDSuffixLoc = 3002 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3003 3004 // Make sure we're allowed user-defined literals here. 3005 if (!UDLScope) 3006 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3007 3008 QualType CookedTy; 3009 if (Literal.isFloatingLiteral()) { 3010 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3011 // long double, the literal is treated as a call of the form 3012 // operator "" X (f L) 3013 CookedTy = Context.LongDoubleTy; 3014 } else { 3015 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3016 // unsigned long long, the literal is treated as a call of the form 3017 // operator "" X (n ULL) 3018 CookedTy = Context.UnsignedLongLongTy; 3019 } 3020 3021 DeclarationName OpName = 3022 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3023 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3024 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3025 3026 SourceLocation TokLoc = Tok.getLocation(); 3027 3028 // Perform literal operator lookup to determine if we're building a raw 3029 // literal or a cooked one. 3030 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3031 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3032 /*AllowRaw*/true, /*AllowTemplate*/true, 3033 /*AllowStringTemplate*/false)) { 3034 case LOLR_Error: 3035 return ExprError(); 3036 3037 case LOLR_Cooked: { 3038 Expr *Lit; 3039 if (Literal.isFloatingLiteral()) { 3040 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3041 } else { 3042 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3043 if (Literal.GetIntegerValue(ResultVal)) 3044 Diag(Tok.getLocation(), diag::err_integer_too_large); 3045 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3046 Tok.getLocation()); 3047 } 3048 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3049 } 3050 3051 case LOLR_Raw: { 3052 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3053 // literal is treated as a call of the form 3054 // operator "" X ("n") 3055 unsigned Length = Literal.getUDSuffixOffset(); 3056 QualType StrTy = Context.getConstantArrayType( 3057 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3058 ArrayType::Normal, 0); 3059 Expr *Lit = StringLiteral::Create( 3060 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3061 /*Pascal*/false, StrTy, &TokLoc, 1); 3062 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3063 } 3064 3065 case LOLR_Template: { 3066 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3067 // template), L is treated as a call fo the form 3068 // operator "" X <'c1', 'c2', ... 'ck'>() 3069 // where n is the source character sequence c1 c2 ... ck. 3070 TemplateArgumentListInfo ExplicitArgs; 3071 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3072 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3073 llvm::APSInt Value(CharBits, CharIsUnsigned); 3074 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3075 Value = TokSpelling[I]; 3076 TemplateArgument Arg(Context, Value, Context.CharTy); 3077 TemplateArgumentLocInfo ArgInfo; 3078 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3079 } 3080 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3081 &ExplicitArgs); 3082 } 3083 case LOLR_StringTemplate: 3084 llvm_unreachable("unexpected literal operator lookup result"); 3085 } 3086 } 3087 3088 Expr *Res; 3089 3090 if (Literal.isFloatingLiteral()) { 3091 QualType Ty; 3092 if (Literal.isFloat) 3093 Ty = Context.FloatTy; 3094 else if (!Literal.isLong) 3095 Ty = Context.DoubleTy; 3096 else 3097 Ty = Context.LongDoubleTy; 3098 3099 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3100 3101 if (Ty == Context.DoubleTy) { 3102 if (getLangOpts().SinglePrecisionConstants) { 3103 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3104 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3105 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3106 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3107 } 3108 } 3109 } else if (!Literal.isIntegerLiteral()) { 3110 return ExprError(); 3111 } else { 3112 QualType Ty; 3113 3114 // 'long long' is a C99 or C++11 feature. 3115 if (!getLangOpts().C99 && Literal.isLongLong) { 3116 if (getLangOpts().CPlusPlus) 3117 Diag(Tok.getLocation(), 3118 getLangOpts().CPlusPlus11 ? 3119 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3120 else 3121 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3122 } 3123 3124 // Get the value in the widest-possible width. 3125 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3126 // The microsoft literal suffix extensions support 128-bit literals, which 3127 // may be wider than [u]intmax_t. 3128 // FIXME: Actually, they don't. We seem to have accidentally invented the 3129 // i128 suffix. 3130 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 3131 PP.getTargetInfo().hasInt128Type()) 3132 MaxWidth = 128; 3133 llvm::APInt ResultVal(MaxWidth, 0); 3134 3135 if (Literal.GetIntegerValue(ResultVal)) { 3136 // If this value didn't fit into uintmax_t, error and force to ull. 3137 Diag(Tok.getLocation(), diag::err_integer_too_large); 3138 Ty = Context.UnsignedLongLongTy; 3139 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3140 "long long is not intmax_t?"); 3141 } else { 3142 // If this value fits into a ULL, try to figure out what else it fits into 3143 // according to the rules of C99 6.4.4.1p5. 3144 3145 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3146 // be an unsigned int. 3147 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3148 3149 // Check from smallest to largest, picking the smallest type we can. 3150 unsigned Width = 0; 3151 if (!Literal.isLong && !Literal.isLongLong) { 3152 // Are int/unsigned possibilities? 3153 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3154 3155 // Does it fit in a unsigned int? 3156 if (ResultVal.isIntN(IntSize)) { 3157 // Does it fit in a signed int? 3158 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3159 Ty = Context.IntTy; 3160 else if (AllowUnsigned) 3161 Ty = Context.UnsignedIntTy; 3162 Width = IntSize; 3163 } 3164 } 3165 3166 // Are long/unsigned long possibilities? 3167 if (Ty.isNull() && !Literal.isLongLong) { 3168 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3169 3170 // Does it fit in a unsigned long? 3171 if (ResultVal.isIntN(LongSize)) { 3172 // Does it fit in a signed long? 3173 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3174 Ty = Context.LongTy; 3175 else if (AllowUnsigned) 3176 Ty = Context.UnsignedLongTy; 3177 Width = LongSize; 3178 } 3179 } 3180 3181 // Check long long if needed. 3182 if (Ty.isNull()) { 3183 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3184 3185 // Does it fit in a unsigned long long? 3186 if (ResultVal.isIntN(LongLongSize)) { 3187 // Does it fit in a signed long long? 3188 // To be compatible with MSVC, hex integer literals ending with the 3189 // LL or i64 suffix are always signed in Microsoft mode. 3190 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3191 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3192 Ty = Context.LongLongTy; 3193 else if (AllowUnsigned) 3194 Ty = Context.UnsignedLongLongTy; 3195 Width = LongLongSize; 3196 } 3197 } 3198 3199 // If it doesn't fit in unsigned long long, and we're using Microsoft 3200 // extensions, then its a 128-bit integer literal. 3201 if (Ty.isNull() && Literal.isMicrosoftInteger && 3202 PP.getTargetInfo().hasInt128Type()) { 3203 if (Literal.isUnsigned) 3204 Ty = Context.UnsignedInt128Ty; 3205 else 3206 Ty = Context.Int128Ty; 3207 Width = 128; 3208 } 3209 3210 // If we still couldn't decide a type, we probably have something that 3211 // does not fit in a signed long long, but has no U suffix. 3212 if (Ty.isNull()) { 3213 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3214 Ty = Context.UnsignedLongLongTy; 3215 Width = Context.getTargetInfo().getLongLongWidth(); 3216 } 3217 3218 if (ResultVal.getBitWidth() != Width) 3219 ResultVal = ResultVal.trunc(Width); 3220 } 3221 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3222 } 3223 3224 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3225 if (Literal.isImaginary) 3226 Res = new (Context) ImaginaryLiteral(Res, 3227 Context.getComplexType(Res->getType())); 3228 3229 return Owned(Res); 3230 } 3231 3232 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3233 assert((E != 0) && "ActOnParenExpr() missing expr"); 3234 return Owned(new (Context) ParenExpr(L, R, E)); 3235 } 3236 3237 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3238 SourceLocation Loc, 3239 SourceRange ArgRange) { 3240 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3241 // scalar or vector data type argument..." 3242 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3243 // type (C99 6.2.5p18) or void. 3244 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3245 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3246 << T << ArgRange; 3247 return true; 3248 } 3249 3250 assert((T->isVoidType() || !T->isIncompleteType()) && 3251 "Scalar types should always be complete"); 3252 return false; 3253 } 3254 3255 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3256 SourceLocation Loc, 3257 SourceRange ArgRange, 3258 UnaryExprOrTypeTrait TraitKind) { 3259 // Invalid types must be hard errors for SFINAE in C++. 3260 if (S.LangOpts.CPlusPlus) 3261 return true; 3262 3263 // C99 6.5.3.4p1: 3264 if (T->isFunctionType() && 3265 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3266 // sizeof(function)/alignof(function) is allowed as an extension. 3267 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3268 << TraitKind << ArgRange; 3269 return false; 3270 } 3271 3272 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3273 // this is an error (OpenCL v1.1 s6.3.k) 3274 if (T->isVoidType()) { 3275 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3276 : diag::ext_sizeof_alignof_void_type; 3277 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3278 return false; 3279 } 3280 3281 return true; 3282 } 3283 3284 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3285 SourceLocation Loc, 3286 SourceRange ArgRange, 3287 UnaryExprOrTypeTrait TraitKind) { 3288 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3289 // runtime doesn't allow it. 3290 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3291 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3292 << T << (TraitKind == UETT_SizeOf) 3293 << ArgRange; 3294 return true; 3295 } 3296 3297 return false; 3298 } 3299 3300 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3301 /// pointer type is equal to T) and emit a warning if it is. 3302 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3303 Expr *E) { 3304 // Don't warn if the operation changed the type. 3305 if (T != E->getType()) 3306 return; 3307 3308 // Now look for array decays. 3309 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3310 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3311 return; 3312 3313 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3314 << ICE->getType() 3315 << ICE->getSubExpr()->getType(); 3316 } 3317 3318 /// \brief Check the constraints on expression operands to unary type expression 3319 /// and type traits. 3320 /// 3321 /// Completes any types necessary and validates the constraints on the operand 3322 /// expression. The logic mostly mirrors the type-based overload, but may modify 3323 /// the expression as it completes the type for that expression through template 3324 /// instantiation, etc. 3325 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3326 UnaryExprOrTypeTrait ExprKind) { 3327 QualType ExprTy = E->getType(); 3328 assert(!ExprTy->isReferenceType()); 3329 3330 if (ExprKind == UETT_VecStep) 3331 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3332 E->getSourceRange()); 3333 3334 // Whitelist some types as extensions 3335 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3336 E->getSourceRange(), ExprKind)) 3337 return false; 3338 3339 if (RequireCompleteExprType(E, 3340 diag::err_sizeof_alignof_incomplete_type, 3341 ExprKind, E->getSourceRange())) 3342 return true; 3343 3344 // Completing the expression's type may have changed it. 3345 ExprTy = E->getType(); 3346 assert(!ExprTy->isReferenceType()); 3347 3348 if (ExprTy->isFunctionType()) { 3349 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3350 << ExprKind << E->getSourceRange(); 3351 return true; 3352 } 3353 3354 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3355 E->getSourceRange(), ExprKind)) 3356 return true; 3357 3358 if (ExprKind == UETT_SizeOf) { 3359 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3360 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3361 QualType OType = PVD->getOriginalType(); 3362 QualType Type = PVD->getType(); 3363 if (Type->isPointerType() && OType->isArrayType()) { 3364 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3365 << Type << OType; 3366 Diag(PVD->getLocation(), diag::note_declared_at); 3367 } 3368 } 3369 } 3370 3371 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3372 // decays into a pointer and returns an unintended result. This is most 3373 // likely a typo for "sizeof(array) op x". 3374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3375 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3376 BO->getLHS()); 3377 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3378 BO->getRHS()); 3379 } 3380 } 3381 3382 return false; 3383 } 3384 3385 /// \brief Check the constraints on operands to unary expression and type 3386 /// traits. 3387 /// 3388 /// This will complete any types necessary, and validate the various constraints 3389 /// on those operands. 3390 /// 3391 /// The UsualUnaryConversions() function is *not* called by this routine. 3392 /// C99 6.3.2.1p[2-4] all state: 3393 /// Except when it is the operand of the sizeof operator ... 3394 /// 3395 /// C++ [expr.sizeof]p4 3396 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3397 /// standard conversions are not applied to the operand of sizeof. 3398 /// 3399 /// This policy is followed for all of the unary trait expressions. 3400 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3401 SourceLocation OpLoc, 3402 SourceRange ExprRange, 3403 UnaryExprOrTypeTrait ExprKind) { 3404 if (ExprType->isDependentType()) 3405 return false; 3406 3407 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3408 // the result is the size of the referenced type." 3409 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3410 // result shall be the alignment of the referenced type." 3411 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3412 ExprType = Ref->getPointeeType(); 3413 3414 if (ExprKind == UETT_VecStep) 3415 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3416 3417 // Whitelist some types as extensions 3418 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3419 ExprKind)) 3420 return false; 3421 3422 if (RequireCompleteType(OpLoc, ExprType, 3423 diag::err_sizeof_alignof_incomplete_type, 3424 ExprKind, ExprRange)) 3425 return true; 3426 3427 if (ExprType->isFunctionType()) { 3428 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3429 << ExprKind << ExprRange; 3430 return true; 3431 } 3432 3433 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3434 ExprKind)) 3435 return true; 3436 3437 return false; 3438 } 3439 3440 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3441 E = E->IgnoreParens(); 3442 3443 // Cannot know anything else if the expression is dependent. 3444 if (E->isTypeDependent()) 3445 return false; 3446 3447 if (E->getObjectKind() == OK_BitField) { 3448 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3449 << 1 << E->getSourceRange(); 3450 return true; 3451 } 3452 3453 ValueDecl *D = 0; 3454 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3455 D = DRE->getDecl(); 3456 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3457 D = ME->getMemberDecl(); 3458 } 3459 3460 // If it's a field, require the containing struct to have a 3461 // complete definition so that we can compute the layout. 3462 // 3463 // This requires a very particular set of circumstances. For a 3464 // field to be contained within an incomplete type, we must in the 3465 // process of parsing that type. To have an expression refer to a 3466 // field, it must be an id-expression or a member-expression, but 3467 // the latter are always ill-formed when the base type is 3468 // incomplete, including only being partially complete. An 3469 // id-expression can never refer to a field in C because fields 3470 // are not in the ordinary namespace. In C++, an id-expression 3471 // can implicitly be a member access, but only if there's an 3472 // implicit 'this' value, and all such contexts are subject to 3473 // delayed parsing --- except for trailing return types in C++11. 3474 // And if an id-expression referring to a field occurs in a 3475 // context that lacks a 'this' value, it's ill-formed --- except, 3476 // again, in C++11, where such references are allowed in an 3477 // unevaluated context. So C++11 introduces some new complexity. 3478 // 3479 // For the record, since __alignof__ on expressions is a GCC 3480 // extension, GCC seems to permit this but always gives the 3481 // nonsensical answer 0. 3482 // 3483 // We don't really need the layout here --- we could instead just 3484 // directly check for all the appropriate alignment-lowing 3485 // attributes --- but that would require duplicating a lot of 3486 // logic that just isn't worth duplicating for such a marginal 3487 // use-case. 3488 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3489 // Fast path this check, since we at least know the record has a 3490 // definition if we can find a member of it. 3491 if (!FD->getParent()->isCompleteDefinition()) { 3492 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3493 << E->getSourceRange(); 3494 return true; 3495 } 3496 3497 // Otherwise, if it's a field, and the field doesn't have 3498 // reference type, then it must have a complete type (or be a 3499 // flexible array member, which we explicitly want to 3500 // white-list anyway), which makes the following checks trivial. 3501 if (!FD->getType()->isReferenceType()) 3502 return false; 3503 } 3504 3505 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3506 } 3507 3508 bool Sema::CheckVecStepExpr(Expr *E) { 3509 E = E->IgnoreParens(); 3510 3511 // Cannot know anything else if the expression is dependent. 3512 if (E->isTypeDependent()) 3513 return false; 3514 3515 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3516 } 3517 3518 /// \brief Build a sizeof or alignof expression given a type operand. 3519 ExprResult 3520 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3521 SourceLocation OpLoc, 3522 UnaryExprOrTypeTrait ExprKind, 3523 SourceRange R) { 3524 if (!TInfo) 3525 return ExprError(); 3526 3527 QualType T = TInfo->getType(); 3528 3529 if (!T->isDependentType() && 3530 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3531 return ExprError(); 3532 3533 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3534 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3535 Context.getSizeType(), 3536 OpLoc, R.getEnd())); 3537 } 3538 3539 /// \brief Build a sizeof or alignof expression given an expression 3540 /// operand. 3541 ExprResult 3542 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3543 UnaryExprOrTypeTrait ExprKind) { 3544 ExprResult PE = CheckPlaceholderExpr(E); 3545 if (PE.isInvalid()) 3546 return ExprError(); 3547 3548 E = PE.get(); 3549 3550 // Verify that the operand is valid. 3551 bool isInvalid = false; 3552 if (E->isTypeDependent()) { 3553 // Delay type-checking for type-dependent expressions. 3554 } else if (ExprKind == UETT_AlignOf) { 3555 isInvalid = CheckAlignOfExpr(*this, E); 3556 } else if (ExprKind == UETT_VecStep) { 3557 isInvalid = CheckVecStepExpr(E); 3558 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3559 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3560 isInvalid = true; 3561 } else { 3562 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3563 } 3564 3565 if (isInvalid) 3566 return ExprError(); 3567 3568 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3569 PE = TransformToPotentiallyEvaluated(E); 3570 if (PE.isInvalid()) return ExprError(); 3571 E = PE.take(); 3572 } 3573 3574 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3575 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3576 ExprKind, E, Context.getSizeType(), OpLoc, 3577 E->getSourceRange().getEnd())); 3578 } 3579 3580 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3581 /// expr and the same for @c alignof and @c __alignof 3582 /// Note that the ArgRange is invalid if isType is false. 3583 ExprResult 3584 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3585 UnaryExprOrTypeTrait ExprKind, bool IsType, 3586 void *TyOrEx, const SourceRange &ArgRange) { 3587 // If error parsing type, ignore. 3588 if (TyOrEx == 0) return ExprError(); 3589 3590 if (IsType) { 3591 TypeSourceInfo *TInfo; 3592 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3593 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3594 } 3595 3596 Expr *ArgEx = (Expr *)TyOrEx; 3597 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3598 return Result; 3599 } 3600 3601 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3602 bool IsReal) { 3603 if (V.get()->isTypeDependent()) 3604 return S.Context.DependentTy; 3605 3606 // _Real and _Imag are only l-values for normal l-values. 3607 if (V.get()->getObjectKind() != OK_Ordinary) { 3608 V = S.DefaultLvalueConversion(V.take()); 3609 if (V.isInvalid()) 3610 return QualType(); 3611 } 3612 3613 // These operators return the element type of a complex type. 3614 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3615 return CT->getElementType(); 3616 3617 // Otherwise they pass through real integer and floating point types here. 3618 if (V.get()->getType()->isArithmeticType()) 3619 return V.get()->getType(); 3620 3621 // Test for placeholders. 3622 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3623 if (PR.isInvalid()) return QualType(); 3624 if (PR.get() != V.get()) { 3625 V = PR; 3626 return CheckRealImagOperand(S, V, Loc, IsReal); 3627 } 3628 3629 // Reject anything else. 3630 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3631 << (IsReal ? "__real" : "__imag"); 3632 return QualType(); 3633 } 3634 3635 3636 3637 ExprResult 3638 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3639 tok::TokenKind Kind, Expr *Input) { 3640 UnaryOperatorKind Opc; 3641 switch (Kind) { 3642 default: llvm_unreachable("Unknown unary op!"); 3643 case tok::plusplus: Opc = UO_PostInc; break; 3644 case tok::minusminus: Opc = UO_PostDec; break; 3645 } 3646 3647 // Since this might is a postfix expression, get rid of ParenListExprs. 3648 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3649 if (Result.isInvalid()) return ExprError(); 3650 Input = Result.take(); 3651 3652 return BuildUnaryOp(S, OpLoc, Opc, Input); 3653 } 3654 3655 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3656 /// 3657 /// \return true on error 3658 static bool checkArithmeticOnObjCPointer(Sema &S, 3659 SourceLocation opLoc, 3660 Expr *op) { 3661 assert(op->getType()->isObjCObjectPointerType()); 3662 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3663 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3664 return false; 3665 3666 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3667 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3668 << op->getSourceRange(); 3669 return true; 3670 } 3671 3672 ExprResult 3673 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3674 Expr *idx, SourceLocation rbLoc) { 3675 // Since this might be a postfix expression, get rid of ParenListExprs. 3676 if (isa<ParenListExpr>(base)) { 3677 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3678 if (result.isInvalid()) return ExprError(); 3679 base = result.take(); 3680 } 3681 3682 // Handle any non-overload placeholder types in the base and index 3683 // expressions. We can't handle overloads here because the other 3684 // operand might be an overloadable type, in which case the overload 3685 // resolution for the operator overload should get the first crack 3686 // at the overload. 3687 if (base->getType()->isNonOverloadPlaceholderType()) { 3688 ExprResult result = CheckPlaceholderExpr(base); 3689 if (result.isInvalid()) return ExprError(); 3690 base = result.take(); 3691 } 3692 if (idx->getType()->isNonOverloadPlaceholderType()) { 3693 ExprResult result = CheckPlaceholderExpr(idx); 3694 if (result.isInvalid()) return ExprError(); 3695 idx = result.take(); 3696 } 3697 3698 // Build an unanalyzed expression if either operand is type-dependent. 3699 if (getLangOpts().CPlusPlus && 3700 (base->isTypeDependent() || idx->isTypeDependent())) { 3701 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3702 Context.DependentTy, 3703 VK_LValue, OK_Ordinary, 3704 rbLoc)); 3705 } 3706 3707 // Use C++ overloaded-operator rules if either operand has record 3708 // type. The spec says to do this if either type is *overloadable*, 3709 // but enum types can't declare subscript operators or conversion 3710 // operators, so there's nothing interesting for overload resolution 3711 // to do if there aren't any record types involved. 3712 // 3713 // ObjC pointers have their own subscripting logic that is not tied 3714 // to overload resolution and so should not take this path. 3715 if (getLangOpts().CPlusPlus && 3716 (base->getType()->isRecordType() || 3717 (!base->getType()->isObjCObjectPointerType() && 3718 idx->getType()->isRecordType()))) { 3719 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3720 } 3721 3722 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3723 } 3724 3725 ExprResult 3726 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3727 Expr *Idx, SourceLocation RLoc) { 3728 Expr *LHSExp = Base; 3729 Expr *RHSExp = Idx; 3730 3731 // Perform default conversions. 3732 if (!LHSExp->getType()->getAs<VectorType>()) { 3733 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3734 if (Result.isInvalid()) 3735 return ExprError(); 3736 LHSExp = Result.take(); 3737 } 3738 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3739 if (Result.isInvalid()) 3740 return ExprError(); 3741 RHSExp = Result.take(); 3742 3743 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3744 ExprValueKind VK = VK_LValue; 3745 ExprObjectKind OK = OK_Ordinary; 3746 3747 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3748 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3749 // in the subscript position. As a result, we need to derive the array base 3750 // and index from the expression types. 3751 Expr *BaseExpr, *IndexExpr; 3752 QualType ResultType; 3753 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3754 BaseExpr = LHSExp; 3755 IndexExpr = RHSExp; 3756 ResultType = Context.DependentTy; 3757 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3758 BaseExpr = LHSExp; 3759 IndexExpr = RHSExp; 3760 ResultType = PTy->getPointeeType(); 3761 } else if (const ObjCObjectPointerType *PTy = 3762 LHSTy->getAs<ObjCObjectPointerType>()) { 3763 BaseExpr = LHSExp; 3764 IndexExpr = RHSExp; 3765 3766 // Use custom logic if this should be the pseudo-object subscript 3767 // expression. 3768 if (!LangOpts.isSubscriptPointerArithmetic()) 3769 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3770 3771 ResultType = PTy->getPointeeType(); 3772 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3773 // Handle the uncommon case of "123[Ptr]". 3774 BaseExpr = RHSExp; 3775 IndexExpr = LHSExp; 3776 ResultType = PTy->getPointeeType(); 3777 } else if (const ObjCObjectPointerType *PTy = 3778 RHSTy->getAs<ObjCObjectPointerType>()) { 3779 // Handle the uncommon case of "123[Ptr]". 3780 BaseExpr = RHSExp; 3781 IndexExpr = LHSExp; 3782 ResultType = PTy->getPointeeType(); 3783 if (!LangOpts.isSubscriptPointerArithmetic()) { 3784 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3785 << ResultType << BaseExpr->getSourceRange(); 3786 return ExprError(); 3787 } 3788 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3789 BaseExpr = LHSExp; // vectors: V[123] 3790 IndexExpr = RHSExp; 3791 VK = LHSExp->getValueKind(); 3792 if (VK != VK_RValue) 3793 OK = OK_VectorComponent; 3794 3795 // FIXME: need to deal with const... 3796 ResultType = VTy->getElementType(); 3797 } else if (LHSTy->isArrayType()) { 3798 // If we see an array that wasn't promoted by 3799 // DefaultFunctionArrayLvalueConversion, it must be an array that 3800 // wasn't promoted because of the C90 rule that doesn't 3801 // allow promoting non-lvalue arrays. Warn, then 3802 // force the promotion here. 3803 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3804 LHSExp->getSourceRange(); 3805 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3806 CK_ArrayToPointerDecay).take(); 3807 LHSTy = LHSExp->getType(); 3808 3809 BaseExpr = LHSExp; 3810 IndexExpr = RHSExp; 3811 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3812 } else if (RHSTy->isArrayType()) { 3813 // Same as previous, except for 123[f().a] case 3814 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3815 RHSExp->getSourceRange(); 3816 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3817 CK_ArrayToPointerDecay).take(); 3818 RHSTy = RHSExp->getType(); 3819 3820 BaseExpr = RHSExp; 3821 IndexExpr = LHSExp; 3822 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3823 } else { 3824 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3825 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3826 } 3827 // C99 6.5.2.1p1 3828 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3829 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3830 << IndexExpr->getSourceRange()); 3831 3832 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3833 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3834 && !IndexExpr->isTypeDependent()) 3835 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3836 3837 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3838 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3839 // type. Note that Functions are not objects, and that (in C99 parlance) 3840 // incomplete types are not object types. 3841 if (ResultType->isFunctionType()) { 3842 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3843 << ResultType << BaseExpr->getSourceRange(); 3844 return ExprError(); 3845 } 3846 3847 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3848 // GNU extension: subscripting on pointer to void 3849 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3850 << BaseExpr->getSourceRange(); 3851 3852 // C forbids expressions of unqualified void type from being l-values. 3853 // See IsCForbiddenLValueType. 3854 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3855 } else if (!ResultType->isDependentType() && 3856 RequireCompleteType(LLoc, ResultType, 3857 diag::err_subscript_incomplete_type, BaseExpr)) 3858 return ExprError(); 3859 3860 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3861 !ResultType.isCForbiddenLValueType()); 3862 3863 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3864 ResultType, VK, OK, RLoc)); 3865 } 3866 3867 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3868 FunctionDecl *FD, 3869 ParmVarDecl *Param) { 3870 if (Param->hasUnparsedDefaultArg()) { 3871 Diag(CallLoc, 3872 diag::err_use_of_default_argument_to_function_declared_later) << 3873 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3874 Diag(UnparsedDefaultArgLocs[Param], 3875 diag::note_default_argument_declared_here); 3876 return ExprError(); 3877 } 3878 3879 if (Param->hasUninstantiatedDefaultArg()) { 3880 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3881 3882 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3883 Param); 3884 3885 // Instantiate the expression. 3886 MultiLevelTemplateArgumentList MutiLevelArgList 3887 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3888 3889 InstantiatingTemplate Inst(*this, CallLoc, Param, 3890 MutiLevelArgList.getInnermost()); 3891 if (Inst.isInvalid()) 3892 return ExprError(); 3893 3894 ExprResult Result; 3895 { 3896 // C++ [dcl.fct.default]p5: 3897 // The names in the [default argument] expression are bound, and 3898 // the semantic constraints are checked, at the point where the 3899 // default argument expression appears. 3900 ContextRAII SavedContext(*this, FD); 3901 LocalInstantiationScope Local(*this); 3902 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3903 } 3904 if (Result.isInvalid()) 3905 return ExprError(); 3906 3907 // Check the expression as an initializer for the parameter. 3908 InitializedEntity Entity 3909 = InitializedEntity::InitializeParameter(Context, Param); 3910 InitializationKind Kind 3911 = InitializationKind::CreateCopy(Param->getLocation(), 3912 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3913 Expr *ResultE = Result.takeAs<Expr>(); 3914 3915 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3916 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3917 if (Result.isInvalid()) 3918 return ExprError(); 3919 3920 Expr *Arg = Result.takeAs<Expr>(); 3921 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3922 // Build the default argument expression. 3923 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3924 } 3925 3926 // If the default expression creates temporaries, we need to 3927 // push them to the current stack of expression temporaries so they'll 3928 // be properly destroyed. 3929 // FIXME: We should really be rebuilding the default argument with new 3930 // bound temporaries; see the comment in PR5810. 3931 // We don't need to do that with block decls, though, because 3932 // blocks in default argument expression can never capture anything. 3933 if (isa<ExprWithCleanups>(Param->getInit())) { 3934 // Set the "needs cleanups" bit regardless of whether there are 3935 // any explicit objects. 3936 ExprNeedsCleanups = true; 3937 3938 // Append all the objects to the cleanup list. Right now, this 3939 // should always be a no-op, because blocks in default argument 3940 // expressions should never be able to capture anything. 3941 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3942 "default argument expression has capturing blocks?"); 3943 } 3944 3945 // We already type-checked the argument, so we know it works. 3946 // Just mark all of the declarations in this potentially-evaluated expression 3947 // as being "referenced". 3948 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3949 /*SkipLocalVariables=*/true); 3950 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3951 } 3952 3953 3954 Sema::VariadicCallType 3955 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3956 Expr *Fn) { 3957 if (Proto && Proto->isVariadic()) { 3958 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3959 return VariadicConstructor; 3960 else if (Fn && Fn->getType()->isBlockPointerType()) 3961 return VariadicBlock; 3962 else if (FDecl) { 3963 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3964 if (Method->isInstance()) 3965 return VariadicMethod; 3966 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 3967 return VariadicMethod; 3968 return VariadicFunction; 3969 } 3970 return VariadicDoesNotApply; 3971 } 3972 3973 namespace { 3974 class FunctionCallCCC : public FunctionCallFilterCCC { 3975 public: 3976 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 3977 unsigned NumArgs, bool HasExplicitTemplateArgs) 3978 : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs), 3979 FunctionName(FuncName) {} 3980 3981 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 3982 if (!candidate.getCorrectionSpecifier() || 3983 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 3984 return false; 3985 } 3986 3987 return FunctionCallFilterCCC::ValidateCandidate(candidate); 3988 } 3989 3990 private: 3991 const IdentifierInfo *const FunctionName; 3992 }; 3993 } 3994 3995 static TypoCorrection TryTypoCorrectionForCall(Sema &S, 3996 DeclarationNameInfo FuncName, 3997 ArrayRef<Expr *> Args) { 3998 FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(), 3999 Args.size(), false); 4000 if (TypoCorrection Corrected = 4001 S.CorrectTypo(FuncName, Sema::LookupOrdinaryName, 4002 S.getScopeForContext(S.CurContext), NULL, CCC)) { 4003 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4004 if (Corrected.isOverloaded()) { 4005 OverloadCandidateSet OCS(FuncName.getLoc()); 4006 OverloadCandidateSet::iterator Best; 4007 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4008 CDEnd = Corrected.end(); 4009 CD != CDEnd; ++CD) { 4010 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4011 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4012 OCS); 4013 } 4014 switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) { 4015 case OR_Success: 4016 ND = Best->Function; 4017 Corrected.setCorrectionDecl(ND); 4018 break; 4019 default: 4020 break; 4021 } 4022 } 4023 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4024 return Corrected; 4025 } 4026 } 4027 } 4028 return TypoCorrection(); 4029 } 4030 4031 /// ConvertArgumentsForCall - Converts the arguments specified in 4032 /// Args/NumArgs to the parameter types of the function FDecl with 4033 /// function prototype Proto. Call is the call expression itself, and 4034 /// Fn is the function expression. For a C++ member function, this 4035 /// routine does not attempt to convert the object argument. Returns 4036 /// true if the call is ill-formed. 4037 bool 4038 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4039 FunctionDecl *FDecl, 4040 const FunctionProtoType *Proto, 4041 ArrayRef<Expr *> Args, 4042 SourceLocation RParenLoc, 4043 bool IsExecConfig) { 4044 // Bail out early if calling a builtin with custom typechecking. 4045 // We don't need to do this in the 4046 if (FDecl) 4047 if (unsigned ID = FDecl->getBuiltinID()) 4048 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4049 return false; 4050 4051 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4052 // assignment, to the types of the corresponding parameter, ... 4053 unsigned NumParams = Proto->getNumParams(); 4054 bool Invalid = false; 4055 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4056 unsigned FnKind = Fn->getType()->isBlockPointerType() 4057 ? 1 /* block */ 4058 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4059 : 0 /* function */); 4060 4061 // If too few arguments are available (and we don't have default 4062 // arguments for the remaining parameters), don't make the call. 4063 if (Args.size() < NumParams) { 4064 if (Args.size() < MinArgs) { 4065 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4066 TypoCorrection TC; 4067 if (FDecl && (TC = TryTypoCorrectionForCall( 4068 *this, DeclarationNameInfo(FDecl->getDeclName(), 4069 (ME ? ME->getMemberLoc() 4070 : Fn->getLocStart())), 4071 Args))) { 4072 unsigned diag_id = 4073 MinArgs == NumParams && !Proto->isVariadic() 4074 ? diag::err_typecheck_call_too_few_args_suggest 4075 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4076 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4077 << static_cast<unsigned>(Args.size()) 4078 << TC.getCorrectionRange()); 4079 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4080 Diag(RParenLoc, 4081 MinArgs == NumParams && !Proto->isVariadic() 4082 ? diag::err_typecheck_call_too_few_args_one 4083 : diag::err_typecheck_call_too_few_args_at_least_one) 4084 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4085 else 4086 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4087 ? diag::err_typecheck_call_too_few_args 4088 : diag::err_typecheck_call_too_few_args_at_least) 4089 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4090 << Fn->getSourceRange(); 4091 4092 // Emit the location of the prototype. 4093 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4094 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4095 << FDecl; 4096 4097 return true; 4098 } 4099 Call->setNumArgs(Context, NumParams); 4100 } 4101 4102 // If too many are passed and not variadic, error on the extras and drop 4103 // them. 4104 if (Args.size() > NumParams) { 4105 if (!Proto->isVariadic()) { 4106 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4107 TypoCorrection TC; 4108 if (FDecl && (TC = TryTypoCorrectionForCall( 4109 *this, DeclarationNameInfo(FDecl->getDeclName(), 4110 (ME ? ME->getMemberLoc() 4111 : Fn->getLocStart())), 4112 Args))) { 4113 unsigned diag_id = 4114 MinArgs == NumParams && !Proto->isVariadic() 4115 ? diag::err_typecheck_call_too_many_args_suggest 4116 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4117 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4118 << static_cast<unsigned>(Args.size()) 4119 << TC.getCorrectionRange()); 4120 } else if (NumParams == 1 && FDecl && 4121 FDecl->getParamDecl(0)->getDeclName()) 4122 Diag(Args[NumParams]->getLocStart(), 4123 MinArgs == NumParams 4124 ? diag::err_typecheck_call_too_many_args_one 4125 : diag::err_typecheck_call_too_many_args_at_most_one) 4126 << FnKind << FDecl->getParamDecl(0) 4127 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4128 << SourceRange(Args[NumParams]->getLocStart(), 4129 Args.back()->getLocEnd()); 4130 else 4131 Diag(Args[NumParams]->getLocStart(), 4132 MinArgs == NumParams 4133 ? diag::err_typecheck_call_too_many_args 4134 : diag::err_typecheck_call_too_many_args_at_most) 4135 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4136 << Fn->getSourceRange() 4137 << SourceRange(Args[NumParams]->getLocStart(), 4138 Args.back()->getLocEnd()); 4139 4140 // Emit the location of the prototype. 4141 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4142 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4143 << FDecl; 4144 4145 // This deletes the extra arguments. 4146 Call->setNumArgs(Context, NumParams); 4147 return true; 4148 } 4149 } 4150 SmallVector<Expr *, 8> AllArgs; 4151 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4152 4153 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4154 Proto, 0, Args, AllArgs, CallType); 4155 if (Invalid) 4156 return true; 4157 unsigned TotalNumArgs = AllArgs.size(); 4158 for (unsigned i = 0; i < TotalNumArgs; ++i) 4159 Call->setArg(i, AllArgs[i]); 4160 4161 return false; 4162 } 4163 4164 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4165 const FunctionProtoType *Proto, 4166 unsigned FirstParam, ArrayRef<Expr *> Args, 4167 SmallVectorImpl<Expr *> &AllArgs, 4168 VariadicCallType CallType, bool AllowExplicit, 4169 bool IsListInitialization) { 4170 unsigned NumParams = Proto->getNumParams(); 4171 unsigned NumArgsToCheck = Args.size(); 4172 bool Invalid = false; 4173 if (Args.size() != NumParams) 4174 // Use default arguments for missing arguments 4175 NumArgsToCheck = NumParams; 4176 unsigned ArgIx = 0; 4177 // Continue to check argument types (even if we have too few/many args). 4178 for (unsigned i = FirstParam; i != NumArgsToCheck; i++) { 4179 QualType ProtoArgType = Proto->getParamType(i); 4180 4181 Expr *Arg; 4182 ParmVarDecl *Param; 4183 if (ArgIx < Args.size()) { 4184 Arg = Args[ArgIx++]; 4185 4186 if (RequireCompleteType(Arg->getLocStart(), 4187 ProtoArgType, 4188 diag::err_call_incomplete_argument, Arg)) 4189 return true; 4190 4191 // Pass the argument 4192 Param = 0; 4193 if (FDecl && i < FDecl->getNumParams()) 4194 Param = FDecl->getParamDecl(i); 4195 4196 // Strip the unbridged-cast placeholder expression off, if applicable. 4197 bool CFAudited = false; 4198 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4199 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4200 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4201 Arg = stripARCUnbridgedCast(Arg); 4202 else if (getLangOpts().ObjCAutoRefCount && 4203 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4204 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4205 CFAudited = true; 4206 4207 InitializedEntity Entity = 4208 Param ? InitializedEntity::InitializeParameter(Context, Param, 4209 ProtoArgType) 4210 : InitializedEntity::InitializeParameter( 4211 Context, ProtoArgType, Proto->isParamConsumed(i)); 4212 4213 // Remember that parameter belongs to a CF audited API. 4214 if (CFAudited) 4215 Entity.setParameterCFAudited(); 4216 4217 ExprResult ArgE = PerformCopyInitialization(Entity, 4218 SourceLocation(), 4219 Owned(Arg), 4220 IsListInitialization, 4221 AllowExplicit); 4222 if (ArgE.isInvalid()) 4223 return true; 4224 4225 Arg = ArgE.takeAs<Expr>(); 4226 } else { 4227 assert(FDecl && "can't use default arguments without a known callee"); 4228 Param = FDecl->getParamDecl(i); 4229 4230 ExprResult ArgExpr = 4231 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4232 if (ArgExpr.isInvalid()) 4233 return true; 4234 4235 Arg = ArgExpr.takeAs<Expr>(); 4236 } 4237 4238 // Check for array bounds violations for each argument to the call. This 4239 // check only triggers warnings when the argument isn't a more complex Expr 4240 // with its own checking, such as a BinaryOperator. 4241 CheckArrayAccess(Arg); 4242 4243 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4244 CheckStaticArrayArgument(CallLoc, Param, Arg); 4245 4246 AllArgs.push_back(Arg); 4247 } 4248 4249 // If this is a variadic call, handle args passed through "...". 4250 if (CallType != VariadicDoesNotApply) { 4251 // Assume that extern "C" functions with variadic arguments that 4252 // return __unknown_anytype aren't *really* variadic. 4253 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4254 FDecl->isExternC()) { 4255 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4256 QualType paramType; // ignored 4257 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4258 Invalid |= arg.isInvalid(); 4259 AllArgs.push_back(arg.take()); 4260 } 4261 4262 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4263 } else { 4264 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4265 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4266 FDecl); 4267 Invalid |= Arg.isInvalid(); 4268 AllArgs.push_back(Arg.take()); 4269 } 4270 } 4271 4272 // Check for array bounds violations. 4273 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4274 CheckArrayAccess(Args[i]); 4275 } 4276 return Invalid; 4277 } 4278 4279 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4280 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4281 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4282 TL = DTL.getOriginalLoc(); 4283 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4284 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4285 << ATL.getLocalSourceRange(); 4286 } 4287 4288 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4289 /// array parameter, check that it is non-null, and that if it is formed by 4290 /// array-to-pointer decay, the underlying array is sufficiently large. 4291 /// 4292 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4293 /// array type derivation, then for each call to the function, the value of the 4294 /// corresponding actual argument shall provide access to the first element of 4295 /// an array with at least as many elements as specified by the size expression. 4296 void 4297 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4298 ParmVarDecl *Param, 4299 const Expr *ArgExpr) { 4300 // Static array parameters are not supported in C++. 4301 if (!Param || getLangOpts().CPlusPlus) 4302 return; 4303 4304 QualType OrigTy = Param->getOriginalType(); 4305 4306 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4307 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4308 return; 4309 4310 if (ArgExpr->isNullPointerConstant(Context, 4311 Expr::NPC_NeverValueDependent)) { 4312 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4313 DiagnoseCalleeStaticArrayParam(*this, Param); 4314 return; 4315 } 4316 4317 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4318 if (!CAT) 4319 return; 4320 4321 const ConstantArrayType *ArgCAT = 4322 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4323 if (!ArgCAT) 4324 return; 4325 4326 if (ArgCAT->getSize().ult(CAT->getSize())) { 4327 Diag(CallLoc, diag::warn_static_array_too_small) 4328 << ArgExpr->getSourceRange() 4329 << (unsigned) ArgCAT->getSize().getZExtValue() 4330 << (unsigned) CAT->getSize().getZExtValue(); 4331 DiagnoseCalleeStaticArrayParam(*this, Param); 4332 } 4333 } 4334 4335 /// Given a function expression of unknown-any type, try to rebuild it 4336 /// to have a function type. 4337 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4338 4339 /// Is the given type a placeholder that we need to lower out 4340 /// immediately during argument processing? 4341 static bool isPlaceholderToRemoveAsArg(QualType type) { 4342 // Placeholders are never sugared. 4343 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4344 if (!placeholder) return false; 4345 4346 switch (placeholder->getKind()) { 4347 // Ignore all the non-placeholder types. 4348 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4349 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4350 #include "clang/AST/BuiltinTypes.def" 4351 return false; 4352 4353 // We cannot lower out overload sets; they might validly be resolved 4354 // by the call machinery. 4355 case BuiltinType::Overload: 4356 return false; 4357 4358 // Unbridged casts in ARC can be handled in some call positions and 4359 // should be left in place. 4360 case BuiltinType::ARCUnbridgedCast: 4361 return false; 4362 4363 // Pseudo-objects should be converted as soon as possible. 4364 case BuiltinType::PseudoObject: 4365 return true; 4366 4367 // The debugger mode could theoretically but currently does not try 4368 // to resolve unknown-typed arguments based on known parameter types. 4369 case BuiltinType::UnknownAny: 4370 return true; 4371 4372 // These are always invalid as call arguments and should be reported. 4373 case BuiltinType::BoundMember: 4374 case BuiltinType::BuiltinFn: 4375 return true; 4376 } 4377 llvm_unreachable("bad builtin type kind"); 4378 } 4379 4380 /// Check an argument list for placeholders that we won't try to 4381 /// handle later. 4382 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4383 // Apply this processing to all the arguments at once instead of 4384 // dying at the first failure. 4385 bool hasInvalid = false; 4386 for (size_t i = 0, e = args.size(); i != e; i++) { 4387 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4388 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4389 if (result.isInvalid()) hasInvalid = true; 4390 else args[i] = result.take(); 4391 } 4392 } 4393 return hasInvalid; 4394 } 4395 4396 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4397 /// This provides the location of the left/right parens and a list of comma 4398 /// locations. 4399 ExprResult 4400 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4401 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4402 Expr *ExecConfig, bool IsExecConfig) { 4403 // Since this might be a postfix expression, get rid of ParenListExprs. 4404 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4405 if (Result.isInvalid()) return ExprError(); 4406 Fn = Result.take(); 4407 4408 if (checkArgsForPlaceholders(*this, ArgExprs)) 4409 return ExprError(); 4410 4411 if (getLangOpts().CPlusPlus) { 4412 // If this is a pseudo-destructor expression, build the call immediately. 4413 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4414 if (!ArgExprs.empty()) { 4415 // Pseudo-destructor calls should not have any arguments. 4416 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4417 << FixItHint::CreateRemoval( 4418 SourceRange(ArgExprs[0]->getLocStart(), 4419 ArgExprs.back()->getLocEnd())); 4420 } 4421 4422 return Owned(new (Context) CallExpr(Context, Fn, None, 4423 Context.VoidTy, VK_RValue, 4424 RParenLoc)); 4425 } 4426 if (Fn->getType() == Context.PseudoObjectTy) { 4427 ExprResult result = CheckPlaceholderExpr(Fn); 4428 if (result.isInvalid()) return ExprError(); 4429 Fn = result.take(); 4430 } 4431 4432 // Determine whether this is a dependent call inside a C++ template, 4433 // in which case we won't do any semantic analysis now. 4434 // FIXME: Will need to cache the results of name lookup (including ADL) in 4435 // Fn. 4436 bool Dependent = false; 4437 if (Fn->isTypeDependent()) 4438 Dependent = true; 4439 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4440 Dependent = true; 4441 4442 if (Dependent) { 4443 if (ExecConfig) { 4444 return Owned(new (Context) CUDAKernelCallExpr( 4445 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4446 Context.DependentTy, VK_RValue, RParenLoc)); 4447 } else { 4448 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4449 Context.DependentTy, VK_RValue, 4450 RParenLoc)); 4451 } 4452 } 4453 4454 // Determine whether this is a call to an object (C++ [over.call.object]). 4455 if (Fn->getType()->isRecordType()) 4456 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4457 ArgExprs, RParenLoc)); 4458 4459 if (Fn->getType() == Context.UnknownAnyTy) { 4460 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4461 if (result.isInvalid()) return ExprError(); 4462 Fn = result.take(); 4463 } 4464 4465 if (Fn->getType() == Context.BoundMemberTy) { 4466 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4467 } 4468 } 4469 4470 // Check for overloaded calls. This can happen even in C due to extensions. 4471 if (Fn->getType() == Context.OverloadTy) { 4472 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4473 4474 // We aren't supposed to apply this logic for if there's an '&' involved. 4475 if (!find.HasFormOfMemberPointer) { 4476 OverloadExpr *ovl = find.Expression; 4477 if (isa<UnresolvedLookupExpr>(ovl)) { 4478 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4479 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4480 RParenLoc, ExecConfig); 4481 } else { 4482 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4483 RParenLoc); 4484 } 4485 } 4486 } 4487 4488 // If we're directly calling a function, get the appropriate declaration. 4489 if (Fn->getType() == Context.UnknownAnyTy) { 4490 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4491 if (result.isInvalid()) return ExprError(); 4492 Fn = result.take(); 4493 } 4494 4495 Expr *NakedFn = Fn->IgnoreParens(); 4496 4497 NamedDecl *NDecl = 0; 4498 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4499 if (UnOp->getOpcode() == UO_AddrOf) 4500 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4501 4502 if (isa<DeclRefExpr>(NakedFn)) 4503 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4504 else if (isa<MemberExpr>(NakedFn)) 4505 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4506 4507 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4508 if (FD->hasAttr<EnableIfAttr>()) { 4509 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4510 Diag(Fn->getLocStart(), 4511 isa<CXXMethodDecl>(FD) ? 4512 diag::err_ovl_no_viable_member_function_in_call : 4513 diag::err_ovl_no_viable_function_in_call) 4514 << FD << FD->getSourceRange(); 4515 Diag(FD->getLocation(), 4516 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4517 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4518 } 4519 } 4520 } 4521 4522 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4523 ExecConfig, IsExecConfig); 4524 } 4525 4526 ExprResult 4527 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4528 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4529 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4530 if (!ConfigDecl) 4531 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4532 << "cudaConfigureCall"); 4533 QualType ConfigQTy = ConfigDecl->getType(); 4534 4535 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4536 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4537 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4538 4539 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4540 /*IsExecConfig=*/true); 4541 } 4542 4543 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4544 /// 4545 /// __builtin_astype( value, dst type ) 4546 /// 4547 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4548 SourceLocation BuiltinLoc, 4549 SourceLocation RParenLoc) { 4550 ExprValueKind VK = VK_RValue; 4551 ExprObjectKind OK = OK_Ordinary; 4552 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4553 QualType SrcTy = E->getType(); 4554 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4555 return ExprError(Diag(BuiltinLoc, 4556 diag::err_invalid_astype_of_different_size) 4557 << DstTy 4558 << SrcTy 4559 << E->getSourceRange()); 4560 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4561 RParenLoc)); 4562 } 4563 4564 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4565 /// provided arguments. 4566 /// 4567 /// __builtin_convertvector( value, dst type ) 4568 /// 4569 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4570 SourceLocation BuiltinLoc, 4571 SourceLocation RParenLoc) { 4572 TypeSourceInfo *TInfo; 4573 GetTypeFromParser(ParsedDestTy, &TInfo); 4574 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4575 } 4576 4577 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4578 /// i.e. an expression not of \p OverloadTy. The expression should 4579 /// unary-convert to an expression of function-pointer or 4580 /// block-pointer type. 4581 /// 4582 /// \param NDecl the declaration being called, if available 4583 ExprResult 4584 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4585 SourceLocation LParenLoc, 4586 ArrayRef<Expr *> Args, 4587 SourceLocation RParenLoc, 4588 Expr *Config, bool IsExecConfig) { 4589 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4590 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4591 4592 // Promote the function operand. 4593 // We special-case function promotion here because we only allow promoting 4594 // builtin functions to function pointers in the callee of a call. 4595 ExprResult Result; 4596 if (BuiltinID && 4597 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4598 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4599 CK_BuiltinFnToFnPtr).take(); 4600 } else { 4601 Result = CallExprUnaryConversions(Fn); 4602 } 4603 if (Result.isInvalid()) 4604 return ExprError(); 4605 Fn = Result.take(); 4606 4607 // Make the call expr early, before semantic checks. This guarantees cleanup 4608 // of arguments and function on error. 4609 CallExpr *TheCall; 4610 if (Config) 4611 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4612 cast<CallExpr>(Config), Args, 4613 Context.BoolTy, VK_RValue, 4614 RParenLoc); 4615 else 4616 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4617 VK_RValue, RParenLoc); 4618 4619 // Bail out early if calling a builtin with custom typechecking. 4620 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4621 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4622 4623 retry: 4624 const FunctionType *FuncT; 4625 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4626 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4627 // have type pointer to function". 4628 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4629 if (FuncT == 0) 4630 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4631 << Fn->getType() << Fn->getSourceRange()); 4632 } else if (const BlockPointerType *BPT = 4633 Fn->getType()->getAs<BlockPointerType>()) { 4634 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4635 } else { 4636 // Handle calls to expressions of unknown-any type. 4637 if (Fn->getType() == Context.UnknownAnyTy) { 4638 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4639 if (rewrite.isInvalid()) return ExprError(); 4640 Fn = rewrite.take(); 4641 TheCall->setCallee(Fn); 4642 goto retry; 4643 } 4644 4645 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4646 << Fn->getType() << Fn->getSourceRange()); 4647 } 4648 4649 if (getLangOpts().CUDA) { 4650 if (Config) { 4651 // CUDA: Kernel calls must be to global functions 4652 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4653 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4654 << FDecl->getName() << Fn->getSourceRange()); 4655 4656 // CUDA: Kernel function must have 'void' return type 4657 if (!FuncT->getReturnType()->isVoidType()) 4658 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4659 << Fn->getType() << Fn->getSourceRange()); 4660 } else { 4661 // CUDA: Calls to global functions must be configured 4662 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4663 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4664 << FDecl->getName() << Fn->getSourceRange()); 4665 } 4666 } 4667 4668 // Check for a valid return type 4669 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 4670 FDecl)) 4671 return ExprError(); 4672 4673 // We know the result type of the call, set it. 4674 TheCall->setType(FuncT->getCallResultType(Context)); 4675 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 4676 4677 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4678 if (Proto) { 4679 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4680 IsExecConfig)) 4681 return ExprError(); 4682 } else { 4683 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4684 4685 if (FDecl) { 4686 // Check if we have too few/too many template arguments, based 4687 // on our knowledge of the function definition. 4688 const FunctionDecl *Def = 0; 4689 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4690 Proto = Def->getType()->getAs<FunctionProtoType>(); 4691 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4692 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4693 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4694 } 4695 4696 // If the function we're calling isn't a function prototype, but we have 4697 // a function prototype from a prior declaratiom, use that prototype. 4698 if (!FDecl->hasPrototype()) 4699 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4700 } 4701 4702 // Promote the arguments (C99 6.5.2.2p6). 4703 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4704 Expr *Arg = Args[i]; 4705 4706 if (Proto && i < Proto->getNumParams()) { 4707 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4708 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 4709 ExprResult ArgE = PerformCopyInitialization(Entity, 4710 SourceLocation(), 4711 Owned(Arg)); 4712 if (ArgE.isInvalid()) 4713 return true; 4714 4715 Arg = ArgE.takeAs<Expr>(); 4716 4717 } else { 4718 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4719 4720 if (ArgE.isInvalid()) 4721 return true; 4722 4723 Arg = ArgE.takeAs<Expr>(); 4724 } 4725 4726 if (RequireCompleteType(Arg->getLocStart(), 4727 Arg->getType(), 4728 diag::err_call_incomplete_argument, Arg)) 4729 return ExprError(); 4730 4731 TheCall->setArg(i, Arg); 4732 } 4733 } 4734 4735 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4736 if (!Method->isStatic()) 4737 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4738 << Fn->getSourceRange()); 4739 4740 // Check for sentinels 4741 if (NDecl) 4742 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4743 4744 // Do special checking on direct calls to functions. 4745 if (FDecl) { 4746 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4747 return ExprError(); 4748 4749 if (BuiltinID) 4750 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4751 } else if (NDecl) { 4752 if (CheckPointerCall(NDecl, TheCall, Proto)) 4753 return ExprError(); 4754 } else { 4755 if (CheckOtherCall(TheCall, Proto)) 4756 return ExprError(); 4757 } 4758 4759 return MaybeBindToTemporary(TheCall); 4760 } 4761 4762 ExprResult 4763 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4764 SourceLocation RParenLoc, Expr *InitExpr) { 4765 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4766 // FIXME: put back this assert when initializers are worked out. 4767 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4768 4769 TypeSourceInfo *TInfo; 4770 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4771 if (!TInfo) 4772 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4773 4774 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4775 } 4776 4777 ExprResult 4778 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4779 SourceLocation RParenLoc, Expr *LiteralExpr) { 4780 QualType literalType = TInfo->getType(); 4781 4782 if (literalType->isArrayType()) { 4783 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4784 diag::err_illegal_decl_array_incomplete_type, 4785 SourceRange(LParenLoc, 4786 LiteralExpr->getSourceRange().getEnd()))) 4787 return ExprError(); 4788 if (literalType->isVariableArrayType()) 4789 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4790 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4791 } else if (!literalType->isDependentType() && 4792 RequireCompleteType(LParenLoc, literalType, 4793 diag::err_typecheck_decl_incomplete_type, 4794 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4795 return ExprError(); 4796 4797 InitializedEntity Entity 4798 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4799 InitializationKind Kind 4800 = InitializationKind::CreateCStyleCast(LParenLoc, 4801 SourceRange(LParenLoc, RParenLoc), 4802 /*InitList=*/true); 4803 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4804 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4805 &literalType); 4806 if (Result.isInvalid()) 4807 return ExprError(); 4808 LiteralExpr = Result.get(); 4809 4810 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4811 if (isFileScope && 4812 !LiteralExpr->isTypeDependent() && 4813 !LiteralExpr->isValueDependent() && 4814 !literalType->isDependentType()) { // 6.5.2.5p3 4815 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4816 return ExprError(); 4817 } 4818 4819 // In C, compound literals are l-values for some reason. 4820 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4821 4822 return MaybeBindToTemporary( 4823 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4824 VK, LiteralExpr, isFileScope)); 4825 } 4826 4827 ExprResult 4828 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4829 SourceLocation RBraceLoc) { 4830 // Immediately handle non-overload placeholders. Overloads can be 4831 // resolved contextually, but everything else here can't. 4832 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4833 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4834 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4835 4836 // Ignore failures; dropping the entire initializer list because 4837 // of one failure would be terrible for indexing/etc. 4838 if (result.isInvalid()) continue; 4839 4840 InitArgList[I] = result.take(); 4841 } 4842 } 4843 4844 // Semantic analysis for initializers is done by ActOnDeclarator() and 4845 // CheckInitializer() - it requires knowledge of the object being intialized. 4846 4847 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4848 RBraceLoc); 4849 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4850 return Owned(E); 4851 } 4852 4853 /// Do an explicit extend of the given block pointer if we're in ARC. 4854 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4855 assert(E.get()->getType()->isBlockPointerType()); 4856 assert(E.get()->isRValue()); 4857 4858 // Only do this in an r-value context. 4859 if (!S.getLangOpts().ObjCAutoRefCount) return; 4860 4861 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4862 CK_ARCExtendBlockObject, E.get(), 4863 /*base path*/ 0, VK_RValue); 4864 S.ExprNeedsCleanups = true; 4865 } 4866 4867 /// Prepare a conversion of the given expression to an ObjC object 4868 /// pointer type. 4869 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4870 QualType type = E.get()->getType(); 4871 if (type->isObjCObjectPointerType()) { 4872 return CK_BitCast; 4873 } else if (type->isBlockPointerType()) { 4874 maybeExtendBlockObject(*this, E); 4875 return CK_BlockPointerToObjCPointerCast; 4876 } else { 4877 assert(type->isPointerType()); 4878 return CK_CPointerToObjCPointerCast; 4879 } 4880 } 4881 4882 /// Prepares for a scalar cast, performing all the necessary stages 4883 /// except the final cast and returning the kind required. 4884 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4885 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4886 // Also, callers should have filtered out the invalid cases with 4887 // pointers. Everything else should be possible. 4888 4889 QualType SrcTy = Src.get()->getType(); 4890 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4891 return CK_NoOp; 4892 4893 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4894 case Type::STK_MemberPointer: 4895 llvm_unreachable("member pointer type in C"); 4896 4897 case Type::STK_CPointer: 4898 case Type::STK_BlockPointer: 4899 case Type::STK_ObjCObjectPointer: 4900 switch (DestTy->getScalarTypeKind()) { 4901 case Type::STK_CPointer: { 4902 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 4903 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 4904 if (SrcAS != DestAS) 4905 return CK_AddressSpaceConversion; 4906 return CK_BitCast; 4907 } 4908 case Type::STK_BlockPointer: 4909 return (SrcKind == Type::STK_BlockPointer 4910 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4911 case Type::STK_ObjCObjectPointer: 4912 if (SrcKind == Type::STK_ObjCObjectPointer) 4913 return CK_BitCast; 4914 if (SrcKind == Type::STK_CPointer) 4915 return CK_CPointerToObjCPointerCast; 4916 maybeExtendBlockObject(*this, Src); 4917 return CK_BlockPointerToObjCPointerCast; 4918 case Type::STK_Bool: 4919 return CK_PointerToBoolean; 4920 case Type::STK_Integral: 4921 return CK_PointerToIntegral; 4922 case Type::STK_Floating: 4923 case Type::STK_FloatingComplex: 4924 case Type::STK_IntegralComplex: 4925 case Type::STK_MemberPointer: 4926 llvm_unreachable("illegal cast from pointer"); 4927 } 4928 llvm_unreachable("Should have returned before this"); 4929 4930 case Type::STK_Bool: // casting from bool is like casting from an integer 4931 case Type::STK_Integral: 4932 switch (DestTy->getScalarTypeKind()) { 4933 case Type::STK_CPointer: 4934 case Type::STK_ObjCObjectPointer: 4935 case Type::STK_BlockPointer: 4936 if (Src.get()->isNullPointerConstant(Context, 4937 Expr::NPC_ValueDependentIsNull)) 4938 return CK_NullToPointer; 4939 return CK_IntegralToPointer; 4940 case Type::STK_Bool: 4941 return CK_IntegralToBoolean; 4942 case Type::STK_Integral: 4943 return CK_IntegralCast; 4944 case Type::STK_Floating: 4945 return CK_IntegralToFloating; 4946 case Type::STK_IntegralComplex: 4947 Src = ImpCastExprToType(Src.take(), 4948 DestTy->castAs<ComplexType>()->getElementType(), 4949 CK_IntegralCast); 4950 return CK_IntegralRealToComplex; 4951 case Type::STK_FloatingComplex: 4952 Src = ImpCastExprToType(Src.take(), 4953 DestTy->castAs<ComplexType>()->getElementType(), 4954 CK_IntegralToFloating); 4955 return CK_FloatingRealToComplex; 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_Floating: 4962 switch (DestTy->getScalarTypeKind()) { 4963 case Type::STK_Floating: 4964 return CK_FloatingCast; 4965 case Type::STK_Bool: 4966 return CK_FloatingToBoolean; 4967 case Type::STK_Integral: 4968 return CK_FloatingToIntegral; 4969 case Type::STK_FloatingComplex: 4970 Src = ImpCastExprToType(Src.take(), 4971 DestTy->castAs<ComplexType>()->getElementType(), 4972 CK_FloatingCast); 4973 return CK_FloatingRealToComplex; 4974 case Type::STK_IntegralComplex: 4975 Src = ImpCastExprToType(Src.take(), 4976 DestTy->castAs<ComplexType>()->getElementType(), 4977 CK_FloatingToIntegral); 4978 return CK_IntegralRealToComplex; 4979 case Type::STK_CPointer: 4980 case Type::STK_ObjCObjectPointer: 4981 case Type::STK_BlockPointer: 4982 llvm_unreachable("valid float->pointer cast?"); 4983 case Type::STK_MemberPointer: 4984 llvm_unreachable("member pointer type in C"); 4985 } 4986 llvm_unreachable("Should have returned before this"); 4987 4988 case Type::STK_FloatingComplex: 4989 switch (DestTy->getScalarTypeKind()) { 4990 case Type::STK_FloatingComplex: 4991 return CK_FloatingComplexCast; 4992 case Type::STK_IntegralComplex: 4993 return CK_FloatingComplexToIntegralComplex; 4994 case Type::STK_Floating: { 4995 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4996 if (Context.hasSameType(ET, DestTy)) 4997 return CK_FloatingComplexToReal; 4998 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4999 return CK_FloatingCast; 5000 } 5001 case Type::STK_Bool: 5002 return CK_FloatingComplexToBoolean; 5003 case Type::STK_Integral: 5004 Src = ImpCastExprToType(Src.take(), 5005 SrcTy->castAs<ComplexType>()->getElementType(), 5006 CK_FloatingComplexToReal); 5007 return CK_FloatingToIntegral; 5008 case Type::STK_CPointer: 5009 case Type::STK_ObjCObjectPointer: 5010 case Type::STK_BlockPointer: 5011 llvm_unreachable("valid complex float->pointer cast?"); 5012 case Type::STK_MemberPointer: 5013 llvm_unreachable("member pointer type in C"); 5014 } 5015 llvm_unreachable("Should have returned before this"); 5016 5017 case Type::STK_IntegralComplex: 5018 switch (DestTy->getScalarTypeKind()) { 5019 case Type::STK_FloatingComplex: 5020 return CK_IntegralComplexToFloatingComplex; 5021 case Type::STK_IntegralComplex: 5022 return CK_IntegralComplexCast; 5023 case Type::STK_Integral: { 5024 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5025 if (Context.hasSameType(ET, DestTy)) 5026 return CK_IntegralComplexToReal; 5027 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 5028 return CK_IntegralCast; 5029 } 5030 case Type::STK_Bool: 5031 return CK_IntegralComplexToBoolean; 5032 case Type::STK_Floating: 5033 Src = ImpCastExprToType(Src.take(), 5034 SrcTy->castAs<ComplexType>()->getElementType(), 5035 CK_IntegralComplexToReal); 5036 return CK_IntegralToFloating; 5037 case Type::STK_CPointer: 5038 case Type::STK_ObjCObjectPointer: 5039 case Type::STK_BlockPointer: 5040 llvm_unreachable("valid complex int->pointer cast?"); 5041 case Type::STK_MemberPointer: 5042 llvm_unreachable("member pointer type in C"); 5043 } 5044 llvm_unreachable("Should have returned before this"); 5045 } 5046 5047 llvm_unreachable("Unhandled scalar cast"); 5048 } 5049 5050 static bool breakDownVectorType(QualType type, uint64_t &len, 5051 QualType &eltType) { 5052 // Vectors are simple. 5053 if (const VectorType *vecType = type->getAs<VectorType>()) { 5054 len = vecType->getNumElements(); 5055 eltType = vecType->getElementType(); 5056 assert(eltType->isScalarType()); 5057 return true; 5058 } 5059 5060 // We allow lax conversion to and from non-vector types, but only if 5061 // they're real types (i.e. non-complex, non-pointer scalar types). 5062 if (!type->isRealType()) return false; 5063 5064 len = 1; 5065 eltType = type; 5066 return true; 5067 } 5068 5069 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) { 5070 uint64_t srcLen, destLen; 5071 QualType srcElt, destElt; 5072 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 5073 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 5074 5075 // ASTContext::getTypeSize will return the size rounded up to a 5076 // power of 2, so instead of using that, we need to use the raw 5077 // element size multiplied by the element count. 5078 uint64_t srcEltSize = S.Context.getTypeSize(srcElt); 5079 uint64_t destEltSize = S.Context.getTypeSize(destElt); 5080 5081 return (srcLen * srcEltSize == destLen * destEltSize); 5082 } 5083 5084 /// Is this a legal conversion between two known vector types? 5085 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5086 assert(destTy->isVectorType() || srcTy->isVectorType()); 5087 5088 if (!Context.getLangOpts().LaxVectorConversions) 5089 return false; 5090 return VectorTypesMatch(*this, srcTy, destTy); 5091 } 5092 5093 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5094 CastKind &Kind) { 5095 assert(VectorTy->isVectorType() && "Not a vector type!"); 5096 5097 if (Ty->isVectorType() || Ty->isIntegerType()) { 5098 if (!VectorTypesMatch(*this, Ty, VectorTy)) 5099 return Diag(R.getBegin(), 5100 Ty->isVectorType() ? 5101 diag::err_invalid_conversion_between_vectors : 5102 diag::err_invalid_conversion_between_vector_and_integer) 5103 << VectorTy << Ty << R; 5104 } else 5105 return Diag(R.getBegin(), 5106 diag::err_invalid_conversion_between_vector_and_scalar) 5107 << VectorTy << Ty << R; 5108 5109 Kind = CK_BitCast; 5110 return false; 5111 } 5112 5113 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5114 Expr *CastExpr, CastKind &Kind) { 5115 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5116 5117 QualType SrcTy = CastExpr->getType(); 5118 5119 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5120 // an ExtVectorType. 5121 // In OpenCL, casts between vectors of different types are not allowed. 5122 // (See OpenCL 6.2). 5123 if (SrcTy->isVectorType()) { 5124 if (!VectorTypesMatch(*this, SrcTy, DestTy) 5125 || (getLangOpts().OpenCL && 5126 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5127 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5128 << DestTy << SrcTy << R; 5129 return ExprError(); 5130 } 5131 Kind = CK_BitCast; 5132 return Owned(CastExpr); 5133 } 5134 5135 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5136 // conversion will take place first from scalar to elt type, and then 5137 // splat from elt type to vector. 5138 if (SrcTy->isPointerType()) 5139 return Diag(R.getBegin(), 5140 diag::err_invalid_conversion_between_vector_and_scalar) 5141 << DestTy << SrcTy << R; 5142 5143 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5144 ExprResult CastExprRes = Owned(CastExpr); 5145 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5146 if (CastExprRes.isInvalid()) 5147 return ExprError(); 5148 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 5149 5150 Kind = CK_VectorSplat; 5151 return Owned(CastExpr); 5152 } 5153 5154 ExprResult 5155 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5156 Declarator &D, ParsedType &Ty, 5157 SourceLocation RParenLoc, Expr *CastExpr) { 5158 assert(!D.isInvalidType() && (CastExpr != 0) && 5159 "ActOnCastExpr(): missing type or expr"); 5160 5161 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5162 if (D.isInvalidType()) 5163 return ExprError(); 5164 5165 if (getLangOpts().CPlusPlus) { 5166 // Check that there are no default arguments (C++ only). 5167 CheckExtraCXXDefaultArguments(D); 5168 } 5169 5170 checkUnusedDeclAttributes(D); 5171 5172 QualType castType = castTInfo->getType(); 5173 Ty = CreateParsedType(castType, castTInfo); 5174 5175 bool isVectorLiteral = false; 5176 5177 // Check for an altivec or OpenCL literal, 5178 // i.e. all the elements are integer constants. 5179 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5180 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5181 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5182 && castType->isVectorType() && (PE || PLE)) { 5183 if (PLE && PLE->getNumExprs() == 0) { 5184 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5185 return ExprError(); 5186 } 5187 if (PE || PLE->getNumExprs() == 1) { 5188 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5189 if (!E->getType()->isVectorType()) 5190 isVectorLiteral = true; 5191 } 5192 else 5193 isVectorLiteral = true; 5194 } 5195 5196 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5197 // then handle it as such. 5198 if (isVectorLiteral) 5199 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5200 5201 // If the Expr being casted is a ParenListExpr, handle it specially. 5202 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5203 // sequence of BinOp comma operators. 5204 if (isa<ParenListExpr>(CastExpr)) { 5205 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5206 if (Result.isInvalid()) return ExprError(); 5207 CastExpr = Result.take(); 5208 } 5209 5210 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5211 !getSourceManager().isInSystemMacro(LParenLoc)) 5212 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5213 5214 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5215 } 5216 5217 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5218 SourceLocation RParenLoc, Expr *E, 5219 TypeSourceInfo *TInfo) { 5220 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5221 "Expected paren or paren list expression"); 5222 5223 Expr **exprs; 5224 unsigned numExprs; 5225 Expr *subExpr; 5226 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5227 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5228 LiteralLParenLoc = PE->getLParenLoc(); 5229 LiteralRParenLoc = PE->getRParenLoc(); 5230 exprs = PE->getExprs(); 5231 numExprs = PE->getNumExprs(); 5232 } else { // isa<ParenExpr> by assertion at function entrance 5233 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5234 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5235 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5236 exprs = &subExpr; 5237 numExprs = 1; 5238 } 5239 5240 QualType Ty = TInfo->getType(); 5241 assert(Ty->isVectorType() && "Expected vector type"); 5242 5243 SmallVector<Expr *, 8> initExprs; 5244 const VectorType *VTy = Ty->getAs<VectorType>(); 5245 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5246 5247 // '(...)' form of vector initialization in AltiVec: the number of 5248 // initializers must be one or must match the size of the vector. 5249 // If a single value is specified in the initializer then it will be 5250 // replicated to all the components of the vector 5251 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5252 // The number of initializers must be one or must match the size of the 5253 // vector. If a single value is specified in the initializer then it will 5254 // be replicated to all the components of the vector 5255 if (numExprs == 1) { 5256 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5257 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5258 if (Literal.isInvalid()) 5259 return ExprError(); 5260 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5261 PrepareScalarCast(Literal, ElemTy)); 5262 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5263 } 5264 else if (numExprs < numElems) { 5265 Diag(E->getExprLoc(), 5266 diag::err_incorrect_number_of_vector_initializers); 5267 return ExprError(); 5268 } 5269 else 5270 initExprs.append(exprs, exprs + numExprs); 5271 } 5272 else { 5273 // For OpenCL, when the number of initializers is a single value, 5274 // it will be replicated to all components of the vector. 5275 if (getLangOpts().OpenCL && 5276 VTy->getVectorKind() == VectorType::GenericVector && 5277 numExprs == 1) { 5278 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5279 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5280 if (Literal.isInvalid()) 5281 return ExprError(); 5282 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5283 PrepareScalarCast(Literal, ElemTy)); 5284 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5285 } 5286 5287 initExprs.append(exprs, exprs + numExprs); 5288 } 5289 // FIXME: This means that pretty-printing the final AST will produce curly 5290 // braces instead of the original commas. 5291 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5292 initExprs, LiteralRParenLoc); 5293 initE->setType(Ty); 5294 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5295 } 5296 5297 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5298 /// the ParenListExpr into a sequence of comma binary operators. 5299 ExprResult 5300 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5301 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5302 if (!E) 5303 return Owned(OrigExpr); 5304 5305 ExprResult Result(E->getExpr(0)); 5306 5307 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5308 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5309 E->getExpr(i)); 5310 5311 if (Result.isInvalid()) return ExprError(); 5312 5313 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5314 } 5315 5316 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5317 SourceLocation R, 5318 MultiExprArg Val) { 5319 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5320 return Owned(expr); 5321 } 5322 5323 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5324 /// constant and the other is not a pointer. Returns true if a diagnostic is 5325 /// emitted. 5326 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5327 SourceLocation QuestionLoc) { 5328 Expr *NullExpr = LHSExpr; 5329 Expr *NonPointerExpr = RHSExpr; 5330 Expr::NullPointerConstantKind NullKind = 5331 NullExpr->isNullPointerConstant(Context, 5332 Expr::NPC_ValueDependentIsNotNull); 5333 5334 if (NullKind == Expr::NPCK_NotNull) { 5335 NullExpr = RHSExpr; 5336 NonPointerExpr = LHSExpr; 5337 NullKind = 5338 NullExpr->isNullPointerConstant(Context, 5339 Expr::NPC_ValueDependentIsNotNull); 5340 } 5341 5342 if (NullKind == Expr::NPCK_NotNull) 5343 return false; 5344 5345 if (NullKind == Expr::NPCK_ZeroExpression) 5346 return false; 5347 5348 if (NullKind == Expr::NPCK_ZeroLiteral) { 5349 // In this case, check to make sure that we got here from a "NULL" 5350 // string in the source code. 5351 NullExpr = NullExpr->IgnoreParenImpCasts(); 5352 SourceLocation loc = NullExpr->getExprLoc(); 5353 if (!findMacroSpelling(loc, "NULL")) 5354 return false; 5355 } 5356 5357 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5358 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5359 << NonPointerExpr->getType() << DiagType 5360 << NonPointerExpr->getSourceRange(); 5361 return true; 5362 } 5363 5364 /// \brief Return false if the condition expression is valid, true otherwise. 5365 static bool checkCondition(Sema &S, Expr *Cond) { 5366 QualType CondTy = Cond->getType(); 5367 5368 // C99 6.5.15p2 5369 if (CondTy->isScalarType()) return false; 5370 5371 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5372 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5373 return false; 5374 5375 // Emit the proper error message. 5376 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5377 diag::err_typecheck_cond_expect_scalar : 5378 diag::err_typecheck_cond_expect_scalar_or_vector) 5379 << CondTy; 5380 return true; 5381 } 5382 5383 /// \brief Return false if the two expressions can be converted to a vector, 5384 /// true otherwise 5385 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5386 ExprResult &RHS, 5387 QualType CondTy) { 5388 // Both operands should be of scalar type. 5389 if (!LHS.get()->getType()->isScalarType()) { 5390 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5391 << CondTy; 5392 return true; 5393 } 5394 if (!RHS.get()->getType()->isScalarType()) { 5395 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5396 << CondTy; 5397 return true; 5398 } 5399 5400 // Implicity convert these scalars to the type of the condition. 5401 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5402 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5403 return false; 5404 } 5405 5406 /// \brief Handle when one or both operands are void type. 5407 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5408 ExprResult &RHS) { 5409 Expr *LHSExpr = LHS.get(); 5410 Expr *RHSExpr = RHS.get(); 5411 5412 if (!LHSExpr->getType()->isVoidType()) 5413 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5414 << RHSExpr->getSourceRange(); 5415 if (!RHSExpr->getType()->isVoidType()) 5416 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5417 << LHSExpr->getSourceRange(); 5418 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5419 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5420 return S.Context.VoidTy; 5421 } 5422 5423 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5424 /// true otherwise. 5425 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5426 QualType PointerTy) { 5427 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5428 !NullExpr.get()->isNullPointerConstant(S.Context, 5429 Expr::NPC_ValueDependentIsNull)) 5430 return true; 5431 5432 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5433 return false; 5434 } 5435 5436 /// \brief Checks compatibility between two pointers and return the resulting 5437 /// type. 5438 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5439 ExprResult &RHS, 5440 SourceLocation Loc) { 5441 QualType LHSTy = LHS.get()->getType(); 5442 QualType RHSTy = RHS.get()->getType(); 5443 5444 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5445 // Two identical pointers types are always compatible. 5446 return LHSTy; 5447 } 5448 5449 QualType lhptee, rhptee; 5450 5451 // Get the pointee types. 5452 bool IsBlockPointer = false; 5453 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5454 lhptee = LHSBTy->getPointeeType(); 5455 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5456 IsBlockPointer = true; 5457 } else { 5458 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5459 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5460 } 5461 5462 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5463 // differently qualified versions of compatible types, the result type is 5464 // a pointer to an appropriately qualified version of the composite 5465 // type. 5466 5467 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5468 // clause doesn't make sense for our extensions. E.g. address space 2 should 5469 // be incompatible with address space 3: they may live on different devices or 5470 // anything. 5471 Qualifiers lhQual = lhptee.getQualifiers(); 5472 Qualifiers rhQual = rhptee.getQualifiers(); 5473 5474 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5475 lhQual.removeCVRQualifiers(); 5476 rhQual.removeCVRQualifiers(); 5477 5478 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5479 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5480 5481 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5482 5483 if (CompositeTy.isNull()) { 5484 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5485 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5486 << RHS.get()->getSourceRange(); 5487 // In this situation, we assume void* type. No especially good 5488 // reason, but this is what gcc does, and we do have to pick 5489 // to get a consistent AST. 5490 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5491 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5492 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5493 return incompatTy; 5494 } 5495 5496 // The pointer types are compatible. 5497 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5498 if (IsBlockPointer) 5499 ResultTy = S.Context.getBlockPointerType(ResultTy); 5500 else 5501 ResultTy = S.Context.getPointerType(ResultTy); 5502 5503 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5504 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5505 return ResultTy; 5506 } 5507 5508 /// \brief Return the resulting type when the operands are both block pointers. 5509 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5510 ExprResult &LHS, 5511 ExprResult &RHS, 5512 SourceLocation Loc) { 5513 QualType LHSTy = LHS.get()->getType(); 5514 QualType RHSTy = RHS.get()->getType(); 5515 5516 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5517 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5518 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5519 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5520 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5521 return destType; 5522 } 5523 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5524 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5525 << RHS.get()->getSourceRange(); 5526 return QualType(); 5527 } 5528 5529 // We have 2 block pointer types. 5530 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5531 } 5532 5533 /// \brief Return the resulting type when the operands are both pointers. 5534 static QualType 5535 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5536 ExprResult &RHS, 5537 SourceLocation Loc) { 5538 // get the pointer types 5539 QualType LHSTy = LHS.get()->getType(); 5540 QualType RHSTy = RHS.get()->getType(); 5541 5542 // get the "pointed to" types 5543 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5544 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5545 5546 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5547 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5548 // Figure out necessary qualifiers (C99 6.5.15p6) 5549 QualType destPointee 5550 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5551 QualType destType = S.Context.getPointerType(destPointee); 5552 // Add qualifiers if necessary. 5553 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5554 // Promote to void*. 5555 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5556 return destType; 5557 } 5558 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5559 QualType destPointee 5560 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5561 QualType destType = S.Context.getPointerType(destPointee); 5562 // Add qualifiers if necessary. 5563 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5564 // Promote to void*. 5565 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5566 return destType; 5567 } 5568 5569 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5570 } 5571 5572 /// \brief Return false if the first expression is not an integer and the second 5573 /// expression is not a pointer, true otherwise. 5574 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5575 Expr* PointerExpr, SourceLocation Loc, 5576 bool IsIntFirstExpr) { 5577 if (!PointerExpr->getType()->isPointerType() || 5578 !Int.get()->getType()->isIntegerType()) 5579 return false; 5580 5581 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5582 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5583 5584 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5585 << Expr1->getType() << Expr2->getType() 5586 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5587 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5588 CK_IntegralToPointer); 5589 return true; 5590 } 5591 5592 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5593 /// In that case, LHS = cond. 5594 /// C99 6.5.15 5595 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5596 ExprResult &RHS, ExprValueKind &VK, 5597 ExprObjectKind &OK, 5598 SourceLocation QuestionLoc) { 5599 5600 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5601 if (!LHSResult.isUsable()) return QualType(); 5602 LHS = LHSResult; 5603 5604 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5605 if (!RHSResult.isUsable()) return QualType(); 5606 RHS = RHSResult; 5607 5608 // C++ is sufficiently different to merit its own checker. 5609 if (getLangOpts().CPlusPlus) 5610 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5611 5612 VK = VK_RValue; 5613 OK = OK_Ordinary; 5614 5615 // First, check the condition. 5616 Cond = UsualUnaryConversions(Cond.take()); 5617 if (Cond.isInvalid()) 5618 return QualType(); 5619 if (checkCondition(*this, Cond.get())) 5620 return QualType(); 5621 5622 // Now check the two expressions. 5623 if (LHS.get()->getType()->isVectorType() || 5624 RHS.get()->getType()->isVectorType()) 5625 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5626 5627 UsualArithmeticConversions(LHS, RHS); 5628 if (LHS.isInvalid() || RHS.isInvalid()) 5629 return QualType(); 5630 5631 QualType CondTy = Cond.get()->getType(); 5632 QualType LHSTy = LHS.get()->getType(); 5633 QualType RHSTy = RHS.get()->getType(); 5634 5635 // If the condition is a vector, and both operands are scalar, 5636 // attempt to implicity convert them to the vector type to act like the 5637 // built in select. (OpenCL v1.1 s6.3.i) 5638 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5639 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5640 return QualType(); 5641 5642 // If both operands have arithmetic type, do the usual arithmetic conversions 5643 // to find a common type: C99 6.5.15p3,5. 5644 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5645 return LHS.get()->getType(); 5646 5647 // If both operands are the same structure or union type, the result is that 5648 // type. 5649 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5650 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5651 if (LHSRT->getDecl() == RHSRT->getDecl()) 5652 // "If both the operands have structure or union type, the result has 5653 // that type." This implies that CV qualifiers are dropped. 5654 return LHSTy.getUnqualifiedType(); 5655 // FIXME: Type of conditional expression must be complete in C mode. 5656 } 5657 5658 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5659 // The following || allows only one side to be void (a GCC-ism). 5660 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5661 return checkConditionalVoidType(*this, LHS, RHS); 5662 } 5663 5664 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5665 // the type of the other operand." 5666 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5667 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5668 5669 // All objective-c pointer type analysis is done here. 5670 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5671 QuestionLoc); 5672 if (LHS.isInvalid() || RHS.isInvalid()) 5673 return QualType(); 5674 if (!compositeType.isNull()) 5675 return compositeType; 5676 5677 5678 // Handle block pointer types. 5679 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5680 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5681 QuestionLoc); 5682 5683 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5684 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5685 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5686 QuestionLoc); 5687 5688 // GCC compatibility: soften pointer/integer mismatch. Note that 5689 // null pointers have been filtered out by this point. 5690 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5691 /*isIntFirstExpr=*/true)) 5692 return RHSTy; 5693 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5694 /*isIntFirstExpr=*/false)) 5695 return LHSTy; 5696 5697 // Emit a better diagnostic if one of the expressions is a null pointer 5698 // constant and the other is not a pointer type. In this case, the user most 5699 // likely forgot to take the address of the other expression. 5700 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5701 return QualType(); 5702 5703 // Otherwise, the operands are not compatible. 5704 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5705 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5706 << RHS.get()->getSourceRange(); 5707 return QualType(); 5708 } 5709 5710 /// FindCompositeObjCPointerType - Helper method to find composite type of 5711 /// two objective-c pointer types of the two input expressions. 5712 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5713 SourceLocation QuestionLoc) { 5714 QualType LHSTy = LHS.get()->getType(); 5715 QualType RHSTy = RHS.get()->getType(); 5716 5717 // Handle things like Class and struct objc_class*. Here we case the result 5718 // to the pseudo-builtin, because that will be implicitly cast back to the 5719 // redefinition type if an attempt is made to access its fields. 5720 if (LHSTy->isObjCClassType() && 5721 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5722 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5723 return LHSTy; 5724 } 5725 if (RHSTy->isObjCClassType() && 5726 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5727 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5728 return RHSTy; 5729 } 5730 // And the same for struct objc_object* / id 5731 if (LHSTy->isObjCIdType() && 5732 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5733 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5734 return LHSTy; 5735 } 5736 if (RHSTy->isObjCIdType() && 5737 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5738 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5739 return RHSTy; 5740 } 5741 // And the same for struct objc_selector* / SEL 5742 if (Context.isObjCSelType(LHSTy) && 5743 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5744 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5745 return LHSTy; 5746 } 5747 if (Context.isObjCSelType(RHSTy) && 5748 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5749 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5750 return RHSTy; 5751 } 5752 // Check constraints for Objective-C object pointers types. 5753 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5754 5755 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5756 // Two identical object pointer types are always compatible. 5757 return LHSTy; 5758 } 5759 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5760 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5761 QualType compositeType = LHSTy; 5762 5763 // If both operands are interfaces and either operand can be 5764 // assigned to the other, use that type as the composite 5765 // type. This allows 5766 // xxx ? (A*) a : (B*) b 5767 // where B is a subclass of A. 5768 // 5769 // Additionally, as for assignment, if either type is 'id' 5770 // allow silent coercion. Finally, if the types are 5771 // incompatible then make sure to use 'id' as the composite 5772 // type so the result is acceptable for sending messages to. 5773 5774 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5775 // It could return the composite type. 5776 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5777 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5778 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5779 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5780 } else if ((LHSTy->isObjCQualifiedIdType() || 5781 RHSTy->isObjCQualifiedIdType()) && 5782 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5783 // Need to handle "id<xx>" explicitly. 5784 // GCC allows qualified id and any Objective-C type to devolve to 5785 // id. Currently localizing to here until clear this should be 5786 // part of ObjCQualifiedIdTypesAreCompatible. 5787 compositeType = Context.getObjCIdType(); 5788 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5789 compositeType = Context.getObjCIdType(); 5790 } else if (!(compositeType = 5791 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5792 ; 5793 else { 5794 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5795 << LHSTy << RHSTy 5796 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5797 QualType incompatTy = Context.getObjCIdType(); 5798 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5799 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5800 return incompatTy; 5801 } 5802 // The object pointer types are compatible. 5803 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5804 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5805 return compositeType; 5806 } 5807 // Check Objective-C object pointer types and 'void *' 5808 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5809 if (getLangOpts().ObjCAutoRefCount) { 5810 // ARC forbids the implicit conversion of object pointers to 'void *', 5811 // so these types are not compatible. 5812 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5813 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5814 LHS = RHS = true; 5815 return QualType(); 5816 } 5817 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5818 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5819 QualType destPointee 5820 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5821 QualType destType = Context.getPointerType(destPointee); 5822 // Add qualifiers if necessary. 5823 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5824 // Promote to void*. 5825 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5826 return destType; 5827 } 5828 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5829 if (getLangOpts().ObjCAutoRefCount) { 5830 // ARC forbids the implicit conversion of object pointers to 'void *', 5831 // so these types are not compatible. 5832 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5833 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5834 LHS = RHS = true; 5835 return QualType(); 5836 } 5837 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5838 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5839 QualType destPointee 5840 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5841 QualType destType = Context.getPointerType(destPointee); 5842 // Add qualifiers if necessary. 5843 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5844 // Promote to void*. 5845 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5846 return destType; 5847 } 5848 return QualType(); 5849 } 5850 5851 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5852 /// ParenRange in parentheses. 5853 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5854 const PartialDiagnostic &Note, 5855 SourceRange ParenRange) { 5856 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5857 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5858 EndLoc.isValid()) { 5859 Self.Diag(Loc, Note) 5860 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5861 << FixItHint::CreateInsertion(EndLoc, ")"); 5862 } else { 5863 // We can't display the parentheses, so just show the bare note. 5864 Self.Diag(Loc, Note) << ParenRange; 5865 } 5866 } 5867 5868 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5869 return Opc >= BO_Mul && Opc <= BO_Shr; 5870 } 5871 5872 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5873 /// expression, either using a built-in or overloaded operator, 5874 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5875 /// expression. 5876 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5877 Expr **RHSExprs) { 5878 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5879 E = E->IgnoreImpCasts(); 5880 E = E->IgnoreConversionOperator(); 5881 E = E->IgnoreImpCasts(); 5882 5883 // Built-in binary operator. 5884 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5885 if (IsArithmeticOp(OP->getOpcode())) { 5886 *Opcode = OP->getOpcode(); 5887 *RHSExprs = OP->getRHS(); 5888 return true; 5889 } 5890 } 5891 5892 // Overloaded operator. 5893 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5894 if (Call->getNumArgs() != 2) 5895 return false; 5896 5897 // Make sure this is really a binary operator that is safe to pass into 5898 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5899 OverloadedOperatorKind OO = Call->getOperator(); 5900 if (OO < OO_Plus || OO > OO_Arrow || 5901 OO == OO_PlusPlus || OO == OO_MinusMinus) 5902 return false; 5903 5904 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5905 if (IsArithmeticOp(OpKind)) { 5906 *Opcode = OpKind; 5907 *RHSExprs = Call->getArg(1); 5908 return true; 5909 } 5910 } 5911 5912 return false; 5913 } 5914 5915 static bool IsLogicOp(BinaryOperatorKind Opc) { 5916 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5917 } 5918 5919 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5920 /// or is a logical expression such as (x==y) which has int type, but is 5921 /// commonly interpreted as boolean. 5922 static bool ExprLooksBoolean(Expr *E) { 5923 E = E->IgnoreParenImpCasts(); 5924 5925 if (E->getType()->isBooleanType()) 5926 return true; 5927 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5928 return IsLogicOp(OP->getOpcode()); 5929 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5930 return OP->getOpcode() == UO_LNot; 5931 5932 return false; 5933 } 5934 5935 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5936 /// and binary operator are mixed in a way that suggests the programmer assumed 5937 /// the conditional operator has higher precedence, for example: 5938 /// "int x = a + someBinaryCondition ? 1 : 2". 5939 static void DiagnoseConditionalPrecedence(Sema &Self, 5940 SourceLocation OpLoc, 5941 Expr *Condition, 5942 Expr *LHSExpr, 5943 Expr *RHSExpr) { 5944 BinaryOperatorKind CondOpcode; 5945 Expr *CondRHS; 5946 5947 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5948 return; 5949 if (!ExprLooksBoolean(CondRHS)) 5950 return; 5951 5952 // The condition is an arithmetic binary expression, with a right- 5953 // hand side that looks boolean, so warn. 5954 5955 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5956 << Condition->getSourceRange() 5957 << BinaryOperator::getOpcodeStr(CondOpcode); 5958 5959 SuggestParentheses(Self, OpLoc, 5960 Self.PDiag(diag::note_precedence_silence) 5961 << BinaryOperator::getOpcodeStr(CondOpcode), 5962 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5963 5964 SuggestParentheses(Self, OpLoc, 5965 Self.PDiag(diag::note_precedence_conditional_first), 5966 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5967 } 5968 5969 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5970 /// in the case of a the GNU conditional expr extension. 5971 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5972 SourceLocation ColonLoc, 5973 Expr *CondExpr, Expr *LHSExpr, 5974 Expr *RHSExpr) { 5975 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5976 // was the condition. 5977 OpaqueValueExpr *opaqueValue = 0; 5978 Expr *commonExpr = 0; 5979 if (LHSExpr == 0) { 5980 commonExpr = CondExpr; 5981 // Lower out placeholder types first. This is important so that we don't 5982 // try to capture a placeholder. This happens in few cases in C++; such 5983 // as Objective-C++'s dictionary subscripting syntax. 5984 if (commonExpr->hasPlaceholderType()) { 5985 ExprResult result = CheckPlaceholderExpr(commonExpr); 5986 if (!result.isUsable()) return ExprError(); 5987 commonExpr = result.take(); 5988 } 5989 // We usually want to apply unary conversions *before* saving, except 5990 // in the special case of a C++ l-value conditional. 5991 if (!(getLangOpts().CPlusPlus 5992 && !commonExpr->isTypeDependent() 5993 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5994 && commonExpr->isGLValue() 5995 && commonExpr->isOrdinaryOrBitFieldObject() 5996 && RHSExpr->isOrdinaryOrBitFieldObject() 5997 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5998 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5999 if (commonRes.isInvalid()) 6000 return ExprError(); 6001 commonExpr = commonRes.take(); 6002 } 6003 6004 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6005 commonExpr->getType(), 6006 commonExpr->getValueKind(), 6007 commonExpr->getObjectKind(), 6008 commonExpr); 6009 LHSExpr = CondExpr = opaqueValue; 6010 } 6011 6012 ExprValueKind VK = VK_RValue; 6013 ExprObjectKind OK = OK_Ordinary; 6014 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 6015 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6016 VK, OK, QuestionLoc); 6017 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6018 RHS.isInvalid()) 6019 return ExprError(); 6020 6021 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6022 RHS.get()); 6023 6024 if (!commonExpr) 6025 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 6026 LHS.take(), ColonLoc, 6027 RHS.take(), result, VK, OK)); 6028 6029 return Owned(new (Context) 6030 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 6031 RHS.take(), QuestionLoc, ColonLoc, result, VK, 6032 OK)); 6033 } 6034 6035 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6036 // being closely modeled after the C99 spec:-). The odd characteristic of this 6037 // routine is it effectively iqnores the qualifiers on the top level pointee. 6038 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6039 // FIXME: add a couple examples in this comment. 6040 static Sema::AssignConvertType 6041 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6042 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6043 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6044 6045 // get the "pointed to" type (ignoring qualifiers at the top level) 6046 const Type *lhptee, *rhptee; 6047 Qualifiers lhq, rhq; 6048 std::tie(lhptee, lhq) = 6049 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6050 std::tie(rhptee, rhq) = 6051 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6052 6053 Sema::AssignConvertType ConvTy = Sema::Compatible; 6054 6055 // C99 6.5.16.1p1: This following citation is common to constraints 6056 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6057 // qualifiers of the type *pointed to* by the right; 6058 6059 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6060 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6061 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6062 // Ignore lifetime for further calculation. 6063 lhq.removeObjCLifetime(); 6064 rhq.removeObjCLifetime(); 6065 } 6066 6067 if (!lhq.compatiblyIncludes(rhq)) { 6068 // Treat address-space mismatches as fatal. TODO: address subspaces 6069 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 6070 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6071 6072 // It's okay to add or remove GC or lifetime qualifiers when converting to 6073 // and from void*. 6074 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6075 .compatiblyIncludes( 6076 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6077 && (lhptee->isVoidType() || rhptee->isVoidType())) 6078 ; // keep old 6079 6080 // Treat lifetime mismatches as fatal. 6081 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6082 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6083 6084 // For GCC compatibility, other qualifier mismatches are treated 6085 // as still compatible in C. 6086 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6087 } 6088 6089 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6090 // incomplete type and the other is a pointer to a qualified or unqualified 6091 // version of void... 6092 if (lhptee->isVoidType()) { 6093 if (rhptee->isIncompleteOrObjectType()) 6094 return ConvTy; 6095 6096 // As an extension, we allow cast to/from void* to function pointer. 6097 assert(rhptee->isFunctionType()); 6098 return Sema::FunctionVoidPointer; 6099 } 6100 6101 if (rhptee->isVoidType()) { 6102 if (lhptee->isIncompleteOrObjectType()) 6103 return ConvTy; 6104 6105 // As an extension, we allow cast to/from void* to function pointer. 6106 assert(lhptee->isFunctionType()); 6107 return Sema::FunctionVoidPointer; 6108 } 6109 6110 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6111 // unqualified versions of compatible types, ... 6112 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6113 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6114 // Check if the pointee types are compatible ignoring the sign. 6115 // We explicitly check for char so that we catch "char" vs 6116 // "unsigned char" on systems where "char" is unsigned. 6117 if (lhptee->isCharType()) 6118 ltrans = S.Context.UnsignedCharTy; 6119 else if (lhptee->hasSignedIntegerRepresentation()) 6120 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6121 6122 if (rhptee->isCharType()) 6123 rtrans = S.Context.UnsignedCharTy; 6124 else if (rhptee->hasSignedIntegerRepresentation()) 6125 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6126 6127 if (ltrans == rtrans) { 6128 // Types are compatible ignoring the sign. Qualifier incompatibility 6129 // takes priority over sign incompatibility because the sign 6130 // warning can be disabled. 6131 if (ConvTy != Sema::Compatible) 6132 return ConvTy; 6133 6134 return Sema::IncompatiblePointerSign; 6135 } 6136 6137 // If we are a multi-level pointer, it's possible that our issue is simply 6138 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6139 // the eventual target type is the same and the pointers have the same 6140 // level of indirection, this must be the issue. 6141 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6142 do { 6143 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6144 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6145 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6146 6147 if (lhptee == rhptee) 6148 return Sema::IncompatibleNestedPointerQualifiers; 6149 } 6150 6151 // General pointer incompatibility takes priority over qualifiers. 6152 return Sema::IncompatiblePointer; 6153 } 6154 if (!S.getLangOpts().CPlusPlus && 6155 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6156 return Sema::IncompatiblePointer; 6157 return ConvTy; 6158 } 6159 6160 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6161 /// block pointer types are compatible or whether a block and normal pointer 6162 /// are compatible. It is more restrict than comparing two function pointer 6163 // types. 6164 static Sema::AssignConvertType 6165 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6166 QualType RHSType) { 6167 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6168 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6169 6170 QualType lhptee, rhptee; 6171 6172 // get the "pointed to" type (ignoring qualifiers at the top level) 6173 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6174 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6175 6176 // In C++, the types have to match exactly. 6177 if (S.getLangOpts().CPlusPlus) 6178 return Sema::IncompatibleBlockPointer; 6179 6180 Sema::AssignConvertType ConvTy = Sema::Compatible; 6181 6182 // For blocks we enforce that qualifiers are identical. 6183 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6184 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6185 6186 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6187 return Sema::IncompatibleBlockPointer; 6188 6189 return ConvTy; 6190 } 6191 6192 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6193 /// for assignment compatibility. 6194 static Sema::AssignConvertType 6195 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6196 QualType RHSType) { 6197 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6198 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6199 6200 if (LHSType->isObjCBuiltinType()) { 6201 // Class is not compatible with ObjC object pointers. 6202 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6203 !RHSType->isObjCQualifiedClassType()) 6204 return Sema::IncompatiblePointer; 6205 return Sema::Compatible; 6206 } 6207 if (RHSType->isObjCBuiltinType()) { 6208 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6209 !LHSType->isObjCQualifiedClassType()) 6210 return Sema::IncompatiblePointer; 6211 return Sema::Compatible; 6212 } 6213 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6214 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6215 6216 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6217 // make an exception for id<P> 6218 !LHSType->isObjCQualifiedIdType()) 6219 return Sema::CompatiblePointerDiscardsQualifiers; 6220 6221 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6222 return Sema::Compatible; 6223 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6224 return Sema::IncompatibleObjCQualifiedId; 6225 return Sema::IncompatiblePointer; 6226 } 6227 6228 Sema::AssignConvertType 6229 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6230 QualType LHSType, QualType RHSType) { 6231 // Fake up an opaque expression. We don't actually care about what 6232 // cast operations are required, so if CheckAssignmentConstraints 6233 // adds casts to this they'll be wasted, but fortunately that doesn't 6234 // usually happen on valid code. 6235 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6236 ExprResult RHSPtr = &RHSExpr; 6237 CastKind K = CK_Invalid; 6238 6239 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6240 } 6241 6242 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6243 /// has code to accommodate several GCC extensions when type checking 6244 /// pointers. Here are some objectionable examples that GCC considers warnings: 6245 /// 6246 /// int a, *pint; 6247 /// short *pshort; 6248 /// struct foo *pfoo; 6249 /// 6250 /// pint = pshort; // warning: assignment from incompatible pointer type 6251 /// a = pint; // warning: assignment makes integer from pointer without a cast 6252 /// pint = a; // warning: assignment makes pointer from integer without a cast 6253 /// pint = pfoo; // warning: assignment from incompatible pointer type 6254 /// 6255 /// As a result, the code for dealing with pointers is more complex than the 6256 /// C99 spec dictates. 6257 /// 6258 /// Sets 'Kind' for any result kind except Incompatible. 6259 Sema::AssignConvertType 6260 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6261 CastKind &Kind) { 6262 QualType RHSType = RHS.get()->getType(); 6263 QualType OrigLHSType = LHSType; 6264 6265 // Get canonical types. We're not formatting these types, just comparing 6266 // them. 6267 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6268 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6269 6270 // Common case: no conversion required. 6271 if (LHSType == RHSType) { 6272 Kind = CK_NoOp; 6273 return Compatible; 6274 } 6275 6276 // If we have an atomic type, try a non-atomic assignment, then just add an 6277 // atomic qualification step. 6278 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6279 Sema::AssignConvertType result = 6280 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6281 if (result != Compatible) 6282 return result; 6283 if (Kind != CK_NoOp) 6284 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 6285 Kind = CK_NonAtomicToAtomic; 6286 return Compatible; 6287 } 6288 6289 // If the left-hand side is a reference type, then we are in a 6290 // (rare!) case where we've allowed the use of references in C, 6291 // e.g., as a parameter type in a built-in function. In this case, 6292 // just make sure that the type referenced is compatible with the 6293 // right-hand side type. The caller is responsible for adjusting 6294 // LHSType so that the resulting expression does not have reference 6295 // type. 6296 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6297 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6298 Kind = CK_LValueBitCast; 6299 return Compatible; 6300 } 6301 return Incompatible; 6302 } 6303 6304 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6305 // to the same ExtVector type. 6306 if (LHSType->isExtVectorType()) { 6307 if (RHSType->isExtVectorType()) 6308 return Incompatible; 6309 if (RHSType->isArithmeticType()) { 6310 // CK_VectorSplat does T -> vector T, so first cast to the 6311 // element type. 6312 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6313 if (elType != RHSType) { 6314 Kind = PrepareScalarCast(RHS, elType); 6315 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 6316 } 6317 Kind = CK_VectorSplat; 6318 return Compatible; 6319 } 6320 } 6321 6322 // Conversions to or from vector type. 6323 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6324 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6325 // Allow assignments of an AltiVec vector type to an equivalent GCC 6326 // vector type and vice versa 6327 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6328 Kind = CK_BitCast; 6329 return Compatible; 6330 } 6331 6332 // If we are allowing lax vector conversions, and LHS and RHS are both 6333 // vectors, the total size only needs to be the same. This is a bitcast; 6334 // no bits are changed but the result type is different. 6335 if (isLaxVectorConversion(RHSType, LHSType)) { 6336 Kind = CK_BitCast; 6337 return IncompatibleVectors; 6338 } 6339 } 6340 return Incompatible; 6341 } 6342 6343 // Arithmetic conversions. 6344 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6345 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6346 Kind = PrepareScalarCast(RHS, LHSType); 6347 return Compatible; 6348 } 6349 6350 // Conversions to normal pointers. 6351 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6352 // U* -> T* 6353 if (isa<PointerType>(RHSType)) { 6354 Kind = CK_BitCast; 6355 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6356 } 6357 6358 // int -> T* 6359 if (RHSType->isIntegerType()) { 6360 Kind = CK_IntegralToPointer; // FIXME: null? 6361 return IntToPointer; 6362 } 6363 6364 // C pointers are not compatible with ObjC object pointers, 6365 // with two exceptions: 6366 if (isa<ObjCObjectPointerType>(RHSType)) { 6367 // - conversions to void* 6368 if (LHSPointer->getPointeeType()->isVoidType()) { 6369 Kind = CK_BitCast; 6370 return Compatible; 6371 } 6372 6373 // - conversions from 'Class' to the redefinition type 6374 if (RHSType->isObjCClassType() && 6375 Context.hasSameType(LHSType, 6376 Context.getObjCClassRedefinitionType())) { 6377 Kind = CK_BitCast; 6378 return Compatible; 6379 } 6380 6381 Kind = CK_BitCast; 6382 return IncompatiblePointer; 6383 } 6384 6385 // U^ -> void* 6386 if (RHSType->getAs<BlockPointerType>()) { 6387 if (LHSPointer->getPointeeType()->isVoidType()) { 6388 Kind = CK_BitCast; 6389 return Compatible; 6390 } 6391 } 6392 6393 return Incompatible; 6394 } 6395 6396 // Conversions to block pointers. 6397 if (isa<BlockPointerType>(LHSType)) { 6398 // U^ -> T^ 6399 if (RHSType->isBlockPointerType()) { 6400 Kind = CK_BitCast; 6401 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6402 } 6403 6404 // int or null -> T^ 6405 if (RHSType->isIntegerType()) { 6406 Kind = CK_IntegralToPointer; // FIXME: null 6407 return IntToBlockPointer; 6408 } 6409 6410 // id -> T^ 6411 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6412 Kind = CK_AnyPointerToBlockPointerCast; 6413 return Compatible; 6414 } 6415 6416 // void* -> T^ 6417 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6418 if (RHSPT->getPointeeType()->isVoidType()) { 6419 Kind = CK_AnyPointerToBlockPointerCast; 6420 return Compatible; 6421 } 6422 6423 return Incompatible; 6424 } 6425 6426 // Conversions to Objective-C pointers. 6427 if (isa<ObjCObjectPointerType>(LHSType)) { 6428 // A* -> B* 6429 if (RHSType->isObjCObjectPointerType()) { 6430 Kind = CK_BitCast; 6431 Sema::AssignConvertType result = 6432 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6433 if (getLangOpts().ObjCAutoRefCount && 6434 result == Compatible && 6435 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6436 result = IncompatibleObjCWeakRef; 6437 return result; 6438 } 6439 6440 // int or null -> A* 6441 if (RHSType->isIntegerType()) { 6442 Kind = CK_IntegralToPointer; // FIXME: null 6443 return IntToPointer; 6444 } 6445 6446 // In general, C pointers are not compatible with ObjC object pointers, 6447 // with two exceptions: 6448 if (isa<PointerType>(RHSType)) { 6449 Kind = CK_CPointerToObjCPointerCast; 6450 6451 // - conversions from 'void*' 6452 if (RHSType->isVoidPointerType()) { 6453 return Compatible; 6454 } 6455 6456 // - conversions to 'Class' from its redefinition type 6457 if (LHSType->isObjCClassType() && 6458 Context.hasSameType(RHSType, 6459 Context.getObjCClassRedefinitionType())) { 6460 return Compatible; 6461 } 6462 6463 return IncompatiblePointer; 6464 } 6465 6466 // T^ -> A* 6467 if (RHSType->isBlockPointerType()) { 6468 maybeExtendBlockObject(*this, RHS); 6469 Kind = CK_BlockPointerToObjCPointerCast; 6470 return Compatible; 6471 } 6472 6473 return Incompatible; 6474 } 6475 6476 // Conversions from pointers that are not covered by the above. 6477 if (isa<PointerType>(RHSType)) { 6478 // T* -> _Bool 6479 if (LHSType == Context.BoolTy) { 6480 Kind = CK_PointerToBoolean; 6481 return Compatible; 6482 } 6483 6484 // T* -> int 6485 if (LHSType->isIntegerType()) { 6486 Kind = CK_PointerToIntegral; 6487 return PointerToInt; 6488 } 6489 6490 return Incompatible; 6491 } 6492 6493 // Conversions from Objective-C pointers that are not covered by the above. 6494 if (isa<ObjCObjectPointerType>(RHSType)) { 6495 // T* -> _Bool 6496 if (LHSType == Context.BoolTy) { 6497 Kind = CK_PointerToBoolean; 6498 return Compatible; 6499 } 6500 6501 // T* -> int 6502 if (LHSType->isIntegerType()) { 6503 Kind = CK_PointerToIntegral; 6504 return PointerToInt; 6505 } 6506 6507 return Incompatible; 6508 } 6509 6510 // struct A -> struct B 6511 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6512 if (Context.typesAreCompatible(LHSType, RHSType)) { 6513 Kind = CK_NoOp; 6514 return Compatible; 6515 } 6516 } 6517 6518 return Incompatible; 6519 } 6520 6521 /// \brief Constructs a transparent union from an expression that is 6522 /// used to initialize the transparent union. 6523 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6524 ExprResult &EResult, QualType UnionType, 6525 FieldDecl *Field) { 6526 // Build an initializer list that designates the appropriate member 6527 // of the transparent union. 6528 Expr *E = EResult.take(); 6529 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6530 E, SourceLocation()); 6531 Initializer->setType(UnionType); 6532 Initializer->setInitializedFieldInUnion(Field); 6533 6534 // Build a compound literal constructing a value of the transparent 6535 // union type from this initializer list. 6536 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6537 EResult = S.Owned( 6538 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6539 VK_RValue, Initializer, false)); 6540 } 6541 6542 Sema::AssignConvertType 6543 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6544 ExprResult &RHS) { 6545 QualType RHSType = RHS.get()->getType(); 6546 6547 // If the ArgType is a Union type, we want to handle a potential 6548 // transparent_union GCC extension. 6549 const RecordType *UT = ArgType->getAsUnionType(); 6550 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6551 return Incompatible; 6552 6553 // The field to initialize within the transparent union. 6554 RecordDecl *UD = UT->getDecl(); 6555 FieldDecl *InitField = 0; 6556 // It's compatible if the expression matches any of the fields. 6557 for (RecordDecl::field_iterator it = UD->field_begin(), 6558 itend = UD->field_end(); 6559 it != itend; ++it) { 6560 if (it->getType()->isPointerType()) { 6561 // If the transparent union contains a pointer type, we allow: 6562 // 1) void pointer 6563 // 2) null pointer constant 6564 if (RHSType->isPointerType()) 6565 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6566 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6567 InitField = *it; 6568 break; 6569 } 6570 6571 if (RHS.get()->isNullPointerConstant(Context, 6572 Expr::NPC_ValueDependentIsNull)) { 6573 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6574 CK_NullToPointer); 6575 InitField = *it; 6576 break; 6577 } 6578 } 6579 6580 CastKind Kind = CK_Invalid; 6581 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6582 == Compatible) { 6583 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6584 InitField = *it; 6585 break; 6586 } 6587 } 6588 6589 if (!InitField) 6590 return Incompatible; 6591 6592 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6593 return Compatible; 6594 } 6595 6596 Sema::AssignConvertType 6597 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6598 bool Diagnose, 6599 bool DiagnoseCFAudited) { 6600 if (getLangOpts().CPlusPlus) { 6601 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6602 // C++ 5.17p3: If the left operand is not of class type, the 6603 // expression is implicitly converted (C++ 4) to the 6604 // cv-unqualified type of the left operand. 6605 ExprResult Res; 6606 if (Diagnose) { 6607 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6608 AA_Assigning); 6609 } else { 6610 ImplicitConversionSequence ICS = 6611 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6612 /*SuppressUserConversions=*/false, 6613 /*AllowExplicit=*/false, 6614 /*InOverloadResolution=*/false, 6615 /*CStyle=*/false, 6616 /*AllowObjCWritebackConversion=*/false); 6617 if (ICS.isFailure()) 6618 return Incompatible; 6619 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6620 ICS, AA_Assigning); 6621 } 6622 if (Res.isInvalid()) 6623 return Incompatible; 6624 Sema::AssignConvertType result = Compatible; 6625 if (getLangOpts().ObjCAutoRefCount && 6626 !CheckObjCARCUnavailableWeakConversion(LHSType, 6627 RHS.get()->getType())) 6628 result = IncompatibleObjCWeakRef; 6629 RHS = Res; 6630 return result; 6631 } 6632 6633 // FIXME: Currently, we fall through and treat C++ classes like C 6634 // structures. 6635 // FIXME: We also fall through for atomics; not sure what should 6636 // happen there, though. 6637 } 6638 6639 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6640 // a null pointer constant. 6641 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 6642 LHSType->isBlockPointerType()) && 6643 RHS.get()->isNullPointerConstant(Context, 6644 Expr::NPC_ValueDependentIsNull)) { 6645 CastKind Kind; 6646 CXXCastPath Path; 6647 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 6648 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path); 6649 return Compatible; 6650 } 6651 6652 // This check seems unnatural, however it is necessary to ensure the proper 6653 // conversion of functions/arrays. If the conversion were done for all 6654 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6655 // expressions that suppress this implicit conversion (&, sizeof). 6656 // 6657 // Suppress this for references: C++ 8.5.3p5. 6658 if (!LHSType->isReferenceType()) { 6659 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6660 if (RHS.isInvalid()) 6661 return Incompatible; 6662 } 6663 6664 CastKind Kind = CK_Invalid; 6665 Sema::AssignConvertType result = 6666 CheckAssignmentConstraints(LHSType, RHS, Kind); 6667 6668 // C99 6.5.16.1p2: The value of the right operand is converted to the 6669 // type of the assignment expression. 6670 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6671 // so that we can use references in built-in functions even in C. 6672 // The getNonReferenceType() call makes sure that the resulting expression 6673 // does not have reference type. 6674 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6675 QualType Ty = LHSType.getNonLValueExprType(Context); 6676 Expr *E = RHS.take(); 6677 if (getLangOpts().ObjCAutoRefCount) 6678 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6679 DiagnoseCFAudited); 6680 if (getLangOpts().ObjC1 && 6681 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 6682 LHSType, E->getType(), E) || 6683 ConversionToObjCStringLiteralCheck(LHSType, E))) { 6684 RHS = Owned(E); 6685 return Compatible; 6686 } 6687 6688 RHS = ImpCastExprToType(E, Ty, Kind); 6689 } 6690 return result; 6691 } 6692 6693 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6694 ExprResult &RHS) { 6695 Diag(Loc, diag::err_typecheck_invalid_operands) 6696 << LHS.get()->getType() << RHS.get()->getType() 6697 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6698 return QualType(); 6699 } 6700 6701 /// Try to convert a value of non-vector type to a vector type by 6702 /// promoting (and only promoting) the type to the element type of the 6703 /// vector and then performing a vector splat. 6704 /// 6705 /// \param scalar - if non-null, actually perform the conversions 6706 /// \return true if the operation fails (but without diagnosing the failure) 6707 static bool tryVectorPromoteAndSplat(Sema &S, ExprResult *scalar, 6708 QualType scalarTy, 6709 QualType vectorEltTy, 6710 QualType vectorTy) { 6711 // The conversion to apply to the scalar before splatting it, 6712 // if necessary. 6713 CastKind scalarCast = CK_Invalid; 6714 6715 if (vectorEltTy->isIntegralType(S.Context)) { 6716 if (!scalarTy->isIntegralType(S.Context)) return true; 6717 int order = S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy); 6718 if (order < 0) return true; 6719 if (order > 0) scalarCast = CK_IntegralCast; 6720 } else if (vectorEltTy->isRealFloatingType()) { 6721 if (scalarTy->isRealFloatingType()) { 6722 int order = S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy); 6723 if (order < 0) return true; 6724 if (order > 0) scalarCast = CK_FloatingCast; 6725 } else if (scalarTy->isIntegralType(S.Context)) { 6726 scalarCast = CK_IntegralToFloating; 6727 } else { 6728 return true; 6729 } 6730 } else { 6731 return true; 6732 } 6733 6734 // Adjust scalar if desired. 6735 if (scalar) { 6736 if (scalarCast != CK_Invalid) 6737 *scalar = S.ImpCastExprToType(scalar->take(), vectorEltTy, scalarCast); 6738 *scalar = S.ImpCastExprToType(scalar->take(), vectorTy, CK_VectorSplat); 6739 } 6740 return false; 6741 } 6742 6743 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6744 SourceLocation Loc, bool IsCompAssign) { 6745 if (!IsCompAssign) { 6746 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6747 if (LHS.isInvalid()) 6748 return QualType(); 6749 } 6750 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6751 if (RHS.isInvalid()) 6752 return QualType(); 6753 6754 // For conversion purposes, we ignore any qualifiers. 6755 // For example, "const float" and "float" are equivalent. 6756 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 6757 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 6758 6759 // If the vector types are identical, return. 6760 if (Context.hasSameType(LHSType, RHSType)) 6761 return LHSType; 6762 6763 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 6764 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 6765 assert(LHSVecType || RHSVecType); 6766 6767 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 6768 if (LHSVecType && RHSVecType && 6769 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6770 if (isa<ExtVectorType>(LHSVecType)) { 6771 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6772 return LHSType; 6773 } 6774 6775 if (!IsCompAssign) 6776 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6777 return RHSType; 6778 } 6779 6780 // If we're allowing lax vector conversions, only the total (data) size 6781 // needs to be the same. 6782 // FIXME: Should we really be allowing this? 6783 // FIXME: We really just pick the LHS type arbitrarily? 6784 if (isLaxVectorConversion(RHSType, LHSType)) { 6785 QualType resultType = LHSType; 6786 RHS = ImpCastExprToType(RHS.take(), resultType, CK_BitCast); 6787 return resultType; 6788 } 6789 6790 // If there's an ext-vector type and a scalar, try to promote (and 6791 // only promote) and splat the scalar to the vector type. 6792 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 6793 if (!tryVectorPromoteAndSplat(*this, &RHS, RHSType, 6794 LHSVecType->getElementType(), LHSType)) 6795 return LHSType; 6796 } 6797 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 6798 if (!tryVectorPromoteAndSplat(*this, (IsCompAssign ? 0 : &LHS), LHSType, 6799 RHSVecType->getElementType(), RHSType)) 6800 return RHSType; 6801 } 6802 6803 // Okay, the expression is invalid. 6804 6805 // If there's a non-vector, non-real operand, diagnose that. 6806 if ((!RHSVecType && !RHSType->isRealType()) || 6807 (!LHSVecType && !LHSType->isRealType())) { 6808 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 6809 << LHSType << RHSType 6810 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6811 return QualType(); 6812 } 6813 6814 // Otherwise, use the generic diagnostic. 6815 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6816 << LHSType << RHSType 6817 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6818 return QualType(); 6819 } 6820 6821 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6822 // expression. These are mainly cases where the null pointer is used as an 6823 // integer instead of a pointer. 6824 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6825 SourceLocation Loc, bool IsCompare) { 6826 // The canonical way to check for a GNU null is with isNullPointerConstant, 6827 // but we use a bit of a hack here for speed; this is a relatively 6828 // hot path, and isNullPointerConstant is slow. 6829 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6830 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6831 6832 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6833 6834 // Avoid analyzing cases where the result will either be invalid (and 6835 // diagnosed as such) or entirely valid and not something to warn about. 6836 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6837 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6838 return; 6839 6840 // Comparison operations would not make sense with a null pointer no matter 6841 // what the other expression is. 6842 if (!IsCompare) { 6843 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6844 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6845 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6846 return; 6847 } 6848 6849 // The rest of the operations only make sense with a null pointer 6850 // if the other expression is a pointer. 6851 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6852 NonNullType->canDecayToPointerType()) 6853 return; 6854 6855 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6856 << LHSNull /* LHS is NULL */ << NonNullType 6857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6858 } 6859 6860 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6861 SourceLocation Loc, 6862 bool IsCompAssign, bool IsDiv) { 6863 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6864 6865 if (LHS.get()->getType()->isVectorType() || 6866 RHS.get()->getType()->isVectorType()) 6867 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6868 6869 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6870 if (LHS.isInvalid() || RHS.isInvalid()) 6871 return QualType(); 6872 6873 6874 if (compType.isNull() || !compType->isArithmeticType()) 6875 return InvalidOperands(Loc, LHS, RHS); 6876 6877 // Check for division by zero. 6878 llvm::APSInt RHSValue; 6879 if (IsDiv && !RHS.get()->isValueDependent() && 6880 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6881 DiagRuntimeBehavior(Loc, RHS.get(), 6882 PDiag(diag::warn_division_by_zero) 6883 << RHS.get()->getSourceRange()); 6884 6885 return compType; 6886 } 6887 6888 QualType Sema::CheckRemainderOperands( 6889 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6890 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6891 6892 if (LHS.get()->getType()->isVectorType() || 6893 RHS.get()->getType()->isVectorType()) { 6894 if (LHS.get()->getType()->hasIntegerRepresentation() && 6895 RHS.get()->getType()->hasIntegerRepresentation()) 6896 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6897 return InvalidOperands(Loc, LHS, RHS); 6898 } 6899 6900 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6901 if (LHS.isInvalid() || RHS.isInvalid()) 6902 return QualType(); 6903 6904 if (compType.isNull() || !compType->isIntegerType()) 6905 return InvalidOperands(Loc, LHS, RHS); 6906 6907 // Check for remainder by zero. 6908 llvm::APSInt RHSValue; 6909 if (!RHS.get()->isValueDependent() && 6910 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6911 DiagRuntimeBehavior(Loc, RHS.get(), 6912 PDiag(diag::warn_remainder_by_zero) 6913 << RHS.get()->getSourceRange()); 6914 6915 return compType; 6916 } 6917 6918 /// \brief Diagnose invalid arithmetic on two void pointers. 6919 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6920 Expr *LHSExpr, Expr *RHSExpr) { 6921 S.Diag(Loc, S.getLangOpts().CPlusPlus 6922 ? diag::err_typecheck_pointer_arith_void_type 6923 : diag::ext_gnu_void_ptr) 6924 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6925 << RHSExpr->getSourceRange(); 6926 } 6927 6928 /// \brief Diagnose invalid arithmetic on a void pointer. 6929 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6930 Expr *Pointer) { 6931 S.Diag(Loc, S.getLangOpts().CPlusPlus 6932 ? diag::err_typecheck_pointer_arith_void_type 6933 : diag::ext_gnu_void_ptr) 6934 << 0 /* one pointer */ << Pointer->getSourceRange(); 6935 } 6936 6937 /// \brief Diagnose invalid arithmetic on two function pointers. 6938 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6939 Expr *LHS, Expr *RHS) { 6940 assert(LHS->getType()->isAnyPointerType()); 6941 assert(RHS->getType()->isAnyPointerType()); 6942 S.Diag(Loc, S.getLangOpts().CPlusPlus 6943 ? diag::err_typecheck_pointer_arith_function_type 6944 : diag::ext_gnu_ptr_func_arith) 6945 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6946 // We only show the second type if it differs from the first. 6947 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6948 RHS->getType()) 6949 << RHS->getType()->getPointeeType() 6950 << LHS->getSourceRange() << RHS->getSourceRange(); 6951 } 6952 6953 /// \brief Diagnose invalid arithmetic on a function pointer. 6954 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6955 Expr *Pointer) { 6956 assert(Pointer->getType()->isAnyPointerType()); 6957 S.Diag(Loc, S.getLangOpts().CPlusPlus 6958 ? diag::err_typecheck_pointer_arith_function_type 6959 : diag::ext_gnu_ptr_func_arith) 6960 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6961 << 0 /* one pointer, so only one type */ 6962 << Pointer->getSourceRange(); 6963 } 6964 6965 /// \brief Emit error if Operand is incomplete pointer type 6966 /// 6967 /// \returns True if pointer has incomplete type 6968 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6969 Expr *Operand) { 6970 assert(Operand->getType()->isAnyPointerType() && 6971 !Operand->getType()->isDependentType()); 6972 QualType PointeeTy = Operand->getType()->getPointeeType(); 6973 return S.RequireCompleteType(Loc, PointeeTy, 6974 diag::err_typecheck_arithmetic_incomplete_type, 6975 PointeeTy, Operand->getSourceRange()); 6976 } 6977 6978 /// \brief Check the validity of an arithmetic pointer operand. 6979 /// 6980 /// If the operand has pointer type, this code will check for pointer types 6981 /// which are invalid in arithmetic operations. These will be diagnosed 6982 /// appropriately, including whether or not the use is supported as an 6983 /// extension. 6984 /// 6985 /// \returns True when the operand is valid to use (even if as an extension). 6986 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6987 Expr *Operand) { 6988 if (!Operand->getType()->isAnyPointerType()) return true; 6989 6990 QualType PointeeTy = Operand->getType()->getPointeeType(); 6991 if (PointeeTy->isVoidType()) { 6992 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6993 return !S.getLangOpts().CPlusPlus; 6994 } 6995 if (PointeeTy->isFunctionType()) { 6996 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6997 return !S.getLangOpts().CPlusPlus; 6998 } 6999 7000 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7001 7002 return true; 7003 } 7004 7005 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7006 /// operands. 7007 /// 7008 /// This routine will diagnose any invalid arithmetic on pointer operands much 7009 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7010 /// for emitting a single diagnostic even for operations where both LHS and RHS 7011 /// are (potentially problematic) pointers. 7012 /// 7013 /// \returns True when the operand is valid to use (even if as an extension). 7014 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7015 Expr *LHSExpr, Expr *RHSExpr) { 7016 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7017 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7018 if (!isLHSPointer && !isRHSPointer) return true; 7019 7020 QualType LHSPointeeTy, RHSPointeeTy; 7021 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7022 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7023 7024 // Check for arithmetic on pointers to incomplete types. 7025 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7026 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7027 if (isLHSVoidPtr || isRHSVoidPtr) { 7028 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7029 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7030 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7031 7032 return !S.getLangOpts().CPlusPlus; 7033 } 7034 7035 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7036 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7037 if (isLHSFuncPtr || isRHSFuncPtr) { 7038 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7039 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7040 RHSExpr); 7041 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7042 7043 return !S.getLangOpts().CPlusPlus; 7044 } 7045 7046 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7047 return false; 7048 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7049 return false; 7050 7051 return true; 7052 } 7053 7054 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7055 /// literal. 7056 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7057 Expr *LHSExpr, Expr *RHSExpr) { 7058 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7059 Expr* IndexExpr = RHSExpr; 7060 if (!StrExpr) { 7061 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7062 IndexExpr = LHSExpr; 7063 } 7064 7065 bool IsStringPlusInt = StrExpr && 7066 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7067 if (!IsStringPlusInt) 7068 return; 7069 7070 llvm::APSInt index; 7071 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7072 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7073 if (index.isNonNegative() && 7074 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7075 index.isUnsigned())) 7076 return; 7077 } 7078 7079 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7080 Self.Diag(OpLoc, diag::warn_string_plus_int) 7081 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7082 7083 // Only print a fixit for "str" + int, not for int + "str". 7084 if (IndexExpr == RHSExpr) { 7085 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7086 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7087 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7088 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7089 << FixItHint::CreateInsertion(EndLoc, "]"); 7090 } else 7091 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7092 } 7093 7094 /// \brief Emit a warning when adding a char literal to a string. 7095 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7096 Expr *LHSExpr, Expr *RHSExpr) { 7097 const DeclRefExpr *StringRefExpr = 7098 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts()); 7099 const CharacterLiteral *CharExpr = 7100 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7101 if (!StringRefExpr) { 7102 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts()); 7103 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7104 } 7105 7106 if (!CharExpr || !StringRefExpr) 7107 return; 7108 7109 const QualType StringType = StringRefExpr->getType(); 7110 7111 // Return if not a PointerType. 7112 if (!StringType->isAnyPointerType()) 7113 return; 7114 7115 // Return if not a CharacterType. 7116 if (!StringType->getPointeeType()->isAnyCharacterType()) 7117 return; 7118 7119 ASTContext &Ctx = Self.getASTContext(); 7120 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7121 7122 const QualType CharType = CharExpr->getType(); 7123 if (!CharType->isAnyCharacterType() && 7124 CharType->isIntegerType() && 7125 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7126 Self.Diag(OpLoc, diag::warn_string_plus_char) 7127 << DiagRange << Ctx.CharTy; 7128 } else { 7129 Self.Diag(OpLoc, diag::warn_string_plus_char) 7130 << DiagRange << CharExpr->getType(); 7131 } 7132 7133 // Only print a fixit for str + char, not for char + str. 7134 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7135 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7136 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7137 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7138 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7139 << FixItHint::CreateInsertion(EndLoc, "]"); 7140 } else { 7141 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7142 } 7143 } 7144 7145 /// \brief Emit error when two pointers are incompatible. 7146 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7147 Expr *LHSExpr, Expr *RHSExpr) { 7148 assert(LHSExpr->getType()->isAnyPointerType()); 7149 assert(RHSExpr->getType()->isAnyPointerType()); 7150 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7151 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7152 << RHSExpr->getSourceRange(); 7153 } 7154 7155 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7156 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7157 QualType* CompLHSTy) { 7158 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7159 7160 if (LHS.get()->getType()->isVectorType() || 7161 RHS.get()->getType()->isVectorType()) { 7162 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7163 if (CompLHSTy) *CompLHSTy = compType; 7164 return compType; 7165 } 7166 7167 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7168 if (LHS.isInvalid() || RHS.isInvalid()) 7169 return QualType(); 7170 7171 // Diagnose "string literal" '+' int and string '+' "char literal". 7172 if (Opc == BO_Add) { 7173 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7174 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7175 } 7176 7177 // handle the common case first (both operands are arithmetic). 7178 if (!compType.isNull() && compType->isArithmeticType()) { 7179 if (CompLHSTy) *CompLHSTy = compType; 7180 return compType; 7181 } 7182 7183 // Type-checking. Ultimately the pointer's going to be in PExp; 7184 // note that we bias towards the LHS being the pointer. 7185 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7186 7187 bool isObjCPointer; 7188 if (PExp->getType()->isPointerType()) { 7189 isObjCPointer = false; 7190 } else if (PExp->getType()->isObjCObjectPointerType()) { 7191 isObjCPointer = true; 7192 } else { 7193 std::swap(PExp, IExp); 7194 if (PExp->getType()->isPointerType()) { 7195 isObjCPointer = false; 7196 } else if (PExp->getType()->isObjCObjectPointerType()) { 7197 isObjCPointer = true; 7198 } else { 7199 return InvalidOperands(Loc, LHS, RHS); 7200 } 7201 } 7202 assert(PExp->getType()->isAnyPointerType()); 7203 7204 if (!IExp->getType()->isIntegerType()) 7205 return InvalidOperands(Loc, LHS, RHS); 7206 7207 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7208 return QualType(); 7209 7210 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7211 return QualType(); 7212 7213 // Check array bounds for pointer arithemtic 7214 CheckArrayAccess(PExp, IExp); 7215 7216 if (CompLHSTy) { 7217 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7218 if (LHSTy.isNull()) { 7219 LHSTy = LHS.get()->getType(); 7220 if (LHSTy->isPromotableIntegerType()) 7221 LHSTy = Context.getPromotedIntegerType(LHSTy); 7222 } 7223 *CompLHSTy = LHSTy; 7224 } 7225 7226 return PExp->getType(); 7227 } 7228 7229 // C99 6.5.6 7230 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7231 SourceLocation Loc, 7232 QualType* CompLHSTy) { 7233 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7234 7235 if (LHS.get()->getType()->isVectorType() || 7236 RHS.get()->getType()->isVectorType()) { 7237 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7238 if (CompLHSTy) *CompLHSTy = compType; 7239 return compType; 7240 } 7241 7242 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7243 if (LHS.isInvalid() || RHS.isInvalid()) 7244 return QualType(); 7245 7246 // Enforce type constraints: C99 6.5.6p3. 7247 7248 // Handle the common case first (both operands are arithmetic). 7249 if (!compType.isNull() && compType->isArithmeticType()) { 7250 if (CompLHSTy) *CompLHSTy = compType; 7251 return compType; 7252 } 7253 7254 // Either ptr - int or ptr - ptr. 7255 if (LHS.get()->getType()->isAnyPointerType()) { 7256 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7257 7258 // Diagnose bad cases where we step over interface counts. 7259 if (LHS.get()->getType()->isObjCObjectPointerType() && 7260 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7261 return QualType(); 7262 7263 // The result type of a pointer-int computation is the pointer type. 7264 if (RHS.get()->getType()->isIntegerType()) { 7265 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7266 return QualType(); 7267 7268 // Check array bounds for pointer arithemtic 7269 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 7270 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7271 7272 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7273 return LHS.get()->getType(); 7274 } 7275 7276 // Handle pointer-pointer subtractions. 7277 if (const PointerType *RHSPTy 7278 = RHS.get()->getType()->getAs<PointerType>()) { 7279 QualType rpointee = RHSPTy->getPointeeType(); 7280 7281 if (getLangOpts().CPlusPlus) { 7282 // Pointee types must be the same: C++ [expr.add] 7283 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7284 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7285 } 7286 } else { 7287 // Pointee types must be compatible C99 6.5.6p3 7288 if (!Context.typesAreCompatible( 7289 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7290 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7291 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7292 return QualType(); 7293 } 7294 } 7295 7296 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7297 LHS.get(), RHS.get())) 7298 return QualType(); 7299 7300 // The pointee type may have zero size. As an extension, a structure or 7301 // union may have zero size or an array may have zero length. In this 7302 // case subtraction does not make sense. 7303 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7304 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7305 if (ElementSize.isZero()) { 7306 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7307 << rpointee.getUnqualifiedType() 7308 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7309 } 7310 } 7311 7312 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7313 return Context.getPointerDiffType(); 7314 } 7315 } 7316 7317 return InvalidOperands(Loc, LHS, RHS); 7318 } 7319 7320 static bool isScopedEnumerationType(QualType T) { 7321 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7322 return ET->getDecl()->isScoped(); 7323 return false; 7324 } 7325 7326 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7327 SourceLocation Loc, unsigned Opc, 7328 QualType LHSType) { 7329 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7330 // so skip remaining warnings as we don't want to modify values within Sema. 7331 if (S.getLangOpts().OpenCL) 7332 return; 7333 7334 llvm::APSInt Right; 7335 // Check right/shifter operand 7336 if (RHS.get()->isValueDependent() || 7337 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7338 return; 7339 7340 if (Right.isNegative()) { 7341 S.DiagRuntimeBehavior(Loc, RHS.get(), 7342 S.PDiag(diag::warn_shift_negative) 7343 << RHS.get()->getSourceRange()); 7344 return; 7345 } 7346 llvm::APInt LeftBits(Right.getBitWidth(), 7347 S.Context.getTypeSize(LHS.get()->getType())); 7348 if (Right.uge(LeftBits)) { 7349 S.DiagRuntimeBehavior(Loc, RHS.get(), 7350 S.PDiag(diag::warn_shift_gt_typewidth) 7351 << RHS.get()->getSourceRange()); 7352 return; 7353 } 7354 if (Opc != BO_Shl) 7355 return; 7356 7357 // When left shifting an ICE which is signed, we can check for overflow which 7358 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7359 // integers have defined behavior modulo one more than the maximum value 7360 // representable in the result type, so never warn for those. 7361 llvm::APSInt Left; 7362 if (LHS.get()->isValueDependent() || 7363 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7364 LHSType->hasUnsignedIntegerRepresentation()) 7365 return; 7366 llvm::APInt ResultBits = 7367 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7368 if (LeftBits.uge(ResultBits)) 7369 return; 7370 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7371 Result = Result.shl(Right); 7372 7373 // Print the bit representation of the signed integer as an unsigned 7374 // hexadecimal number. 7375 SmallString<40> HexResult; 7376 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7377 7378 // If we are only missing a sign bit, this is less likely to result in actual 7379 // bugs -- if the result is cast back to an unsigned type, it will have the 7380 // expected value. Thus we place this behind a different warning that can be 7381 // turned off separately if needed. 7382 if (LeftBits == ResultBits - 1) { 7383 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7384 << HexResult.str() << LHSType 7385 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7386 return; 7387 } 7388 7389 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7390 << HexResult.str() << Result.getMinSignedBits() << LHSType 7391 << Left.getBitWidth() << LHS.get()->getSourceRange() 7392 << RHS.get()->getSourceRange(); 7393 } 7394 7395 // C99 6.5.7 7396 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7397 SourceLocation Loc, unsigned Opc, 7398 bool IsCompAssign) { 7399 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7400 7401 // Vector shifts promote their scalar inputs to vector type. 7402 if (LHS.get()->getType()->isVectorType() || 7403 RHS.get()->getType()->isVectorType()) 7404 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7405 7406 // Shifts don't perform usual arithmetic conversions, they just do integer 7407 // promotions on each operand. C99 6.5.7p3 7408 7409 // For the LHS, do usual unary conversions, but then reset them away 7410 // if this is a compound assignment. 7411 ExprResult OldLHS = LHS; 7412 LHS = UsualUnaryConversions(LHS.take()); 7413 if (LHS.isInvalid()) 7414 return QualType(); 7415 QualType LHSType = LHS.get()->getType(); 7416 if (IsCompAssign) LHS = OldLHS; 7417 7418 // The RHS is simpler. 7419 RHS = UsualUnaryConversions(RHS.take()); 7420 if (RHS.isInvalid()) 7421 return QualType(); 7422 QualType RHSType = RHS.get()->getType(); 7423 7424 // C99 6.5.7p2: Each of the operands shall have integer type. 7425 if (!LHSType->hasIntegerRepresentation() || 7426 !RHSType->hasIntegerRepresentation()) 7427 return InvalidOperands(Loc, LHS, RHS); 7428 7429 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7430 // hasIntegerRepresentation() above instead of this. 7431 if (isScopedEnumerationType(LHSType) || 7432 isScopedEnumerationType(RHSType)) { 7433 return InvalidOperands(Loc, LHS, RHS); 7434 } 7435 // Sanity-check shift operands 7436 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7437 7438 // "The type of the result is that of the promoted left operand." 7439 return LHSType; 7440 } 7441 7442 static bool IsWithinTemplateSpecialization(Decl *D) { 7443 if (DeclContext *DC = D->getDeclContext()) { 7444 if (isa<ClassTemplateSpecializationDecl>(DC)) 7445 return true; 7446 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7447 return FD->isFunctionTemplateSpecialization(); 7448 } 7449 return false; 7450 } 7451 7452 /// If two different enums are compared, raise a warning. 7453 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7454 Expr *RHS) { 7455 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7456 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7457 7458 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7459 if (!LHSEnumType) 7460 return; 7461 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7462 if (!RHSEnumType) 7463 return; 7464 7465 // Ignore anonymous enums. 7466 if (!LHSEnumType->getDecl()->getIdentifier()) 7467 return; 7468 if (!RHSEnumType->getDecl()->getIdentifier()) 7469 return; 7470 7471 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7472 return; 7473 7474 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7475 << LHSStrippedType << RHSStrippedType 7476 << LHS->getSourceRange() << RHS->getSourceRange(); 7477 } 7478 7479 /// \brief Diagnose bad pointer comparisons. 7480 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7481 ExprResult &LHS, ExprResult &RHS, 7482 bool IsError) { 7483 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7484 : diag::ext_typecheck_comparison_of_distinct_pointers) 7485 << LHS.get()->getType() << RHS.get()->getType() 7486 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7487 } 7488 7489 /// \brief Returns false if the pointers are converted to a composite type, 7490 /// true otherwise. 7491 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7492 ExprResult &LHS, ExprResult &RHS) { 7493 // C++ [expr.rel]p2: 7494 // [...] Pointer conversions (4.10) and qualification 7495 // conversions (4.4) are performed on pointer operands (or on 7496 // a pointer operand and a null pointer constant) to bring 7497 // them to their composite pointer type. [...] 7498 // 7499 // C++ [expr.eq]p1 uses the same notion for (in)equality 7500 // comparisons of pointers. 7501 7502 // C++ [expr.eq]p2: 7503 // In addition, pointers to members can be compared, or a pointer to 7504 // member and a null pointer constant. Pointer to member conversions 7505 // (4.11) and qualification conversions (4.4) are performed to bring 7506 // them to a common type. If one operand is a null pointer constant, 7507 // the common type is the type of the other operand. Otherwise, the 7508 // common type is a pointer to member type similar (4.4) to the type 7509 // of one of the operands, with a cv-qualification signature (4.4) 7510 // that is the union of the cv-qualification signatures of the operand 7511 // types. 7512 7513 QualType LHSType = LHS.get()->getType(); 7514 QualType RHSType = RHS.get()->getType(); 7515 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7516 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7517 7518 bool NonStandardCompositeType = false; 7519 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7520 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7521 if (T.isNull()) { 7522 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7523 return true; 7524 } 7525 7526 if (NonStandardCompositeType) 7527 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7528 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7529 << RHS.get()->getSourceRange(); 7530 7531 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7532 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7533 return false; 7534 } 7535 7536 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7537 ExprResult &LHS, 7538 ExprResult &RHS, 7539 bool IsError) { 7540 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7541 : diag::ext_typecheck_comparison_of_fptr_to_void) 7542 << LHS.get()->getType() << RHS.get()->getType() 7543 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7544 } 7545 7546 static bool isObjCObjectLiteral(ExprResult &E) { 7547 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7548 case Stmt::ObjCArrayLiteralClass: 7549 case Stmt::ObjCDictionaryLiteralClass: 7550 case Stmt::ObjCStringLiteralClass: 7551 case Stmt::ObjCBoxedExprClass: 7552 return true; 7553 default: 7554 // Note that ObjCBoolLiteral is NOT an object literal! 7555 return false; 7556 } 7557 } 7558 7559 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7560 const ObjCObjectPointerType *Type = 7561 LHS->getType()->getAs<ObjCObjectPointerType>(); 7562 7563 // If this is not actually an Objective-C object, bail out. 7564 if (!Type) 7565 return false; 7566 7567 // Get the LHS object's interface type. 7568 QualType InterfaceType = Type->getPointeeType(); 7569 if (const ObjCObjectType *iQFaceTy = 7570 InterfaceType->getAsObjCQualifiedInterfaceType()) 7571 InterfaceType = iQFaceTy->getBaseType(); 7572 7573 // If the RHS isn't an Objective-C object, bail out. 7574 if (!RHS->getType()->isObjCObjectPointerType()) 7575 return false; 7576 7577 // Try to find the -isEqual: method. 7578 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7579 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7580 InterfaceType, 7581 /*instance=*/true); 7582 if (!Method) { 7583 if (Type->isObjCIdType()) { 7584 // For 'id', just check the global pool. 7585 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7586 /*receiverId=*/true, 7587 /*warn=*/false); 7588 } else { 7589 // Check protocols. 7590 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7591 /*instance=*/true); 7592 } 7593 } 7594 7595 if (!Method) 7596 return false; 7597 7598 QualType T = Method->param_begin()[0]->getType(); 7599 if (!T->isObjCObjectPointerType()) 7600 return false; 7601 7602 QualType R = Method->getReturnType(); 7603 if (!R->isScalarType()) 7604 return false; 7605 7606 return true; 7607 } 7608 7609 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7610 FromE = FromE->IgnoreParenImpCasts(); 7611 switch (FromE->getStmtClass()) { 7612 default: 7613 break; 7614 case Stmt::ObjCStringLiteralClass: 7615 // "string literal" 7616 return LK_String; 7617 case Stmt::ObjCArrayLiteralClass: 7618 // "array literal" 7619 return LK_Array; 7620 case Stmt::ObjCDictionaryLiteralClass: 7621 // "dictionary literal" 7622 return LK_Dictionary; 7623 case Stmt::BlockExprClass: 7624 return LK_Block; 7625 case Stmt::ObjCBoxedExprClass: { 7626 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7627 switch (Inner->getStmtClass()) { 7628 case Stmt::IntegerLiteralClass: 7629 case Stmt::FloatingLiteralClass: 7630 case Stmt::CharacterLiteralClass: 7631 case Stmt::ObjCBoolLiteralExprClass: 7632 case Stmt::CXXBoolLiteralExprClass: 7633 // "numeric literal" 7634 return LK_Numeric; 7635 case Stmt::ImplicitCastExprClass: { 7636 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7637 // Boolean literals can be represented by implicit casts. 7638 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7639 return LK_Numeric; 7640 break; 7641 } 7642 default: 7643 break; 7644 } 7645 return LK_Boxed; 7646 } 7647 } 7648 return LK_None; 7649 } 7650 7651 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7652 ExprResult &LHS, ExprResult &RHS, 7653 BinaryOperator::Opcode Opc){ 7654 Expr *Literal; 7655 Expr *Other; 7656 if (isObjCObjectLiteral(LHS)) { 7657 Literal = LHS.get(); 7658 Other = RHS.get(); 7659 } else { 7660 Literal = RHS.get(); 7661 Other = LHS.get(); 7662 } 7663 7664 // Don't warn on comparisons against nil. 7665 Other = Other->IgnoreParenCasts(); 7666 if (Other->isNullPointerConstant(S.getASTContext(), 7667 Expr::NPC_ValueDependentIsNotNull)) 7668 return; 7669 7670 // This should be kept in sync with warn_objc_literal_comparison. 7671 // LK_String should always be after the other literals, since it has its own 7672 // warning flag. 7673 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7674 assert(LiteralKind != Sema::LK_Block); 7675 if (LiteralKind == Sema::LK_None) { 7676 llvm_unreachable("Unknown Objective-C object literal kind"); 7677 } 7678 7679 if (LiteralKind == Sema::LK_String) 7680 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7681 << Literal->getSourceRange(); 7682 else 7683 S.Diag(Loc, diag::warn_objc_literal_comparison) 7684 << LiteralKind << Literal->getSourceRange(); 7685 7686 if (BinaryOperator::isEqualityOp(Opc) && 7687 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7688 SourceLocation Start = LHS.get()->getLocStart(); 7689 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7690 CharSourceRange OpRange = 7691 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7692 7693 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7694 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7695 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7696 << FixItHint::CreateInsertion(End, "]"); 7697 } 7698 } 7699 7700 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7701 ExprResult &RHS, 7702 SourceLocation Loc, 7703 unsigned OpaqueOpc) { 7704 // This checking requires bools. 7705 if (!S.getLangOpts().Bool) return; 7706 7707 // Check that left hand side is !something. 7708 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7709 if (!UO || UO->getOpcode() != UO_LNot) return; 7710 7711 // Only check if the right hand side is non-bool arithmetic type. 7712 if (RHS.get()->getType()->isBooleanType()) return; 7713 7714 // Make sure that the something in !something is not bool. 7715 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7716 if (SubExpr->getType()->isBooleanType()) return; 7717 7718 // Emit warning. 7719 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7720 << Loc; 7721 7722 // First note suggest !(x < y) 7723 SourceLocation FirstOpen = SubExpr->getLocStart(); 7724 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7725 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7726 if (FirstClose.isInvalid()) 7727 FirstOpen = SourceLocation(); 7728 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7729 << FixItHint::CreateInsertion(FirstOpen, "(") 7730 << FixItHint::CreateInsertion(FirstClose, ")"); 7731 7732 // Second note suggests (!x) < y 7733 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7734 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7735 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7736 if (SecondClose.isInvalid()) 7737 SecondOpen = SourceLocation(); 7738 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7739 << FixItHint::CreateInsertion(SecondOpen, "(") 7740 << FixItHint::CreateInsertion(SecondClose, ")"); 7741 } 7742 7743 // Get the decl for a simple expression: a reference to a variable, 7744 // an implicit C++ field reference, or an implicit ObjC ivar reference. 7745 static ValueDecl *getCompareDecl(Expr *E) { 7746 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7747 return DR->getDecl(); 7748 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7749 if (Ivar->isFreeIvar()) 7750 return Ivar->getDecl(); 7751 } 7752 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7753 if (Mem->isImplicitAccess()) 7754 return Mem->getMemberDecl(); 7755 } 7756 return 0; 7757 } 7758 7759 // C99 6.5.8, C++ [expr.rel] 7760 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7761 SourceLocation Loc, unsigned OpaqueOpc, 7762 bool IsRelational) { 7763 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7764 7765 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7766 7767 // Handle vector comparisons separately. 7768 if (LHS.get()->getType()->isVectorType() || 7769 RHS.get()->getType()->isVectorType()) 7770 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7771 7772 QualType LHSType = LHS.get()->getType(); 7773 QualType RHSType = RHS.get()->getType(); 7774 7775 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7776 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7777 7778 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7779 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7780 7781 if (!LHSType->hasFloatingRepresentation() && 7782 !(LHSType->isBlockPointerType() && IsRelational) && 7783 !LHS.get()->getLocStart().isMacroID() && 7784 !RHS.get()->getLocStart().isMacroID() && 7785 ActiveTemplateInstantiations.empty()) { 7786 // For non-floating point types, check for self-comparisons of the form 7787 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7788 // often indicate logic errors in the program. 7789 // 7790 // NOTE: Don't warn about comparison expressions resulting from macro 7791 // expansion. Also don't warn about comparisons which are only self 7792 // comparisons within a template specialization. The warnings should catch 7793 // obvious cases in the definition of the template anyways. The idea is to 7794 // warn when the typed comparison operator will always evaluate to the same 7795 // result. 7796 ValueDecl *DL = getCompareDecl(LHSStripped); 7797 ValueDecl *DR = getCompareDecl(RHSStripped); 7798 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7799 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7800 << 0 // self- 7801 << (Opc == BO_EQ 7802 || Opc == BO_LE 7803 || Opc == BO_GE)); 7804 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7805 !DL->getType()->isReferenceType() && 7806 !DR->getType()->isReferenceType()) { 7807 // what is it always going to eval to? 7808 char always_evals_to; 7809 switch(Opc) { 7810 case BO_EQ: // e.g. array1 == array2 7811 always_evals_to = 0; // false 7812 break; 7813 case BO_NE: // e.g. array1 != array2 7814 always_evals_to = 1; // true 7815 break; 7816 default: 7817 // best we can say is 'a constant' 7818 always_evals_to = 2; // e.g. array1 <= array2 7819 break; 7820 } 7821 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7822 << 1 // array 7823 << always_evals_to); 7824 } 7825 7826 if (isa<CastExpr>(LHSStripped)) 7827 LHSStripped = LHSStripped->IgnoreParenCasts(); 7828 if (isa<CastExpr>(RHSStripped)) 7829 RHSStripped = RHSStripped->IgnoreParenCasts(); 7830 7831 // Warn about comparisons against a string constant (unless the other 7832 // operand is null), the user probably wants strcmp. 7833 Expr *literalString = 0; 7834 Expr *literalStringStripped = 0; 7835 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7836 !RHSStripped->isNullPointerConstant(Context, 7837 Expr::NPC_ValueDependentIsNull)) { 7838 literalString = LHS.get(); 7839 literalStringStripped = LHSStripped; 7840 } else if ((isa<StringLiteral>(RHSStripped) || 7841 isa<ObjCEncodeExpr>(RHSStripped)) && 7842 !LHSStripped->isNullPointerConstant(Context, 7843 Expr::NPC_ValueDependentIsNull)) { 7844 literalString = RHS.get(); 7845 literalStringStripped = RHSStripped; 7846 } 7847 7848 if (literalString) { 7849 DiagRuntimeBehavior(Loc, 0, 7850 PDiag(diag::warn_stringcompare) 7851 << isa<ObjCEncodeExpr>(literalStringStripped) 7852 << literalString->getSourceRange()); 7853 } 7854 } 7855 7856 // C99 6.5.8p3 / C99 6.5.9p4 7857 UsualArithmeticConversions(LHS, RHS); 7858 if (LHS.isInvalid() || RHS.isInvalid()) 7859 return QualType(); 7860 7861 LHSType = LHS.get()->getType(); 7862 RHSType = RHS.get()->getType(); 7863 7864 // The result of comparisons is 'bool' in C++, 'int' in C. 7865 QualType ResultTy = Context.getLogicalOperationType(); 7866 7867 if (IsRelational) { 7868 if (LHSType->isRealType() && RHSType->isRealType()) 7869 return ResultTy; 7870 } else { 7871 // Check for comparisons of floating point operands using != and ==. 7872 if (LHSType->hasFloatingRepresentation()) 7873 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7874 7875 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7876 return ResultTy; 7877 } 7878 7879 const Expr::NullPointerConstantKind LHSNullKind = 7880 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7881 const Expr::NullPointerConstantKind RHSNullKind = 7882 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7883 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 7884 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 7885 7886 if (!IsRelational && LHSIsNull != RHSIsNull) { 7887 bool IsEquality = Opc == BO_EQ; 7888 if (RHSIsNull) 7889 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 7890 RHS.get()->getSourceRange()); 7891 else 7892 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 7893 LHS.get()->getSourceRange()); 7894 } 7895 7896 // All of the following pointer-related warnings are GCC extensions, except 7897 // when handling null pointer constants. 7898 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7899 QualType LCanPointeeTy = 7900 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7901 QualType RCanPointeeTy = 7902 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7903 7904 if (getLangOpts().CPlusPlus) { 7905 if (LCanPointeeTy == RCanPointeeTy) 7906 return ResultTy; 7907 if (!IsRelational && 7908 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7909 // Valid unless comparison between non-null pointer and function pointer 7910 // This is a gcc extension compatibility comparison. 7911 // In a SFINAE context, we treat this as a hard error to maintain 7912 // conformance with the C++ standard. 7913 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7914 && !LHSIsNull && !RHSIsNull) { 7915 diagnoseFunctionPointerToVoidComparison( 7916 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7917 7918 if (isSFINAEContext()) 7919 return QualType(); 7920 7921 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7922 return ResultTy; 7923 } 7924 } 7925 7926 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7927 return QualType(); 7928 else 7929 return ResultTy; 7930 } 7931 // C99 6.5.9p2 and C99 6.5.8p2 7932 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7933 RCanPointeeTy.getUnqualifiedType())) { 7934 // Valid unless a relational comparison of function pointers 7935 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7936 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7937 << LHSType << RHSType << LHS.get()->getSourceRange() 7938 << RHS.get()->getSourceRange(); 7939 } 7940 } else if (!IsRelational && 7941 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7942 // Valid unless comparison between non-null pointer and function pointer 7943 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7944 && !LHSIsNull && !RHSIsNull) 7945 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7946 /*isError*/false); 7947 } else { 7948 // Invalid 7949 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7950 } 7951 if (LCanPointeeTy != RCanPointeeTy) { 7952 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 7953 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 7954 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 7955 : CK_BitCast; 7956 if (LHSIsNull && !RHSIsNull) 7957 LHS = ImpCastExprToType(LHS.take(), RHSType, Kind); 7958 else 7959 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind); 7960 } 7961 return ResultTy; 7962 } 7963 7964 if (getLangOpts().CPlusPlus) { 7965 // Comparison of nullptr_t with itself. 7966 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7967 return ResultTy; 7968 7969 // Comparison of pointers with null pointer constants and equality 7970 // comparisons of member pointers to null pointer constants. 7971 if (RHSIsNull && 7972 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7973 (!IsRelational && 7974 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7975 RHS = ImpCastExprToType(RHS.take(), LHSType, 7976 LHSType->isMemberPointerType() 7977 ? CK_NullToMemberPointer 7978 : CK_NullToPointer); 7979 return ResultTy; 7980 } 7981 if (LHSIsNull && 7982 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7983 (!IsRelational && 7984 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7985 LHS = ImpCastExprToType(LHS.take(), RHSType, 7986 RHSType->isMemberPointerType() 7987 ? CK_NullToMemberPointer 7988 : CK_NullToPointer); 7989 return ResultTy; 7990 } 7991 7992 // Comparison of member pointers. 7993 if (!IsRelational && 7994 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7995 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7996 return QualType(); 7997 else 7998 return ResultTy; 7999 } 8000 8001 // Handle scoped enumeration types specifically, since they don't promote 8002 // to integers. 8003 if (LHS.get()->getType()->isEnumeralType() && 8004 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8005 RHS.get()->getType())) 8006 return ResultTy; 8007 } 8008 8009 // Handle block pointer types. 8010 if (!IsRelational && LHSType->isBlockPointerType() && 8011 RHSType->isBlockPointerType()) { 8012 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8013 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8014 8015 if (!LHSIsNull && !RHSIsNull && 8016 !Context.typesAreCompatible(lpointee, rpointee)) { 8017 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8018 << LHSType << RHSType << LHS.get()->getSourceRange() 8019 << RHS.get()->getSourceRange(); 8020 } 8021 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 8022 return ResultTy; 8023 } 8024 8025 // Allow block pointers to be compared with null pointer constants. 8026 if (!IsRelational 8027 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8028 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8029 if (!LHSIsNull && !RHSIsNull) { 8030 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8031 ->getPointeeType()->isVoidType()) 8032 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8033 ->getPointeeType()->isVoidType()))) 8034 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8035 << LHSType << RHSType << LHS.get()->getSourceRange() 8036 << RHS.get()->getSourceRange(); 8037 } 8038 if (LHSIsNull && !RHSIsNull) 8039 LHS = ImpCastExprToType(LHS.take(), RHSType, 8040 RHSType->isPointerType() ? CK_BitCast 8041 : CK_AnyPointerToBlockPointerCast); 8042 else 8043 RHS = ImpCastExprToType(RHS.take(), LHSType, 8044 LHSType->isPointerType() ? CK_BitCast 8045 : CK_AnyPointerToBlockPointerCast); 8046 return ResultTy; 8047 } 8048 8049 if (LHSType->isObjCObjectPointerType() || 8050 RHSType->isObjCObjectPointerType()) { 8051 const PointerType *LPT = LHSType->getAs<PointerType>(); 8052 const PointerType *RPT = RHSType->getAs<PointerType>(); 8053 if (LPT || RPT) { 8054 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8055 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8056 8057 if (!LPtrToVoid && !RPtrToVoid && 8058 !Context.typesAreCompatible(LHSType, RHSType)) { 8059 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8060 /*isError*/false); 8061 } 8062 if (LHSIsNull && !RHSIsNull) { 8063 Expr *E = LHS.take(); 8064 if (getLangOpts().ObjCAutoRefCount) 8065 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8066 LHS = ImpCastExprToType(E, RHSType, 8067 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8068 } 8069 else { 8070 Expr *E = RHS.take(); 8071 if (getLangOpts().ObjCAutoRefCount) 8072 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion); 8073 RHS = ImpCastExprToType(E, LHSType, 8074 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8075 } 8076 return ResultTy; 8077 } 8078 if (LHSType->isObjCObjectPointerType() && 8079 RHSType->isObjCObjectPointerType()) { 8080 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8081 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8082 /*isError*/false); 8083 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8084 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8085 8086 if (LHSIsNull && !RHSIsNull) 8087 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 8088 else 8089 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 8090 return ResultTy; 8091 } 8092 } 8093 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8094 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8095 unsigned DiagID = 0; 8096 bool isError = false; 8097 if (LangOpts.DebuggerSupport) { 8098 // Under a debugger, allow the comparison of pointers to integers, 8099 // since users tend to want to compare addresses. 8100 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8101 (RHSIsNull && RHSType->isIntegerType())) { 8102 if (IsRelational && !getLangOpts().CPlusPlus) 8103 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8104 } else if (IsRelational && !getLangOpts().CPlusPlus) 8105 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8106 else if (getLangOpts().CPlusPlus) { 8107 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8108 isError = true; 8109 } else 8110 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8111 8112 if (DiagID) { 8113 Diag(Loc, DiagID) 8114 << LHSType << RHSType << LHS.get()->getSourceRange() 8115 << RHS.get()->getSourceRange(); 8116 if (isError) 8117 return QualType(); 8118 } 8119 8120 if (LHSType->isIntegerType()) 8121 LHS = ImpCastExprToType(LHS.take(), RHSType, 8122 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8123 else 8124 RHS = ImpCastExprToType(RHS.take(), LHSType, 8125 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8126 return ResultTy; 8127 } 8128 8129 // Handle block pointers. 8130 if (!IsRelational && RHSIsNull 8131 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8132 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 8133 return ResultTy; 8134 } 8135 if (!IsRelational && LHSIsNull 8136 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8137 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 8138 return ResultTy; 8139 } 8140 8141 return InvalidOperands(Loc, LHS, RHS); 8142 } 8143 8144 8145 // Return a signed type that is of identical size and number of elements. 8146 // For floating point vectors, return an integer type of identical size 8147 // and number of elements. 8148 QualType Sema::GetSignedVectorType(QualType V) { 8149 const VectorType *VTy = V->getAs<VectorType>(); 8150 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8151 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8152 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8153 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8154 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8155 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8156 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8157 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8158 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8159 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8160 "Unhandled vector element size in vector compare"); 8161 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8162 } 8163 8164 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 8165 /// operates on extended vector types. Instead of producing an IntTy result, 8166 /// like a scalar comparison, a vector comparison produces a vector of integer 8167 /// types. 8168 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8169 SourceLocation Loc, 8170 bool IsRelational) { 8171 // Check to make sure we're operating on vectors of the same type and width, 8172 // Allowing one side to be a scalar of element type. 8173 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8174 if (vType.isNull()) 8175 return vType; 8176 8177 QualType LHSType = LHS.get()->getType(); 8178 8179 // If AltiVec, the comparison results in a numeric type, i.e. 8180 // bool for C++, int for C 8181 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8182 return Context.getLogicalOperationType(); 8183 8184 // For non-floating point types, check for self-comparisons of the form 8185 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8186 // often indicate logic errors in the program. 8187 if (!LHSType->hasFloatingRepresentation() && 8188 ActiveTemplateInstantiations.empty()) { 8189 if (DeclRefExpr* DRL 8190 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8191 if (DeclRefExpr* DRR 8192 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8193 if (DRL->getDecl() == DRR->getDecl()) 8194 DiagRuntimeBehavior(Loc, 0, 8195 PDiag(diag::warn_comparison_always) 8196 << 0 // self- 8197 << 2 // "a constant" 8198 ); 8199 } 8200 8201 // Check for comparisons of floating point operands using != and ==. 8202 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8203 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8204 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8205 } 8206 8207 // Return a signed type for the vector. 8208 return GetSignedVectorType(LHSType); 8209 } 8210 8211 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8212 SourceLocation Loc) { 8213 // Ensure that either both operands are of the same vector type, or 8214 // one operand is of a vector type and the other is of its element type. 8215 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8216 if (vType.isNull()) 8217 return InvalidOperands(Loc, LHS, RHS); 8218 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8219 vType->hasFloatingRepresentation()) 8220 return InvalidOperands(Loc, LHS, RHS); 8221 8222 return GetSignedVectorType(LHS.get()->getType()); 8223 } 8224 8225 inline QualType Sema::CheckBitwiseOperands( 8226 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8227 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8228 8229 if (LHS.get()->getType()->isVectorType() || 8230 RHS.get()->getType()->isVectorType()) { 8231 if (LHS.get()->getType()->hasIntegerRepresentation() && 8232 RHS.get()->getType()->hasIntegerRepresentation()) 8233 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8234 8235 return InvalidOperands(Loc, LHS, RHS); 8236 } 8237 8238 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 8239 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8240 IsCompAssign); 8241 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8242 return QualType(); 8243 LHS = LHSResult.take(); 8244 RHS = RHSResult.take(); 8245 8246 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8247 return compType; 8248 return InvalidOperands(Loc, LHS, RHS); 8249 } 8250 8251 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8252 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8253 8254 // Check vector operands differently. 8255 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8256 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8257 8258 // Diagnose cases where the user write a logical and/or but probably meant a 8259 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8260 // is a constant. 8261 if (LHS.get()->getType()->isIntegerType() && 8262 !LHS.get()->getType()->isBooleanType() && 8263 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8264 // Don't warn in macros or template instantiations. 8265 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8266 // If the RHS can be constant folded, and if it constant folds to something 8267 // that isn't 0 or 1 (which indicate a potential logical operation that 8268 // happened to fold to true/false) then warn. 8269 // Parens on the RHS are ignored. 8270 llvm::APSInt Result; 8271 if (RHS.get()->EvaluateAsInt(Result, Context)) 8272 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 8273 (Result != 0 && Result != 1)) { 8274 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8275 << RHS.get()->getSourceRange() 8276 << (Opc == BO_LAnd ? "&&" : "||"); 8277 // Suggest replacing the logical operator with the bitwise version 8278 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8279 << (Opc == BO_LAnd ? "&" : "|") 8280 << FixItHint::CreateReplacement(SourceRange( 8281 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8282 getLangOpts())), 8283 Opc == BO_LAnd ? "&" : "|"); 8284 if (Opc == BO_LAnd) 8285 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8286 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8287 << FixItHint::CreateRemoval( 8288 SourceRange( 8289 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8290 0, getSourceManager(), 8291 getLangOpts()), 8292 RHS.get()->getLocEnd())); 8293 } 8294 } 8295 8296 if (!Context.getLangOpts().CPlusPlus) { 8297 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8298 // not operate on the built-in scalar and vector float types. 8299 if (Context.getLangOpts().OpenCL && 8300 Context.getLangOpts().OpenCLVersion < 120) { 8301 if (LHS.get()->getType()->isFloatingType() || 8302 RHS.get()->getType()->isFloatingType()) 8303 return InvalidOperands(Loc, LHS, RHS); 8304 } 8305 8306 LHS = UsualUnaryConversions(LHS.take()); 8307 if (LHS.isInvalid()) 8308 return QualType(); 8309 8310 RHS = UsualUnaryConversions(RHS.take()); 8311 if (RHS.isInvalid()) 8312 return QualType(); 8313 8314 if (!LHS.get()->getType()->isScalarType() || 8315 !RHS.get()->getType()->isScalarType()) 8316 return InvalidOperands(Loc, LHS, RHS); 8317 8318 return Context.IntTy; 8319 } 8320 8321 // The following is safe because we only use this method for 8322 // non-overloadable operands. 8323 8324 // C++ [expr.log.and]p1 8325 // C++ [expr.log.or]p1 8326 // The operands are both contextually converted to type bool. 8327 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8328 if (LHSRes.isInvalid()) 8329 return InvalidOperands(Loc, LHS, RHS); 8330 LHS = LHSRes; 8331 8332 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8333 if (RHSRes.isInvalid()) 8334 return InvalidOperands(Loc, LHS, RHS); 8335 RHS = RHSRes; 8336 8337 // C++ [expr.log.and]p2 8338 // C++ [expr.log.or]p2 8339 // The result is a bool. 8340 return Context.BoolTy; 8341 } 8342 8343 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8344 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8345 if (!ME) return false; 8346 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8347 ObjCMessageExpr *Base = 8348 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8349 if (!Base) return false; 8350 return Base->getMethodDecl() != 0; 8351 } 8352 8353 /// Is the given expression (which must be 'const') a reference to a 8354 /// variable which was originally non-const, but which has become 8355 /// 'const' due to being captured within a block? 8356 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8357 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8358 assert(E->isLValue() && E->getType().isConstQualified()); 8359 E = E->IgnoreParens(); 8360 8361 // Must be a reference to a declaration from an enclosing scope. 8362 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8363 if (!DRE) return NCCK_None; 8364 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8365 8366 // The declaration must be a variable which is not declared 'const'. 8367 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8368 if (!var) return NCCK_None; 8369 if (var->getType().isConstQualified()) return NCCK_None; 8370 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8371 8372 // Decide whether the first capture was for a block or a lambda. 8373 DeclContext *DC = S.CurContext, *Prev = 0; 8374 while (DC != var->getDeclContext()) { 8375 Prev = DC; 8376 DC = DC->getParent(); 8377 } 8378 // Unless we have an init-capture, we've gone one step too far. 8379 if (!var->isInitCapture()) 8380 DC = Prev; 8381 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8382 } 8383 8384 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8385 /// emit an error and return true. If so, return false. 8386 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8387 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8388 SourceLocation OrigLoc = Loc; 8389 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8390 &Loc); 8391 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8392 IsLV = Expr::MLV_InvalidMessageExpression; 8393 if (IsLV == Expr::MLV_Valid) 8394 return false; 8395 8396 unsigned Diag = 0; 8397 bool NeedType = false; 8398 switch (IsLV) { // C99 6.5.16p2 8399 case Expr::MLV_ConstQualified: 8400 Diag = diag::err_typecheck_assign_const; 8401 8402 // Use a specialized diagnostic when we're assigning to an object 8403 // from an enclosing function or block. 8404 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8405 if (NCCK == NCCK_Block) 8406 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8407 else 8408 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8409 break; 8410 } 8411 8412 // In ARC, use some specialized diagnostics for occasions where we 8413 // infer 'const'. These are always pseudo-strong variables. 8414 if (S.getLangOpts().ObjCAutoRefCount) { 8415 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8416 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8417 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8418 8419 // Use the normal diagnostic if it's pseudo-__strong but the 8420 // user actually wrote 'const'. 8421 if (var->isARCPseudoStrong() && 8422 (!var->getTypeSourceInfo() || 8423 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8424 // There are two pseudo-strong cases: 8425 // - self 8426 ObjCMethodDecl *method = S.getCurMethodDecl(); 8427 if (method && var == method->getSelfDecl()) 8428 Diag = method->isClassMethod() 8429 ? diag::err_typecheck_arc_assign_self_class_method 8430 : diag::err_typecheck_arc_assign_self; 8431 8432 // - fast enumeration variables 8433 else 8434 Diag = diag::err_typecheck_arr_assign_enumeration; 8435 8436 SourceRange Assign; 8437 if (Loc != OrigLoc) 8438 Assign = SourceRange(OrigLoc, OrigLoc); 8439 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8440 // We need to preserve the AST regardless, so migration tool 8441 // can do its job. 8442 return false; 8443 } 8444 } 8445 } 8446 8447 break; 8448 case Expr::MLV_ArrayType: 8449 case Expr::MLV_ArrayTemporary: 8450 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8451 NeedType = true; 8452 break; 8453 case Expr::MLV_NotObjectType: 8454 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8455 NeedType = true; 8456 break; 8457 case Expr::MLV_LValueCast: 8458 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8459 break; 8460 case Expr::MLV_Valid: 8461 llvm_unreachable("did not take early return for MLV_Valid"); 8462 case Expr::MLV_InvalidExpression: 8463 case Expr::MLV_MemberFunction: 8464 case Expr::MLV_ClassTemporary: 8465 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8466 break; 8467 case Expr::MLV_IncompleteType: 8468 case Expr::MLV_IncompleteVoidType: 8469 return S.RequireCompleteType(Loc, E->getType(), 8470 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8471 case Expr::MLV_DuplicateVectorComponents: 8472 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8473 break; 8474 case Expr::MLV_NoSetterProperty: 8475 llvm_unreachable("readonly properties should be processed differently"); 8476 case Expr::MLV_InvalidMessageExpression: 8477 Diag = diag::error_readonly_message_assignment; 8478 break; 8479 case Expr::MLV_SubObjCPropertySetting: 8480 Diag = diag::error_no_subobject_property_setting; 8481 break; 8482 } 8483 8484 SourceRange Assign; 8485 if (Loc != OrigLoc) 8486 Assign = SourceRange(OrigLoc, OrigLoc); 8487 if (NeedType) 8488 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8489 else 8490 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8491 return true; 8492 } 8493 8494 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8495 SourceLocation Loc, 8496 Sema &Sema) { 8497 // C / C++ fields 8498 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8499 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8500 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8501 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8502 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8503 } 8504 8505 // Objective-C instance variables 8506 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8507 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8508 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8509 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8510 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8511 if (RL && RR && RL->getDecl() == RR->getDecl()) 8512 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8513 } 8514 } 8515 8516 // C99 6.5.16.1 8517 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8518 SourceLocation Loc, 8519 QualType CompoundType) { 8520 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8521 8522 // Verify that LHS is a modifiable lvalue, and emit error if not. 8523 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8524 return QualType(); 8525 8526 QualType LHSType = LHSExpr->getType(); 8527 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8528 CompoundType; 8529 AssignConvertType ConvTy; 8530 if (CompoundType.isNull()) { 8531 Expr *RHSCheck = RHS.get(); 8532 8533 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8534 8535 QualType LHSTy(LHSType); 8536 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8537 if (RHS.isInvalid()) 8538 return QualType(); 8539 // Special case of NSObject attributes on c-style pointer types. 8540 if (ConvTy == IncompatiblePointer && 8541 ((Context.isObjCNSObjectType(LHSType) && 8542 RHSType->isObjCObjectPointerType()) || 8543 (Context.isObjCNSObjectType(RHSType) && 8544 LHSType->isObjCObjectPointerType()))) 8545 ConvTy = Compatible; 8546 8547 if (ConvTy == Compatible && 8548 LHSType->isObjCObjectType()) 8549 Diag(Loc, diag::err_objc_object_assignment) 8550 << LHSType; 8551 8552 // If the RHS is a unary plus or minus, check to see if they = and + are 8553 // right next to each other. If so, the user may have typo'd "x =+ 4" 8554 // instead of "x += 4". 8555 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8556 RHSCheck = ICE->getSubExpr(); 8557 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8558 if ((UO->getOpcode() == UO_Plus || 8559 UO->getOpcode() == UO_Minus) && 8560 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8561 // Only if the two operators are exactly adjacent. 8562 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8563 // And there is a space or other character before the subexpr of the 8564 // unary +/-. We don't want to warn on "x=-1". 8565 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8566 UO->getSubExpr()->getLocStart().isFileID()) { 8567 Diag(Loc, diag::warn_not_compound_assign) 8568 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8569 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8570 } 8571 } 8572 8573 if (ConvTy == Compatible) { 8574 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8575 // Warn about retain cycles where a block captures the LHS, but 8576 // not if the LHS is a simple variable into which the block is 8577 // being stored...unless that variable can be captured by reference! 8578 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8579 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8580 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8581 checkRetainCycles(LHSExpr, RHS.get()); 8582 8583 // It is safe to assign a weak reference into a strong variable. 8584 // Although this code can still have problems: 8585 // id x = self.weakProp; 8586 // id y = self.weakProp; 8587 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8588 // paths through the function. This should be revisited if 8589 // -Wrepeated-use-of-weak is made flow-sensitive. 8590 DiagnosticsEngine::Level Level = 8591 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8592 RHS.get()->getLocStart()); 8593 if (Level != DiagnosticsEngine::Ignored) 8594 getCurFunction()->markSafeWeakUse(RHS.get()); 8595 8596 } else if (getLangOpts().ObjCAutoRefCount) { 8597 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8598 } 8599 } 8600 } else { 8601 // Compound assignment "x += y" 8602 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8603 } 8604 8605 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8606 RHS.get(), AA_Assigning)) 8607 return QualType(); 8608 8609 CheckForNullPointerDereference(*this, LHSExpr); 8610 8611 // C99 6.5.16p3: The type of an assignment expression is the type of the 8612 // left operand unless the left operand has qualified type, in which case 8613 // it is the unqualified version of the type of the left operand. 8614 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8615 // is converted to the type of the assignment expression (above). 8616 // C++ 5.17p1: the type of the assignment expression is that of its left 8617 // operand. 8618 return (getLangOpts().CPlusPlus 8619 ? LHSType : LHSType.getUnqualifiedType()); 8620 } 8621 8622 // C99 6.5.17 8623 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8624 SourceLocation Loc) { 8625 LHS = S.CheckPlaceholderExpr(LHS.take()); 8626 RHS = S.CheckPlaceholderExpr(RHS.take()); 8627 if (LHS.isInvalid() || RHS.isInvalid()) 8628 return QualType(); 8629 8630 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8631 // operands, but not unary promotions. 8632 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8633 8634 // So we treat the LHS as a ignored value, and in C++ we allow the 8635 // containing site to determine what should be done with the RHS. 8636 LHS = S.IgnoredValueConversions(LHS.take()); 8637 if (LHS.isInvalid()) 8638 return QualType(); 8639 8640 S.DiagnoseUnusedExprResult(LHS.get()); 8641 8642 if (!S.getLangOpts().CPlusPlus) { 8643 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8644 if (RHS.isInvalid()) 8645 return QualType(); 8646 if (!RHS.get()->getType()->isVoidType()) 8647 S.RequireCompleteType(Loc, RHS.get()->getType(), 8648 diag::err_incomplete_type); 8649 } 8650 8651 return RHS.get()->getType(); 8652 } 8653 8654 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8655 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8656 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8657 ExprValueKind &VK, 8658 SourceLocation OpLoc, 8659 bool IsInc, bool IsPrefix) { 8660 if (Op->isTypeDependent()) 8661 return S.Context.DependentTy; 8662 8663 QualType ResType = Op->getType(); 8664 // Atomic types can be used for increment / decrement where the non-atomic 8665 // versions can, so ignore the _Atomic() specifier for the purpose of 8666 // checking. 8667 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8668 ResType = ResAtomicType->getValueType(); 8669 8670 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8671 8672 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8673 // Decrement of bool is not allowed. 8674 if (!IsInc) { 8675 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8676 return QualType(); 8677 } 8678 // Increment of bool sets it to true, but is deprecated. 8679 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8680 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8681 // Error on enum increments and decrements in C++ mode 8682 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8683 return QualType(); 8684 } else if (ResType->isRealType()) { 8685 // OK! 8686 } else if (ResType->isPointerType()) { 8687 // C99 6.5.2.4p2, 6.5.6p2 8688 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8689 return QualType(); 8690 } else if (ResType->isObjCObjectPointerType()) { 8691 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8692 // Otherwise, we just need a complete type. 8693 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8694 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8695 return QualType(); 8696 } else if (ResType->isAnyComplexType()) { 8697 // C99 does not support ++/-- on complex types, we allow as an extension. 8698 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8699 << ResType << Op->getSourceRange(); 8700 } else if (ResType->isPlaceholderType()) { 8701 ExprResult PR = S.CheckPlaceholderExpr(Op); 8702 if (PR.isInvalid()) return QualType(); 8703 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8704 IsInc, IsPrefix); 8705 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8706 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8707 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8708 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8709 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8710 } else { 8711 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8712 << ResType << int(IsInc) << Op->getSourceRange(); 8713 return QualType(); 8714 } 8715 // At this point, we know we have a real, complex or pointer type. 8716 // Now make sure the operand is a modifiable lvalue. 8717 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8718 return QualType(); 8719 // In C++, a prefix increment is the same type as the operand. Otherwise 8720 // (in C or with postfix), the increment is the unqualified type of the 8721 // operand. 8722 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8723 VK = VK_LValue; 8724 return ResType; 8725 } else { 8726 VK = VK_RValue; 8727 return ResType.getUnqualifiedType(); 8728 } 8729 } 8730 8731 8732 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8733 /// This routine allows us to typecheck complex/recursive expressions 8734 /// where the declaration is needed for type checking. We only need to 8735 /// handle cases when the expression references a function designator 8736 /// or is an lvalue. Here are some examples: 8737 /// - &(x) => x 8738 /// - &*****f => f for f a function designator. 8739 /// - &s.xx => s 8740 /// - &s.zz[1].yy -> s, if zz is an array 8741 /// - *(x + 1) -> x, if x is an array 8742 /// - &"123"[2] -> 0 8743 /// - & __real__ x -> x 8744 static ValueDecl *getPrimaryDecl(Expr *E) { 8745 switch (E->getStmtClass()) { 8746 case Stmt::DeclRefExprClass: 8747 return cast<DeclRefExpr>(E)->getDecl(); 8748 case Stmt::MemberExprClass: 8749 // If this is an arrow operator, the address is an offset from 8750 // the base's value, so the object the base refers to is 8751 // irrelevant. 8752 if (cast<MemberExpr>(E)->isArrow()) 8753 return 0; 8754 // Otherwise, the expression refers to a part of the base 8755 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8756 case Stmt::ArraySubscriptExprClass: { 8757 // FIXME: This code shouldn't be necessary! We should catch the implicit 8758 // promotion of register arrays earlier. 8759 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8760 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8761 if (ICE->getSubExpr()->getType()->isArrayType()) 8762 return getPrimaryDecl(ICE->getSubExpr()); 8763 } 8764 return 0; 8765 } 8766 case Stmt::UnaryOperatorClass: { 8767 UnaryOperator *UO = cast<UnaryOperator>(E); 8768 8769 switch(UO->getOpcode()) { 8770 case UO_Real: 8771 case UO_Imag: 8772 case UO_Extension: 8773 return getPrimaryDecl(UO->getSubExpr()); 8774 default: 8775 return 0; 8776 } 8777 } 8778 case Stmt::ParenExprClass: 8779 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8780 case Stmt::ImplicitCastExprClass: 8781 // If the result of an implicit cast is an l-value, we care about 8782 // the sub-expression; otherwise, the result here doesn't matter. 8783 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8784 default: 8785 return 0; 8786 } 8787 } 8788 8789 namespace { 8790 enum { 8791 AO_Bit_Field = 0, 8792 AO_Vector_Element = 1, 8793 AO_Property_Expansion = 2, 8794 AO_Register_Variable = 3, 8795 AO_No_Error = 4 8796 }; 8797 } 8798 /// \brief Diagnose invalid operand for address of operations. 8799 /// 8800 /// \param Type The type of operand which cannot have its address taken. 8801 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8802 Expr *E, unsigned Type) { 8803 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8804 } 8805 8806 /// CheckAddressOfOperand - The operand of & must be either a function 8807 /// designator or an lvalue designating an object. If it is an lvalue, the 8808 /// object cannot be declared with storage class register or be a bit field. 8809 /// Note: The usual conversions are *not* applied to the operand of the & 8810 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8811 /// In C++, the operand might be an overloaded function name, in which case 8812 /// we allow the '&' but retain the overloaded-function type. 8813 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8814 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8815 if (PTy->getKind() == BuiltinType::Overload) { 8816 Expr *E = OrigOp.get()->IgnoreParens(); 8817 if (!isa<OverloadExpr>(E)) { 8818 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8819 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8820 << OrigOp.get()->getSourceRange(); 8821 return QualType(); 8822 } 8823 8824 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8825 if (isa<UnresolvedMemberExpr>(Ovl)) 8826 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8827 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8828 << OrigOp.get()->getSourceRange(); 8829 return QualType(); 8830 } 8831 8832 return Context.OverloadTy; 8833 } 8834 8835 if (PTy->getKind() == BuiltinType::UnknownAny) 8836 return Context.UnknownAnyTy; 8837 8838 if (PTy->getKind() == BuiltinType::BoundMember) { 8839 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8840 << OrigOp.get()->getSourceRange(); 8841 return QualType(); 8842 } 8843 8844 OrigOp = CheckPlaceholderExpr(OrigOp.take()); 8845 if (OrigOp.isInvalid()) return QualType(); 8846 } 8847 8848 if (OrigOp.get()->isTypeDependent()) 8849 return Context.DependentTy; 8850 8851 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8852 8853 // Make sure to ignore parentheses in subsequent checks 8854 Expr *op = OrigOp.get()->IgnoreParens(); 8855 8856 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 8857 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 8858 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 8859 return QualType(); 8860 } 8861 8862 if (getLangOpts().C99) { 8863 // Implement C99-only parts of addressof rules. 8864 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8865 if (uOp->getOpcode() == UO_Deref) 8866 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8867 // (assuming the deref expression is valid). 8868 return uOp->getSubExpr()->getType(); 8869 } 8870 // Technically, there should be a check for array subscript 8871 // expressions here, but the result of one is always an lvalue anyway. 8872 } 8873 ValueDecl *dcl = getPrimaryDecl(op); 8874 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8875 unsigned AddressOfError = AO_No_Error; 8876 8877 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8878 bool sfinae = (bool)isSFINAEContext(); 8879 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8880 : diag::ext_typecheck_addrof_temporary) 8881 << op->getType() << op->getSourceRange(); 8882 if (sfinae) 8883 return QualType(); 8884 // Materialize the temporary as an lvalue so that we can take its address. 8885 OrigOp = op = new (Context) 8886 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8887 } else if (isa<ObjCSelectorExpr>(op)) { 8888 return Context.getPointerType(op->getType()); 8889 } else if (lval == Expr::LV_MemberFunction) { 8890 // If it's an instance method, make a member pointer. 8891 // The expression must have exactly the form &A::foo. 8892 8893 // If the underlying expression isn't a decl ref, give up. 8894 if (!isa<DeclRefExpr>(op)) { 8895 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8896 << OrigOp.get()->getSourceRange(); 8897 return QualType(); 8898 } 8899 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8900 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8901 8902 // The id-expression was parenthesized. 8903 if (OrigOp.get() != DRE) { 8904 Diag(OpLoc, diag::err_parens_pointer_member_function) 8905 << OrigOp.get()->getSourceRange(); 8906 8907 // The method was named without a qualifier. 8908 } else if (!DRE->getQualifier()) { 8909 if (MD->getParent()->getName().empty()) 8910 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8911 << op->getSourceRange(); 8912 else { 8913 SmallString<32> Str; 8914 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8915 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8916 << op->getSourceRange() 8917 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8918 } 8919 } 8920 8921 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 8922 if (isa<CXXDestructorDecl>(MD)) 8923 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 8924 8925 QualType MPTy = Context.getMemberPointerType( 8926 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8927 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8928 RequireCompleteType(OpLoc, MPTy, 0); 8929 return MPTy; 8930 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8931 // C99 6.5.3.2p1 8932 // The operand must be either an l-value or a function designator 8933 if (!op->getType()->isFunctionType()) { 8934 // Use a special diagnostic for loads from property references. 8935 if (isa<PseudoObjectExpr>(op)) { 8936 AddressOfError = AO_Property_Expansion; 8937 } else { 8938 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8939 << op->getType() << op->getSourceRange(); 8940 return QualType(); 8941 } 8942 } 8943 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8944 // The operand cannot be a bit-field 8945 AddressOfError = AO_Bit_Field; 8946 } else if (op->getObjectKind() == OK_VectorComponent) { 8947 // The operand cannot be an element of a vector 8948 AddressOfError = AO_Vector_Element; 8949 } else if (dcl) { // C99 6.5.3.2p1 8950 // We have an lvalue with a decl. Make sure the decl is not declared 8951 // with the register storage-class specifier. 8952 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8953 // in C++ it is not error to take address of a register 8954 // variable (c++03 7.1.1P3) 8955 if (vd->getStorageClass() == SC_Register && 8956 !getLangOpts().CPlusPlus) { 8957 AddressOfError = AO_Register_Variable; 8958 } 8959 } else if (isa<FunctionTemplateDecl>(dcl)) { 8960 return Context.OverloadTy; 8961 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8962 // Okay: we can take the address of a field. 8963 // Could be a pointer to member, though, if there is an explicit 8964 // scope qualifier for the class. 8965 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8966 DeclContext *Ctx = dcl->getDeclContext(); 8967 if (Ctx && Ctx->isRecord()) { 8968 if (dcl->getType()->isReferenceType()) { 8969 Diag(OpLoc, 8970 diag::err_cannot_form_pointer_to_member_of_reference_type) 8971 << dcl->getDeclName() << dcl->getType(); 8972 return QualType(); 8973 } 8974 8975 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8976 Ctx = Ctx->getParent(); 8977 8978 QualType MPTy = Context.getMemberPointerType( 8979 op->getType(), 8980 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8981 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8982 RequireCompleteType(OpLoc, MPTy, 0); 8983 return MPTy; 8984 } 8985 } 8986 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8987 llvm_unreachable("Unknown/unexpected decl type"); 8988 } 8989 8990 if (AddressOfError != AO_No_Error) { 8991 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 8992 return QualType(); 8993 } 8994 8995 if (lval == Expr::LV_IncompleteVoidType) { 8996 // Taking the address of a void variable is technically illegal, but we 8997 // allow it in cases which are otherwise valid. 8998 // Example: "extern void x; void* y = &x;". 8999 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 9000 } 9001 9002 // If the operand has type "type", the result has type "pointer to type". 9003 if (op->getType()->isObjCObjectType()) 9004 return Context.getObjCObjectPointerType(op->getType()); 9005 return Context.getPointerType(op->getType()); 9006 } 9007 9008 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 9009 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 9010 SourceLocation OpLoc) { 9011 if (Op->isTypeDependent()) 9012 return S.Context.DependentTy; 9013 9014 ExprResult ConvResult = S.UsualUnaryConversions(Op); 9015 if (ConvResult.isInvalid()) 9016 return QualType(); 9017 Op = ConvResult.take(); 9018 QualType OpTy = Op->getType(); 9019 QualType Result; 9020 9021 if (isa<CXXReinterpretCastExpr>(Op)) { 9022 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 9023 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 9024 Op->getSourceRange()); 9025 } 9026 9027 // Note that per both C89 and C99, indirection is always legal, even if OpTy 9028 // is an incomplete type or void. It would be possible to warn about 9029 // dereferencing a void pointer, but it's completely well-defined, and such a 9030 // warning is unlikely to catch any mistakes. 9031 if (const PointerType *PT = OpTy->getAs<PointerType>()) 9032 Result = PT->getPointeeType(); 9033 else if (const ObjCObjectPointerType *OPT = 9034 OpTy->getAs<ObjCObjectPointerType>()) 9035 Result = OPT->getPointeeType(); 9036 else { 9037 ExprResult PR = S.CheckPlaceholderExpr(Op); 9038 if (PR.isInvalid()) return QualType(); 9039 if (PR.take() != Op) 9040 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 9041 } 9042 9043 if (Result.isNull()) { 9044 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 9045 << OpTy << Op->getSourceRange(); 9046 return QualType(); 9047 } 9048 9049 // Dereferences are usually l-values... 9050 VK = VK_LValue; 9051 9052 // ...except that certain expressions are never l-values in C. 9053 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 9054 VK = VK_RValue; 9055 9056 return Result; 9057 } 9058 9059 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 9060 tok::TokenKind Kind) { 9061 BinaryOperatorKind Opc; 9062 switch (Kind) { 9063 default: llvm_unreachable("Unknown binop!"); 9064 case tok::periodstar: Opc = BO_PtrMemD; break; 9065 case tok::arrowstar: Opc = BO_PtrMemI; break; 9066 case tok::star: Opc = BO_Mul; break; 9067 case tok::slash: Opc = BO_Div; break; 9068 case tok::percent: Opc = BO_Rem; break; 9069 case tok::plus: Opc = BO_Add; break; 9070 case tok::minus: Opc = BO_Sub; break; 9071 case tok::lessless: Opc = BO_Shl; break; 9072 case tok::greatergreater: Opc = BO_Shr; break; 9073 case tok::lessequal: Opc = BO_LE; break; 9074 case tok::less: Opc = BO_LT; break; 9075 case tok::greaterequal: Opc = BO_GE; break; 9076 case tok::greater: Opc = BO_GT; break; 9077 case tok::exclaimequal: Opc = BO_NE; break; 9078 case tok::equalequal: Opc = BO_EQ; break; 9079 case tok::amp: Opc = BO_And; break; 9080 case tok::caret: Opc = BO_Xor; break; 9081 case tok::pipe: Opc = BO_Or; break; 9082 case tok::ampamp: Opc = BO_LAnd; break; 9083 case tok::pipepipe: Opc = BO_LOr; break; 9084 case tok::equal: Opc = BO_Assign; break; 9085 case tok::starequal: Opc = BO_MulAssign; break; 9086 case tok::slashequal: Opc = BO_DivAssign; break; 9087 case tok::percentequal: Opc = BO_RemAssign; break; 9088 case tok::plusequal: Opc = BO_AddAssign; break; 9089 case tok::minusequal: Opc = BO_SubAssign; break; 9090 case tok::lesslessequal: Opc = BO_ShlAssign; break; 9091 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 9092 case tok::ampequal: Opc = BO_AndAssign; break; 9093 case tok::caretequal: Opc = BO_XorAssign; break; 9094 case tok::pipeequal: Opc = BO_OrAssign; break; 9095 case tok::comma: Opc = BO_Comma; break; 9096 } 9097 return Opc; 9098 } 9099 9100 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 9101 tok::TokenKind Kind) { 9102 UnaryOperatorKind Opc; 9103 switch (Kind) { 9104 default: llvm_unreachable("Unknown unary op!"); 9105 case tok::plusplus: Opc = UO_PreInc; break; 9106 case tok::minusminus: Opc = UO_PreDec; break; 9107 case tok::amp: Opc = UO_AddrOf; break; 9108 case tok::star: Opc = UO_Deref; break; 9109 case tok::plus: Opc = UO_Plus; break; 9110 case tok::minus: Opc = UO_Minus; break; 9111 case tok::tilde: Opc = UO_Not; break; 9112 case tok::exclaim: Opc = UO_LNot; break; 9113 case tok::kw___real: Opc = UO_Real; break; 9114 case tok::kw___imag: Opc = UO_Imag; break; 9115 case tok::kw___extension__: Opc = UO_Extension; break; 9116 } 9117 return Opc; 9118 } 9119 9120 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 9121 /// This warning is only emitted for builtin assignment operations. It is also 9122 /// suppressed in the event of macro expansions. 9123 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 9124 SourceLocation OpLoc) { 9125 if (!S.ActiveTemplateInstantiations.empty()) 9126 return; 9127 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 9128 return; 9129 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 9130 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 9131 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 9132 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 9133 if (!LHSDeclRef || !RHSDeclRef || 9134 LHSDeclRef->getLocation().isMacroID() || 9135 RHSDeclRef->getLocation().isMacroID()) 9136 return; 9137 const ValueDecl *LHSDecl = 9138 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 9139 const ValueDecl *RHSDecl = 9140 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 9141 if (LHSDecl != RHSDecl) 9142 return; 9143 if (LHSDecl->getType().isVolatileQualified()) 9144 return; 9145 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9146 if (RefTy->getPointeeType().isVolatileQualified()) 9147 return; 9148 9149 S.Diag(OpLoc, diag::warn_self_assignment) 9150 << LHSDeclRef->getType() 9151 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9152 } 9153 9154 /// Check if a bitwise-& is performed on an Objective-C pointer. This 9155 /// is usually indicative of introspection within the Objective-C pointer. 9156 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9157 SourceLocation OpLoc) { 9158 if (!S.getLangOpts().ObjC1) 9159 return; 9160 9161 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 9162 const Expr *LHS = L.get(); 9163 const Expr *RHS = R.get(); 9164 9165 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9166 ObjCPointerExpr = LHS; 9167 OtherExpr = RHS; 9168 } 9169 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9170 ObjCPointerExpr = RHS; 9171 OtherExpr = LHS; 9172 } 9173 9174 // This warning is deliberately made very specific to reduce false 9175 // positives with logic that uses '&' for hashing. This logic mainly 9176 // looks for code trying to introspect into tagged pointers, which 9177 // code should generally never do. 9178 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9179 unsigned Diag = diag::warn_objc_pointer_masking; 9180 // Determine if we are introspecting the result of performSelectorXXX. 9181 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9182 // Special case messages to -performSelector and friends, which 9183 // can return non-pointer values boxed in a pointer value. 9184 // Some clients may wish to silence warnings in this subcase. 9185 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9186 Selector S = ME->getSelector(); 9187 StringRef SelArg0 = S.getNameForSlot(0); 9188 if (SelArg0.startswith("performSelector")) 9189 Diag = diag::warn_objc_pointer_masking_performSelector; 9190 } 9191 9192 S.Diag(OpLoc, Diag) 9193 << ObjCPointerExpr->getSourceRange(); 9194 } 9195 } 9196 9197 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 9198 /// operator @p Opc at location @c TokLoc. This routine only supports 9199 /// built-in operations; ActOnBinOp handles overloaded operators. 9200 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9201 BinaryOperatorKind Opc, 9202 Expr *LHSExpr, Expr *RHSExpr) { 9203 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 9204 // The syntax only allows initializer lists on the RHS of assignment, 9205 // so we don't need to worry about accepting invalid code for 9206 // non-assignment operators. 9207 // C++11 5.17p9: 9208 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 9209 // of x = {} is x = T(). 9210 InitializationKind Kind = 9211 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 9212 InitializedEntity Entity = 9213 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 9214 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 9215 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 9216 if (Init.isInvalid()) 9217 return Init; 9218 RHSExpr = Init.take(); 9219 } 9220 9221 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 9222 QualType ResultTy; // Result type of the binary operator. 9223 // The following two variables are used for compound assignment operators 9224 QualType CompLHSTy; // Type of LHS after promotions for computation 9225 QualType CompResultTy; // Type of computation result 9226 ExprValueKind VK = VK_RValue; 9227 ExprObjectKind OK = OK_Ordinary; 9228 9229 switch (Opc) { 9230 case BO_Assign: 9231 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9232 if (getLangOpts().CPlusPlus && 9233 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9234 VK = LHS.get()->getValueKind(); 9235 OK = LHS.get()->getObjectKind(); 9236 } 9237 if (!ResultTy.isNull()) 9238 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9239 break; 9240 case BO_PtrMemD: 9241 case BO_PtrMemI: 9242 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9243 Opc == BO_PtrMemI); 9244 break; 9245 case BO_Mul: 9246 case BO_Div: 9247 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9248 Opc == BO_Div); 9249 break; 9250 case BO_Rem: 9251 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9252 break; 9253 case BO_Add: 9254 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9255 break; 9256 case BO_Sub: 9257 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9258 break; 9259 case BO_Shl: 9260 case BO_Shr: 9261 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9262 break; 9263 case BO_LE: 9264 case BO_LT: 9265 case BO_GE: 9266 case BO_GT: 9267 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9268 break; 9269 case BO_EQ: 9270 case BO_NE: 9271 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9272 break; 9273 case BO_And: 9274 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9275 case BO_Xor: 9276 case BO_Or: 9277 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9278 break; 9279 case BO_LAnd: 9280 case BO_LOr: 9281 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9282 break; 9283 case BO_MulAssign: 9284 case BO_DivAssign: 9285 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9286 Opc == BO_DivAssign); 9287 CompLHSTy = CompResultTy; 9288 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9289 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9290 break; 9291 case BO_RemAssign: 9292 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9293 CompLHSTy = CompResultTy; 9294 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9295 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9296 break; 9297 case BO_AddAssign: 9298 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9299 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9300 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9301 break; 9302 case BO_SubAssign: 9303 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9304 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9305 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9306 break; 9307 case BO_ShlAssign: 9308 case BO_ShrAssign: 9309 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9310 CompLHSTy = CompResultTy; 9311 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9312 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9313 break; 9314 case BO_AndAssign: 9315 case BO_XorAssign: 9316 case BO_OrAssign: 9317 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9318 CompLHSTy = CompResultTy; 9319 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9320 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9321 break; 9322 case BO_Comma: 9323 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9324 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9325 VK = RHS.get()->getValueKind(); 9326 OK = RHS.get()->getObjectKind(); 9327 } 9328 break; 9329 } 9330 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9331 return ExprError(); 9332 9333 // Check for array bounds violations for both sides of the BinaryOperator 9334 CheckArrayAccess(LHS.get()); 9335 CheckArrayAccess(RHS.get()); 9336 9337 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9338 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9339 &Context.Idents.get("object_setClass"), 9340 SourceLocation(), LookupOrdinaryName); 9341 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9342 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9343 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9344 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9345 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9346 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9347 } 9348 else 9349 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9350 } 9351 else if (const ObjCIvarRefExpr *OIRE = 9352 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9353 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9354 9355 if (CompResultTy.isNull()) 9356 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 9357 ResultTy, VK, OK, OpLoc, 9358 FPFeatures.fp_contract)); 9359 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9360 OK_ObjCProperty) { 9361 VK = VK_LValue; 9362 OK = LHS.get()->getObjectKind(); 9363 } 9364 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 9365 ResultTy, VK, OK, CompLHSTy, 9366 CompResultTy, OpLoc, 9367 FPFeatures.fp_contract)); 9368 } 9369 9370 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9371 /// operators are mixed in a way that suggests that the programmer forgot that 9372 /// comparison operators have higher precedence. The most typical example of 9373 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9374 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9375 SourceLocation OpLoc, Expr *LHSExpr, 9376 Expr *RHSExpr) { 9377 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9378 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9379 9380 // Check that one of the sides is a comparison operator. 9381 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9382 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9383 if (!isLeftComp && !isRightComp) 9384 return; 9385 9386 // Bitwise operations are sometimes used as eager logical ops. 9387 // Don't diagnose this. 9388 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9389 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9390 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9391 return; 9392 9393 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9394 OpLoc) 9395 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9396 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9397 SourceRange ParensRange = isLeftComp ? 9398 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9399 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9400 9401 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9402 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9403 SuggestParentheses(Self, OpLoc, 9404 Self.PDiag(diag::note_precedence_silence) << OpStr, 9405 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9406 SuggestParentheses(Self, OpLoc, 9407 Self.PDiag(diag::note_precedence_bitwise_first) 9408 << BinaryOperator::getOpcodeStr(Opc), 9409 ParensRange); 9410 } 9411 9412 /// \brief It accepts a '&' expr that is inside a '|' one. 9413 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9414 /// in parentheses. 9415 static void 9416 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9417 BinaryOperator *Bop) { 9418 assert(Bop->getOpcode() == BO_And); 9419 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9420 << Bop->getSourceRange() << OpLoc; 9421 SuggestParentheses(Self, Bop->getOperatorLoc(), 9422 Self.PDiag(diag::note_precedence_silence) 9423 << Bop->getOpcodeStr(), 9424 Bop->getSourceRange()); 9425 } 9426 9427 /// \brief It accepts a '&&' expr that is inside a '||' one. 9428 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9429 /// in parentheses. 9430 static void 9431 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9432 BinaryOperator *Bop) { 9433 assert(Bop->getOpcode() == BO_LAnd); 9434 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9435 << Bop->getSourceRange() << OpLoc; 9436 SuggestParentheses(Self, Bop->getOperatorLoc(), 9437 Self.PDiag(diag::note_precedence_silence) 9438 << Bop->getOpcodeStr(), 9439 Bop->getSourceRange()); 9440 } 9441 9442 /// \brief Returns true if the given expression can be evaluated as a constant 9443 /// 'true'. 9444 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9445 bool Res; 9446 return !E->isValueDependent() && 9447 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9448 } 9449 9450 /// \brief Returns true if the given expression can be evaluated as a constant 9451 /// 'false'. 9452 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9453 bool Res; 9454 return !E->isValueDependent() && 9455 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9456 } 9457 9458 /// \brief Look for '&&' in the left hand of a '||' expr. 9459 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9460 Expr *LHSExpr, Expr *RHSExpr) { 9461 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9462 if (Bop->getOpcode() == BO_LAnd) { 9463 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9464 if (EvaluatesAsFalse(S, RHSExpr)) 9465 return; 9466 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9467 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9468 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9469 } else if (Bop->getOpcode() == BO_LOr) { 9470 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9471 // If it's "a || b && 1 || c" we didn't warn earlier for 9472 // "a || b && 1", but warn now. 9473 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9474 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9475 } 9476 } 9477 } 9478 } 9479 9480 /// \brief Look for '&&' in the right hand of a '||' expr. 9481 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9482 Expr *LHSExpr, Expr *RHSExpr) { 9483 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9484 if (Bop->getOpcode() == BO_LAnd) { 9485 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9486 if (EvaluatesAsFalse(S, LHSExpr)) 9487 return; 9488 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9489 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9490 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9491 } 9492 } 9493 } 9494 9495 /// \brief Look for '&' in the left or right hand of a '|' expr. 9496 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9497 Expr *OrArg) { 9498 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9499 if (Bop->getOpcode() == BO_And) 9500 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9501 } 9502 } 9503 9504 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9505 Expr *SubExpr, StringRef Shift) { 9506 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9507 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9508 StringRef Op = Bop->getOpcodeStr(); 9509 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9510 << Bop->getSourceRange() << OpLoc << Shift << Op; 9511 SuggestParentheses(S, Bop->getOperatorLoc(), 9512 S.PDiag(diag::note_precedence_silence) << Op, 9513 Bop->getSourceRange()); 9514 } 9515 } 9516 } 9517 9518 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9519 Expr *LHSExpr, Expr *RHSExpr) { 9520 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9521 if (!OCE) 9522 return; 9523 9524 FunctionDecl *FD = OCE->getDirectCallee(); 9525 if (!FD || !FD->isOverloadedOperator()) 9526 return; 9527 9528 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9529 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9530 return; 9531 9532 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9533 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9534 << (Kind == OO_LessLess); 9535 SuggestParentheses(S, OCE->getOperatorLoc(), 9536 S.PDiag(diag::note_precedence_silence) 9537 << (Kind == OO_LessLess ? "<<" : ">>"), 9538 OCE->getSourceRange()); 9539 SuggestParentheses(S, OpLoc, 9540 S.PDiag(diag::note_evaluate_comparison_first), 9541 SourceRange(OCE->getArg(1)->getLocStart(), 9542 RHSExpr->getLocEnd())); 9543 } 9544 9545 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9546 /// precedence. 9547 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9548 SourceLocation OpLoc, Expr *LHSExpr, 9549 Expr *RHSExpr){ 9550 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9551 if (BinaryOperator::isBitwiseOp(Opc)) 9552 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9553 9554 // Diagnose "arg1 & arg2 | arg3" 9555 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9556 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9557 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9558 } 9559 9560 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9561 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9562 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9563 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9564 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9565 } 9566 9567 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9568 || Opc == BO_Shr) { 9569 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9570 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9571 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9572 } 9573 9574 // Warn on overloaded shift operators and comparisons, such as: 9575 // cout << 5 == 4; 9576 if (BinaryOperator::isComparisonOp(Opc)) 9577 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9578 } 9579 9580 // Binary Operators. 'Tok' is the token for the operator. 9581 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9582 tok::TokenKind Kind, 9583 Expr *LHSExpr, Expr *RHSExpr) { 9584 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9585 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9586 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9587 9588 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9589 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9590 9591 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9592 } 9593 9594 /// Build an overloaded binary operator expression in the given scope. 9595 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9596 BinaryOperatorKind Opc, 9597 Expr *LHS, Expr *RHS) { 9598 // Find all of the overloaded operators visible from this 9599 // point. We perform both an operator-name lookup from the local 9600 // scope and an argument-dependent lookup based on the types of 9601 // the arguments. 9602 UnresolvedSet<16> Functions; 9603 OverloadedOperatorKind OverOp 9604 = BinaryOperator::getOverloadedOperator(Opc); 9605 if (Sc && OverOp != OO_None) 9606 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9607 RHS->getType(), Functions); 9608 9609 // Build the (potentially-overloaded, potentially-dependent) 9610 // binary operation. 9611 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9612 } 9613 9614 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9615 BinaryOperatorKind Opc, 9616 Expr *LHSExpr, Expr *RHSExpr) { 9617 // We want to end up calling one of checkPseudoObjectAssignment 9618 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9619 // both expressions are overloadable or either is type-dependent), 9620 // or CreateBuiltinBinOp (in any other case). We also want to get 9621 // any placeholder types out of the way. 9622 9623 // Handle pseudo-objects in the LHS. 9624 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9625 // Assignments with a pseudo-object l-value need special analysis. 9626 if (pty->getKind() == BuiltinType::PseudoObject && 9627 BinaryOperator::isAssignmentOp(Opc)) 9628 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9629 9630 // Don't resolve overloads if the other type is overloadable. 9631 if (pty->getKind() == BuiltinType::Overload) { 9632 // We can't actually test that if we still have a placeholder, 9633 // though. Fortunately, none of the exceptions we see in that 9634 // code below are valid when the LHS is an overload set. Note 9635 // that an overload set can be dependently-typed, but it never 9636 // instantiates to having an overloadable type. 9637 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9638 if (resolvedRHS.isInvalid()) return ExprError(); 9639 RHSExpr = resolvedRHS.take(); 9640 9641 if (RHSExpr->isTypeDependent() || 9642 RHSExpr->getType()->isOverloadableType()) 9643 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9644 } 9645 9646 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9647 if (LHS.isInvalid()) return ExprError(); 9648 LHSExpr = LHS.take(); 9649 } 9650 9651 // Handle pseudo-objects in the RHS. 9652 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9653 // An overload in the RHS can potentially be resolved by the type 9654 // being assigned to. 9655 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9656 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9657 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9658 9659 if (LHSExpr->getType()->isOverloadableType()) 9660 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9661 9662 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9663 } 9664 9665 // Don't resolve overloads if the other type is overloadable. 9666 if (pty->getKind() == BuiltinType::Overload && 9667 LHSExpr->getType()->isOverloadableType()) 9668 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9669 9670 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9671 if (!resolvedRHS.isUsable()) return ExprError(); 9672 RHSExpr = resolvedRHS.take(); 9673 } 9674 9675 if (getLangOpts().CPlusPlus) { 9676 // If either expression is type-dependent, always build an 9677 // overloaded op. 9678 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9679 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9680 9681 // Otherwise, build an overloaded op if either expression has an 9682 // overloadable type. 9683 if (LHSExpr->getType()->isOverloadableType() || 9684 RHSExpr->getType()->isOverloadableType()) 9685 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9686 } 9687 9688 // Build a built-in binary operation. 9689 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9690 } 9691 9692 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9693 UnaryOperatorKind Opc, 9694 Expr *InputExpr) { 9695 ExprResult Input = Owned(InputExpr); 9696 ExprValueKind VK = VK_RValue; 9697 ExprObjectKind OK = OK_Ordinary; 9698 QualType resultType; 9699 switch (Opc) { 9700 case UO_PreInc: 9701 case UO_PreDec: 9702 case UO_PostInc: 9703 case UO_PostDec: 9704 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9705 Opc == UO_PreInc || 9706 Opc == UO_PostInc, 9707 Opc == UO_PreInc || 9708 Opc == UO_PreDec); 9709 break; 9710 case UO_AddrOf: 9711 resultType = CheckAddressOfOperand(Input, OpLoc); 9712 break; 9713 case UO_Deref: { 9714 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9715 if (Input.isInvalid()) return ExprError(); 9716 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9717 break; 9718 } 9719 case UO_Plus: 9720 case UO_Minus: 9721 Input = UsualUnaryConversions(Input.take()); 9722 if (Input.isInvalid()) return ExprError(); 9723 resultType = Input.get()->getType(); 9724 if (resultType->isDependentType()) 9725 break; 9726 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9727 resultType->isVectorType()) 9728 break; 9729 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9730 Opc == UO_Plus && 9731 resultType->isPointerType()) 9732 break; 9733 9734 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9735 << resultType << Input.get()->getSourceRange()); 9736 9737 case UO_Not: // bitwise complement 9738 Input = UsualUnaryConversions(Input.take()); 9739 if (Input.isInvalid()) 9740 return ExprError(); 9741 resultType = Input.get()->getType(); 9742 if (resultType->isDependentType()) 9743 break; 9744 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9745 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9746 // C99 does not support '~' for complex conjugation. 9747 Diag(OpLoc, diag::ext_integer_complement_complex) 9748 << resultType << Input.get()->getSourceRange(); 9749 else if (resultType->hasIntegerRepresentation()) 9750 break; 9751 else if (resultType->isExtVectorType()) { 9752 if (Context.getLangOpts().OpenCL) { 9753 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9754 // on vector float types. 9755 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9756 if (!T->isIntegerType()) 9757 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9758 << resultType << Input.get()->getSourceRange()); 9759 } 9760 break; 9761 } else { 9762 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9763 << resultType << Input.get()->getSourceRange()); 9764 } 9765 break; 9766 9767 case UO_LNot: // logical negation 9768 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9769 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9770 if (Input.isInvalid()) return ExprError(); 9771 resultType = Input.get()->getType(); 9772 9773 // Though we still have to promote half FP to float... 9774 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9775 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9776 resultType = Context.FloatTy; 9777 } 9778 9779 if (resultType->isDependentType()) 9780 break; 9781 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 9782 // C99 6.5.3.3p1: ok, fallthrough; 9783 if (Context.getLangOpts().CPlusPlus) { 9784 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9785 // operand contextually converted to bool. 9786 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9787 ScalarTypeToBooleanCastKind(resultType)); 9788 } else if (Context.getLangOpts().OpenCL && 9789 Context.getLangOpts().OpenCLVersion < 120) { 9790 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9791 // operate on scalar float types. 9792 if (!resultType->isIntegerType()) 9793 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9794 << resultType << Input.get()->getSourceRange()); 9795 } 9796 } else if (resultType->isExtVectorType()) { 9797 if (Context.getLangOpts().OpenCL && 9798 Context.getLangOpts().OpenCLVersion < 120) { 9799 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9800 // operate on vector float types. 9801 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9802 if (!T->isIntegerType()) 9803 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9804 << resultType << Input.get()->getSourceRange()); 9805 } 9806 // Vector logical not returns the signed variant of the operand type. 9807 resultType = GetSignedVectorType(resultType); 9808 break; 9809 } else { 9810 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9811 << resultType << Input.get()->getSourceRange()); 9812 } 9813 9814 // LNot always has type int. C99 6.5.3.3p5. 9815 // In C++, it's bool. C++ 5.3.1p8 9816 resultType = Context.getLogicalOperationType(); 9817 break; 9818 case UO_Real: 9819 case UO_Imag: 9820 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9821 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9822 // complex l-values to ordinary l-values and all other values to r-values. 9823 if (Input.isInvalid()) return ExprError(); 9824 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9825 if (Input.get()->getValueKind() != VK_RValue && 9826 Input.get()->getObjectKind() == OK_Ordinary) 9827 VK = Input.get()->getValueKind(); 9828 } else if (!getLangOpts().CPlusPlus) { 9829 // In C, a volatile scalar is read by __imag. In C++, it is not. 9830 Input = DefaultLvalueConversion(Input.take()); 9831 } 9832 break; 9833 case UO_Extension: 9834 resultType = Input.get()->getType(); 9835 VK = Input.get()->getValueKind(); 9836 OK = Input.get()->getObjectKind(); 9837 break; 9838 } 9839 if (resultType.isNull() || Input.isInvalid()) 9840 return ExprError(); 9841 9842 // Check for array bounds violations in the operand of the UnaryOperator, 9843 // except for the '*' and '&' operators that have to be handled specially 9844 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9845 // that are explicitly defined as valid by the standard). 9846 if (Opc != UO_AddrOf && Opc != UO_Deref) 9847 CheckArrayAccess(Input.get()); 9848 9849 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9850 VK, OK, OpLoc)); 9851 } 9852 9853 /// \brief Determine whether the given expression is a qualified member 9854 /// access expression, of a form that could be turned into a pointer to member 9855 /// with the address-of operator. 9856 static bool isQualifiedMemberAccess(Expr *E) { 9857 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9858 if (!DRE->getQualifier()) 9859 return false; 9860 9861 ValueDecl *VD = DRE->getDecl(); 9862 if (!VD->isCXXClassMember()) 9863 return false; 9864 9865 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9866 return true; 9867 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9868 return Method->isInstance(); 9869 9870 return false; 9871 } 9872 9873 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9874 if (!ULE->getQualifier()) 9875 return false; 9876 9877 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9878 DEnd = ULE->decls_end(); 9879 D != DEnd; ++D) { 9880 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9881 if (Method->isInstance()) 9882 return true; 9883 } else { 9884 // Overload set does not contain methods. 9885 break; 9886 } 9887 } 9888 9889 return false; 9890 } 9891 9892 return false; 9893 } 9894 9895 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9896 UnaryOperatorKind Opc, Expr *Input) { 9897 // First things first: handle placeholders so that the 9898 // overloaded-operator check considers the right type. 9899 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9900 // Increment and decrement of pseudo-object references. 9901 if (pty->getKind() == BuiltinType::PseudoObject && 9902 UnaryOperator::isIncrementDecrementOp(Opc)) 9903 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9904 9905 // extension is always a builtin operator. 9906 if (Opc == UO_Extension) 9907 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9908 9909 // & gets special logic for several kinds of placeholder. 9910 // The builtin code knows what to do. 9911 if (Opc == UO_AddrOf && 9912 (pty->getKind() == BuiltinType::Overload || 9913 pty->getKind() == BuiltinType::UnknownAny || 9914 pty->getKind() == BuiltinType::BoundMember)) 9915 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9916 9917 // Anything else needs to be handled now. 9918 ExprResult Result = CheckPlaceholderExpr(Input); 9919 if (Result.isInvalid()) return ExprError(); 9920 Input = Result.take(); 9921 } 9922 9923 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9924 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9925 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9926 // Find all of the overloaded operators visible from this 9927 // point. We perform both an operator-name lookup from the local 9928 // scope and an argument-dependent lookup based on the types of 9929 // the arguments. 9930 UnresolvedSet<16> Functions; 9931 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9932 if (S && OverOp != OO_None) 9933 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9934 Functions); 9935 9936 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9937 } 9938 9939 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9940 } 9941 9942 // Unary Operators. 'Tok' is the token for the operator. 9943 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9944 tok::TokenKind Op, Expr *Input) { 9945 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9946 } 9947 9948 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9949 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9950 LabelDecl *TheDecl) { 9951 TheDecl->markUsed(Context); 9952 // Create the AST node. The address of a label always has type 'void*'. 9953 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9954 Context.getPointerType(Context.VoidTy))); 9955 } 9956 9957 /// Given the last statement in a statement-expression, check whether 9958 /// the result is a producing expression (like a call to an 9959 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9960 /// release out of the full-expression. Otherwise, return null. 9961 /// Cannot fail. 9962 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9963 // Should always be wrapped with one of these. 9964 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9965 if (!cleanups) return 0; 9966 9967 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9968 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9969 return 0; 9970 9971 // Splice out the cast. This shouldn't modify any interesting 9972 // features of the statement. 9973 Expr *producer = cast->getSubExpr(); 9974 assert(producer->getType() == cast->getType()); 9975 assert(producer->getValueKind() == cast->getValueKind()); 9976 cleanups->setSubExpr(producer); 9977 return cleanups; 9978 } 9979 9980 void Sema::ActOnStartStmtExpr() { 9981 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9982 } 9983 9984 void Sema::ActOnStmtExprError() { 9985 // Note that function is also called by TreeTransform when leaving a 9986 // StmtExpr scope without rebuilding anything. 9987 9988 DiscardCleanupsInEvaluationContext(); 9989 PopExpressionEvaluationContext(); 9990 } 9991 9992 ExprResult 9993 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9994 SourceLocation RPLoc) { // "({..})" 9995 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9996 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9997 9998 if (hasAnyUnrecoverableErrorsInThisFunction()) 9999 DiscardCleanupsInEvaluationContext(); 10000 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 10001 PopExpressionEvaluationContext(); 10002 10003 bool isFileScope 10004 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 10005 if (isFileScope) 10006 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 10007 10008 // FIXME: there are a variety of strange constraints to enforce here, for 10009 // example, it is not possible to goto into a stmt expression apparently. 10010 // More semantic analysis is needed. 10011 10012 // If there are sub-stmts in the compound stmt, take the type of the last one 10013 // as the type of the stmtexpr. 10014 QualType Ty = Context.VoidTy; 10015 bool StmtExprMayBindToTemp = false; 10016 if (!Compound->body_empty()) { 10017 Stmt *LastStmt = Compound->body_back(); 10018 LabelStmt *LastLabelStmt = 0; 10019 // If LastStmt is a label, skip down through into the body. 10020 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 10021 LastLabelStmt = Label; 10022 LastStmt = Label->getSubStmt(); 10023 } 10024 10025 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 10026 // Do function/array conversion on the last expression, but not 10027 // lvalue-to-rvalue. However, initialize an unqualified type. 10028 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 10029 if (LastExpr.isInvalid()) 10030 return ExprError(); 10031 Ty = LastExpr.get()->getType().getUnqualifiedType(); 10032 10033 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 10034 // In ARC, if the final expression ends in a consume, splice 10035 // the consume out and bind it later. In the alternate case 10036 // (when dealing with a retainable type), the result 10037 // initialization will create a produce. In both cases the 10038 // result will be +1, and we'll need to balance that out with 10039 // a bind. 10040 if (Expr *rebuiltLastStmt 10041 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 10042 LastExpr = rebuiltLastStmt; 10043 } else { 10044 LastExpr = PerformCopyInitialization( 10045 InitializedEntity::InitializeResult(LPLoc, 10046 Ty, 10047 false), 10048 SourceLocation(), 10049 LastExpr); 10050 } 10051 10052 if (LastExpr.isInvalid()) 10053 return ExprError(); 10054 if (LastExpr.get() != 0) { 10055 if (!LastLabelStmt) 10056 Compound->setLastStmt(LastExpr.take()); 10057 else 10058 LastLabelStmt->setSubStmt(LastExpr.take()); 10059 StmtExprMayBindToTemp = true; 10060 } 10061 } 10062 } 10063 } 10064 10065 // FIXME: Check that expression type is complete/non-abstract; statement 10066 // expressions are not lvalues. 10067 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 10068 if (StmtExprMayBindToTemp) 10069 return MaybeBindToTemporary(ResStmtExpr); 10070 return Owned(ResStmtExpr); 10071 } 10072 10073 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 10074 TypeSourceInfo *TInfo, 10075 OffsetOfComponent *CompPtr, 10076 unsigned NumComponents, 10077 SourceLocation RParenLoc) { 10078 QualType ArgTy = TInfo->getType(); 10079 bool Dependent = ArgTy->isDependentType(); 10080 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 10081 10082 // We must have at least one component that refers to the type, and the first 10083 // one is known to be a field designator. Verify that the ArgTy represents 10084 // a struct/union/class. 10085 if (!Dependent && !ArgTy->isRecordType()) 10086 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 10087 << ArgTy << TypeRange); 10088 10089 // Type must be complete per C99 7.17p3 because a declaring a variable 10090 // with an incomplete type would be ill-formed. 10091 if (!Dependent 10092 && RequireCompleteType(BuiltinLoc, ArgTy, 10093 diag::err_offsetof_incomplete_type, TypeRange)) 10094 return ExprError(); 10095 10096 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 10097 // GCC extension, diagnose them. 10098 // FIXME: This diagnostic isn't actually visible because the location is in 10099 // a system header! 10100 if (NumComponents != 1) 10101 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 10102 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 10103 10104 bool DidWarnAboutNonPOD = false; 10105 QualType CurrentType = ArgTy; 10106 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 10107 SmallVector<OffsetOfNode, 4> Comps; 10108 SmallVector<Expr*, 4> Exprs; 10109 for (unsigned i = 0; i != NumComponents; ++i) { 10110 const OffsetOfComponent &OC = CompPtr[i]; 10111 if (OC.isBrackets) { 10112 // Offset of an array sub-field. TODO: Should we allow vector elements? 10113 if (!CurrentType->isDependentType()) { 10114 const ArrayType *AT = Context.getAsArrayType(CurrentType); 10115 if(!AT) 10116 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 10117 << CurrentType); 10118 CurrentType = AT->getElementType(); 10119 } else 10120 CurrentType = Context.DependentTy; 10121 10122 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 10123 if (IdxRval.isInvalid()) 10124 return ExprError(); 10125 Expr *Idx = IdxRval.take(); 10126 10127 // The expression must be an integral expression. 10128 // FIXME: An integral constant expression? 10129 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 10130 !Idx->getType()->isIntegerType()) 10131 return ExprError(Diag(Idx->getLocStart(), 10132 diag::err_typecheck_subscript_not_integer) 10133 << Idx->getSourceRange()); 10134 10135 // Record this array index. 10136 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 10137 Exprs.push_back(Idx); 10138 continue; 10139 } 10140 10141 // Offset of a field. 10142 if (CurrentType->isDependentType()) { 10143 // We have the offset of a field, but we can't look into the dependent 10144 // type. Just record the identifier of the field. 10145 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10146 CurrentType = Context.DependentTy; 10147 continue; 10148 } 10149 10150 // We need to have a complete type to look into. 10151 if (RequireCompleteType(OC.LocStart, CurrentType, 10152 diag::err_offsetof_incomplete_type)) 10153 return ExprError(); 10154 10155 // Look for the designated field. 10156 const RecordType *RC = CurrentType->getAs<RecordType>(); 10157 if (!RC) 10158 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10159 << CurrentType); 10160 RecordDecl *RD = RC->getDecl(); 10161 10162 // C++ [lib.support.types]p5: 10163 // The macro offsetof accepts a restricted set of type arguments in this 10164 // International Standard. type shall be a POD structure or a POD union 10165 // (clause 9). 10166 // C++11 [support.types]p4: 10167 // If type is not a standard-layout class (Clause 9), the results are 10168 // undefined. 10169 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10170 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10171 unsigned DiagID = 10172 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 10173 : diag::warn_offsetof_non_pod_type; 10174 10175 if (!IsSafe && !DidWarnAboutNonPOD && 10176 DiagRuntimeBehavior(BuiltinLoc, 0, 10177 PDiag(DiagID) 10178 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10179 << CurrentType)) 10180 DidWarnAboutNonPOD = true; 10181 } 10182 10183 // Look for the field. 10184 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10185 LookupQualifiedName(R, RD); 10186 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 10187 IndirectFieldDecl *IndirectMemberDecl = 0; 10188 if (!MemberDecl) { 10189 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 10190 MemberDecl = IndirectMemberDecl->getAnonField(); 10191 } 10192 10193 if (!MemberDecl) 10194 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 10195 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 10196 OC.LocEnd)); 10197 10198 // C99 7.17p3: 10199 // (If the specified member is a bit-field, the behavior is undefined.) 10200 // 10201 // We diagnose this as an error. 10202 if (MemberDecl->isBitField()) { 10203 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 10204 << MemberDecl->getDeclName() 10205 << SourceRange(BuiltinLoc, RParenLoc); 10206 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 10207 return ExprError(); 10208 } 10209 10210 RecordDecl *Parent = MemberDecl->getParent(); 10211 if (IndirectMemberDecl) 10212 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 10213 10214 // If the member was found in a base class, introduce OffsetOfNodes for 10215 // the base class indirections. 10216 CXXBasePaths Paths; 10217 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 10218 if (Paths.getDetectedVirtual()) { 10219 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 10220 << MemberDecl->getDeclName() 10221 << SourceRange(BuiltinLoc, RParenLoc); 10222 return ExprError(); 10223 } 10224 10225 CXXBasePath &Path = Paths.front(); 10226 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10227 B != BEnd; ++B) 10228 Comps.push_back(OffsetOfNode(B->Base)); 10229 } 10230 10231 if (IndirectMemberDecl) { 10232 for (auto *FI : IndirectMemberDecl->chain()) { 10233 assert(isa<FieldDecl>(FI)); 10234 Comps.push_back(OffsetOfNode(OC.LocStart, 10235 cast<FieldDecl>(FI), OC.LocEnd)); 10236 } 10237 } else 10238 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10239 10240 CurrentType = MemberDecl->getType().getNonReferenceType(); 10241 } 10242 10243 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 10244 TInfo, Comps, Exprs, RParenLoc)); 10245 } 10246 10247 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10248 SourceLocation BuiltinLoc, 10249 SourceLocation TypeLoc, 10250 ParsedType ParsedArgTy, 10251 OffsetOfComponent *CompPtr, 10252 unsigned NumComponents, 10253 SourceLocation RParenLoc) { 10254 10255 TypeSourceInfo *ArgTInfo; 10256 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10257 if (ArgTy.isNull()) 10258 return ExprError(); 10259 10260 if (!ArgTInfo) 10261 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10262 10263 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10264 RParenLoc); 10265 } 10266 10267 10268 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10269 Expr *CondExpr, 10270 Expr *LHSExpr, Expr *RHSExpr, 10271 SourceLocation RPLoc) { 10272 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10273 10274 ExprValueKind VK = VK_RValue; 10275 ExprObjectKind OK = OK_Ordinary; 10276 QualType resType; 10277 bool ValueDependent = false; 10278 bool CondIsTrue = false; 10279 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10280 resType = Context.DependentTy; 10281 ValueDependent = true; 10282 } else { 10283 // The conditional expression is required to be a constant expression. 10284 llvm::APSInt condEval(32); 10285 ExprResult CondICE 10286 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10287 diag::err_typecheck_choose_expr_requires_constant, false); 10288 if (CondICE.isInvalid()) 10289 return ExprError(); 10290 CondExpr = CondICE.take(); 10291 CondIsTrue = condEval.getZExtValue(); 10292 10293 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10294 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10295 10296 resType = ActiveExpr->getType(); 10297 ValueDependent = ActiveExpr->isValueDependent(); 10298 VK = ActiveExpr->getValueKind(); 10299 OK = ActiveExpr->getObjectKind(); 10300 } 10301 10302 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 10303 resType, VK, OK, RPLoc, CondIsTrue, 10304 resType->isDependentType(), 10305 ValueDependent)); 10306 } 10307 10308 //===----------------------------------------------------------------------===// 10309 // Clang Extensions. 10310 //===----------------------------------------------------------------------===// 10311 10312 /// ActOnBlockStart - This callback is invoked when a block literal is started. 10313 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10314 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10315 10316 if (LangOpts.CPlusPlus) { 10317 Decl *ManglingContextDecl; 10318 if (MangleNumberingContext *MCtx = 10319 getCurrentMangleNumberContext(Block->getDeclContext(), 10320 ManglingContextDecl)) { 10321 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10322 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10323 } 10324 } 10325 10326 PushBlockScope(CurScope, Block); 10327 CurContext->addDecl(Block); 10328 if (CurScope) 10329 PushDeclContext(CurScope, Block); 10330 else 10331 CurContext = Block; 10332 10333 getCurBlock()->HasImplicitReturnType = true; 10334 10335 // Enter a new evaluation context to insulate the block from any 10336 // cleanups from the enclosing full-expression. 10337 PushExpressionEvaluationContext(PotentiallyEvaluated); 10338 } 10339 10340 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10341 Scope *CurScope) { 10342 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 10343 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10344 BlockScopeInfo *CurBlock = getCurBlock(); 10345 10346 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10347 QualType T = Sig->getType(); 10348 10349 // FIXME: We should allow unexpanded parameter packs here, but that would, 10350 // in turn, make the block expression contain unexpanded parameter packs. 10351 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10352 // Drop the parameters. 10353 FunctionProtoType::ExtProtoInfo EPI; 10354 EPI.HasTrailingReturn = false; 10355 EPI.TypeQuals |= DeclSpec::TQ_const; 10356 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10357 Sig = Context.getTrivialTypeSourceInfo(T); 10358 } 10359 10360 // GetTypeForDeclarator always produces a function type for a block 10361 // literal signature. Furthermore, it is always a FunctionProtoType 10362 // unless the function was written with a typedef. 10363 assert(T->isFunctionType() && 10364 "GetTypeForDeclarator made a non-function block signature"); 10365 10366 // Look for an explicit signature in that function type. 10367 FunctionProtoTypeLoc ExplicitSignature; 10368 10369 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10370 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10371 10372 // Check whether that explicit signature was synthesized by 10373 // GetTypeForDeclarator. If so, don't save that as part of the 10374 // written signature. 10375 if (ExplicitSignature.getLocalRangeBegin() == 10376 ExplicitSignature.getLocalRangeEnd()) { 10377 // This would be much cheaper if we stored TypeLocs instead of 10378 // TypeSourceInfos. 10379 TypeLoc Result = ExplicitSignature.getReturnLoc(); 10380 unsigned Size = Result.getFullDataSize(); 10381 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10382 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10383 10384 ExplicitSignature = FunctionProtoTypeLoc(); 10385 } 10386 } 10387 10388 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10389 CurBlock->FunctionType = T; 10390 10391 const FunctionType *Fn = T->getAs<FunctionType>(); 10392 QualType RetTy = Fn->getReturnType(); 10393 bool isVariadic = 10394 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10395 10396 CurBlock->TheDecl->setIsVariadic(isVariadic); 10397 10398 // Context.DependentTy is used as a placeholder for a missing block 10399 // return type. TODO: what should we do with declarators like: 10400 // ^ * { ... } 10401 // If the answer is "apply template argument deduction".... 10402 if (RetTy != Context.DependentTy) { 10403 CurBlock->ReturnType = RetTy; 10404 CurBlock->TheDecl->setBlockMissingReturnType(false); 10405 CurBlock->HasImplicitReturnType = false; 10406 } 10407 10408 // Push block parameters from the declarator if we had them. 10409 SmallVector<ParmVarDecl*, 8> Params; 10410 if (ExplicitSignature) { 10411 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 10412 ParmVarDecl *Param = ExplicitSignature.getParam(I); 10413 if (Param->getIdentifier() == 0 && 10414 !Param->isImplicit() && 10415 !Param->isInvalidDecl() && 10416 !getLangOpts().CPlusPlus) 10417 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10418 Params.push_back(Param); 10419 } 10420 10421 // Fake up parameter variables if we have a typedef, like 10422 // ^ fntype { ... } 10423 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10424 for (FunctionProtoType::param_type_iterator I = Fn->param_type_begin(), 10425 E = Fn->param_type_end(); 10426 I != E; ++I) { 10427 ParmVarDecl *Param = 10428 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 10429 ParamInfo.getLocStart(), 10430 *I); 10431 Params.push_back(Param); 10432 } 10433 } 10434 10435 // Set the parameters on the block decl. 10436 if (!Params.empty()) { 10437 CurBlock->TheDecl->setParams(Params); 10438 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10439 CurBlock->TheDecl->param_end(), 10440 /*CheckParameterNames=*/false); 10441 } 10442 10443 // Finally we can process decl attributes. 10444 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10445 10446 // Put the parameter variables in scope. 10447 for (auto AI : CurBlock->TheDecl->params()) { 10448 AI->setOwningFunction(CurBlock->TheDecl); 10449 10450 // If this has an identifier, add it to the scope stack. 10451 if (AI->getIdentifier()) { 10452 CheckShadow(CurBlock->TheScope, AI); 10453 10454 PushOnScopeChains(AI, CurBlock->TheScope); 10455 } 10456 } 10457 } 10458 10459 /// ActOnBlockError - If there is an error parsing a block, this callback 10460 /// is invoked to pop the information about the block from the action impl. 10461 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10462 // Leave the expression-evaluation context. 10463 DiscardCleanupsInEvaluationContext(); 10464 PopExpressionEvaluationContext(); 10465 10466 // Pop off CurBlock, handle nested blocks. 10467 PopDeclContext(); 10468 PopFunctionScopeInfo(); 10469 } 10470 10471 /// ActOnBlockStmtExpr - This is called when the body of a block statement 10472 /// literal was successfully completed. ^(int x){...} 10473 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10474 Stmt *Body, Scope *CurScope) { 10475 // If blocks are disabled, emit an error. 10476 if (!LangOpts.Blocks) 10477 Diag(CaretLoc, diag::err_blocks_disable); 10478 10479 // Leave the expression-evaluation context. 10480 if (hasAnyUnrecoverableErrorsInThisFunction()) 10481 DiscardCleanupsInEvaluationContext(); 10482 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10483 PopExpressionEvaluationContext(); 10484 10485 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10486 10487 if (BSI->HasImplicitReturnType) 10488 deduceClosureReturnType(*BSI); 10489 10490 PopDeclContext(); 10491 10492 QualType RetTy = Context.VoidTy; 10493 if (!BSI->ReturnType.isNull()) 10494 RetTy = BSI->ReturnType; 10495 10496 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 10497 QualType BlockTy; 10498 10499 // Set the captured variables on the block. 10500 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10501 SmallVector<BlockDecl::Capture, 4> Captures; 10502 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10503 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10504 if (Cap.isThisCapture()) 10505 continue; 10506 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10507 Cap.isNested(), Cap.getInitExpr()); 10508 Captures.push_back(NewCap); 10509 } 10510 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10511 BSI->CXXThisCaptureIndex != 0); 10512 10513 // If the user wrote a function type in some form, try to use that. 10514 if (!BSI->FunctionType.isNull()) { 10515 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10516 10517 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10518 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10519 10520 // Turn protoless block types into nullary block types. 10521 if (isa<FunctionNoProtoType>(FTy)) { 10522 FunctionProtoType::ExtProtoInfo EPI; 10523 EPI.ExtInfo = Ext; 10524 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10525 10526 // Otherwise, if we don't need to change anything about the function type, 10527 // preserve its sugar structure. 10528 } else if (FTy->getReturnType() == RetTy && 10529 (!NoReturn || FTy->getNoReturnAttr())) { 10530 BlockTy = BSI->FunctionType; 10531 10532 // Otherwise, make the minimal modifications to the function type. 10533 } else { 10534 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10535 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10536 EPI.TypeQuals = 0; // FIXME: silently? 10537 EPI.ExtInfo = Ext; 10538 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 10539 } 10540 10541 // If we don't have a function type, just build one from nothing. 10542 } else { 10543 FunctionProtoType::ExtProtoInfo EPI; 10544 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10545 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10546 } 10547 10548 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10549 BSI->TheDecl->param_end()); 10550 BlockTy = Context.getBlockPointerType(BlockTy); 10551 10552 // If needed, diagnose invalid gotos and switches in the block. 10553 if (getCurFunction()->NeedsScopeChecking() && 10554 !hasAnyUnrecoverableErrorsInThisFunction() && 10555 !PP.isCodeCompletionEnabled()) 10556 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10557 10558 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10559 10560 // Try to apply the named return value optimization. We have to check again 10561 // if we can do this, though, because blocks keep return statements around 10562 // to deduce an implicit return type. 10563 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10564 !BSI->TheDecl->isDependentContext()) 10565 computeNRVO(Body, getCurBlock()); 10566 10567 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10568 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10569 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10570 10571 // If the block isn't obviously global, i.e. it captures anything at 10572 // all, then we need to do a few things in the surrounding context: 10573 if (Result->getBlockDecl()->hasCaptures()) { 10574 // First, this expression has a new cleanup object. 10575 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10576 ExprNeedsCleanups = true; 10577 10578 // It also gets a branch-protected scope if any of the captured 10579 // variables needs destruction. 10580 for (BlockDecl::capture_const_iterator 10581 ci = Result->getBlockDecl()->capture_begin(), 10582 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10583 const VarDecl *var = ci->getVariable(); 10584 if (var->getType().isDestructedType() != QualType::DK_none) { 10585 getCurFunction()->setHasBranchProtectedScope(); 10586 break; 10587 } 10588 } 10589 } 10590 10591 return Owned(Result); 10592 } 10593 10594 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10595 Expr *E, ParsedType Ty, 10596 SourceLocation RPLoc) { 10597 TypeSourceInfo *TInfo; 10598 GetTypeFromParser(Ty, &TInfo); 10599 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10600 } 10601 10602 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10603 Expr *E, TypeSourceInfo *TInfo, 10604 SourceLocation RPLoc) { 10605 Expr *OrigExpr = E; 10606 10607 // Get the va_list type 10608 QualType VaListType = Context.getBuiltinVaListType(); 10609 if (VaListType->isArrayType()) { 10610 // Deal with implicit array decay; for example, on x86-64, 10611 // va_list is an array, but it's supposed to decay to 10612 // a pointer for va_arg. 10613 VaListType = Context.getArrayDecayedType(VaListType); 10614 // Make sure the input expression also decays appropriately. 10615 ExprResult Result = UsualUnaryConversions(E); 10616 if (Result.isInvalid()) 10617 return ExprError(); 10618 E = Result.take(); 10619 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10620 // If va_list is a record type and we are compiling in C++ mode, 10621 // check the argument using reference binding. 10622 InitializedEntity Entity 10623 = InitializedEntity::InitializeParameter(Context, 10624 Context.getLValueReferenceType(VaListType), false); 10625 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10626 if (Init.isInvalid()) 10627 return ExprError(); 10628 E = Init.takeAs<Expr>(); 10629 } else { 10630 // Otherwise, the va_list argument must be an l-value because 10631 // it is modified by va_arg. 10632 if (!E->isTypeDependent() && 10633 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10634 return ExprError(); 10635 } 10636 10637 if (!E->isTypeDependent() && 10638 !Context.hasSameType(VaListType, E->getType())) { 10639 return ExprError(Diag(E->getLocStart(), 10640 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10641 << OrigExpr->getType() << E->getSourceRange()); 10642 } 10643 10644 if (!TInfo->getType()->isDependentType()) { 10645 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10646 diag::err_second_parameter_to_va_arg_incomplete, 10647 TInfo->getTypeLoc())) 10648 return ExprError(); 10649 10650 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10651 TInfo->getType(), 10652 diag::err_second_parameter_to_va_arg_abstract, 10653 TInfo->getTypeLoc())) 10654 return ExprError(); 10655 10656 if (!TInfo->getType().isPODType(Context)) { 10657 Diag(TInfo->getTypeLoc().getBeginLoc(), 10658 TInfo->getType()->isObjCLifetimeType() 10659 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10660 : diag::warn_second_parameter_to_va_arg_not_pod) 10661 << TInfo->getType() 10662 << TInfo->getTypeLoc().getSourceRange(); 10663 } 10664 10665 // Check for va_arg where arguments of the given type will be promoted 10666 // (i.e. this va_arg is guaranteed to have undefined behavior). 10667 QualType PromoteType; 10668 if (TInfo->getType()->isPromotableIntegerType()) { 10669 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10670 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10671 PromoteType = QualType(); 10672 } 10673 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10674 PromoteType = Context.DoubleTy; 10675 if (!PromoteType.isNull()) 10676 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10677 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10678 << TInfo->getType() 10679 << PromoteType 10680 << TInfo->getTypeLoc().getSourceRange()); 10681 } 10682 10683 QualType T = TInfo->getType().getNonLValueExprType(Context); 10684 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10685 } 10686 10687 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10688 // The type of __null will be int or long, depending on the size of 10689 // pointers on the target. 10690 QualType Ty; 10691 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10692 if (pw == Context.getTargetInfo().getIntWidth()) 10693 Ty = Context.IntTy; 10694 else if (pw == Context.getTargetInfo().getLongWidth()) 10695 Ty = Context.LongTy; 10696 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10697 Ty = Context.LongLongTy; 10698 else { 10699 llvm_unreachable("I don't know size of pointer!"); 10700 } 10701 10702 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10703 } 10704 10705 bool 10706 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 10707 if (!getLangOpts().ObjC1) 10708 return false; 10709 10710 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10711 if (!PT) 10712 return false; 10713 10714 if (!PT->isObjCIdType()) { 10715 // Check if the destination is the 'NSString' interface. 10716 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10717 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10718 return false; 10719 } 10720 10721 // Ignore any parens, implicit casts (should only be 10722 // array-to-pointer decays), and not-so-opaque values. The last is 10723 // important for making this trigger for property assignments. 10724 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 10725 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10726 if (OV->getSourceExpr()) 10727 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10728 10729 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10730 if (!SL || !SL->isAscii()) 10731 return false; 10732 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 10733 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10734 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).take(); 10735 return true; 10736 } 10737 10738 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10739 SourceLocation Loc, 10740 QualType DstType, QualType SrcType, 10741 Expr *SrcExpr, AssignmentAction Action, 10742 bool *Complained) { 10743 if (Complained) 10744 *Complained = false; 10745 10746 // Decode the result (notice that AST's are still created for extensions). 10747 bool CheckInferredResultType = false; 10748 bool isInvalid = false; 10749 unsigned DiagKind = 0; 10750 FixItHint Hint; 10751 ConversionFixItGenerator ConvHints; 10752 bool MayHaveConvFixit = false; 10753 bool MayHaveFunctionDiff = false; 10754 10755 switch (ConvTy) { 10756 case Compatible: 10757 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10758 return false; 10759 10760 case PointerToInt: 10761 DiagKind = diag::ext_typecheck_convert_pointer_int; 10762 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10763 MayHaveConvFixit = true; 10764 break; 10765 case IntToPointer: 10766 DiagKind = diag::ext_typecheck_convert_int_pointer; 10767 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10768 MayHaveConvFixit = true; 10769 break; 10770 case IncompatiblePointer: 10771 DiagKind = 10772 (Action == AA_Passing_CFAudited ? 10773 diag::err_arc_typecheck_convert_incompatible_pointer : 10774 diag::ext_typecheck_convert_incompatible_pointer); 10775 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10776 SrcType->isObjCObjectPointerType(); 10777 if (Hint.isNull() && !CheckInferredResultType) { 10778 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10779 } 10780 else if (CheckInferredResultType) { 10781 SrcType = SrcType.getUnqualifiedType(); 10782 DstType = DstType.getUnqualifiedType(); 10783 } 10784 MayHaveConvFixit = true; 10785 break; 10786 case IncompatiblePointerSign: 10787 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10788 break; 10789 case FunctionVoidPointer: 10790 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10791 break; 10792 case IncompatiblePointerDiscardsQualifiers: { 10793 // Perform array-to-pointer decay if necessary. 10794 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10795 10796 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10797 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10798 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10799 DiagKind = diag::err_typecheck_incompatible_address_space; 10800 break; 10801 10802 10803 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10804 DiagKind = diag::err_typecheck_incompatible_ownership; 10805 break; 10806 } 10807 10808 llvm_unreachable("unknown error case for discarding qualifiers!"); 10809 // fallthrough 10810 } 10811 case CompatiblePointerDiscardsQualifiers: 10812 // If the qualifiers lost were because we were applying the 10813 // (deprecated) C++ conversion from a string literal to a char* 10814 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10815 // Ideally, this check would be performed in 10816 // checkPointerTypesForAssignment. However, that would require a 10817 // bit of refactoring (so that the second argument is an 10818 // expression, rather than a type), which should be done as part 10819 // of a larger effort to fix checkPointerTypesForAssignment for 10820 // C++ semantics. 10821 if (getLangOpts().CPlusPlus && 10822 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10823 return false; 10824 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10825 break; 10826 case IncompatibleNestedPointerQualifiers: 10827 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10828 break; 10829 case IntToBlockPointer: 10830 DiagKind = diag::err_int_to_block_pointer; 10831 break; 10832 case IncompatibleBlockPointer: 10833 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10834 break; 10835 case IncompatibleObjCQualifiedId: 10836 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10837 // it can give a more specific diagnostic. 10838 DiagKind = diag::warn_incompatible_qualified_id; 10839 break; 10840 case IncompatibleVectors: 10841 DiagKind = diag::warn_incompatible_vectors; 10842 break; 10843 case IncompatibleObjCWeakRef: 10844 DiagKind = diag::err_arc_weak_unavailable_assign; 10845 break; 10846 case Incompatible: 10847 DiagKind = diag::err_typecheck_convert_incompatible; 10848 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10849 MayHaveConvFixit = true; 10850 isInvalid = true; 10851 MayHaveFunctionDiff = true; 10852 break; 10853 } 10854 10855 QualType FirstType, SecondType; 10856 switch (Action) { 10857 case AA_Assigning: 10858 case AA_Initializing: 10859 // The destination type comes first. 10860 FirstType = DstType; 10861 SecondType = SrcType; 10862 break; 10863 10864 case AA_Returning: 10865 case AA_Passing: 10866 case AA_Passing_CFAudited: 10867 case AA_Converting: 10868 case AA_Sending: 10869 case AA_Casting: 10870 // The source type comes first. 10871 FirstType = SrcType; 10872 SecondType = DstType; 10873 break; 10874 } 10875 10876 PartialDiagnostic FDiag = PDiag(DiagKind); 10877 if (Action == AA_Passing_CFAudited) 10878 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 10879 else 10880 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10881 10882 // If we can fix the conversion, suggest the FixIts. 10883 assert(ConvHints.isNull() || Hint.isNull()); 10884 if (!ConvHints.isNull()) { 10885 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10886 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10887 FDiag << *HI; 10888 } else { 10889 FDiag << Hint; 10890 } 10891 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10892 10893 if (MayHaveFunctionDiff) 10894 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10895 10896 Diag(Loc, FDiag); 10897 10898 if (SecondType == Context.OverloadTy) 10899 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10900 FirstType); 10901 10902 if (CheckInferredResultType) 10903 EmitRelatedResultTypeNote(SrcExpr); 10904 10905 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10906 EmitRelatedResultTypeNoteForReturn(DstType); 10907 10908 if (Complained) 10909 *Complained = true; 10910 return isInvalid; 10911 } 10912 10913 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10914 llvm::APSInt *Result) { 10915 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10916 public: 10917 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10918 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10919 } 10920 } Diagnoser; 10921 10922 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10923 } 10924 10925 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10926 llvm::APSInt *Result, 10927 unsigned DiagID, 10928 bool AllowFold) { 10929 class IDDiagnoser : public VerifyICEDiagnoser { 10930 unsigned DiagID; 10931 10932 public: 10933 IDDiagnoser(unsigned DiagID) 10934 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10935 10936 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10937 S.Diag(Loc, DiagID) << SR; 10938 } 10939 } Diagnoser(DiagID); 10940 10941 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10942 } 10943 10944 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10945 SourceRange SR) { 10946 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10947 } 10948 10949 ExprResult 10950 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10951 VerifyICEDiagnoser &Diagnoser, 10952 bool AllowFold) { 10953 SourceLocation DiagLoc = E->getLocStart(); 10954 10955 if (getLangOpts().CPlusPlus11) { 10956 // C++11 [expr.const]p5: 10957 // If an expression of literal class type is used in a context where an 10958 // integral constant expression is required, then that class type shall 10959 // have a single non-explicit conversion function to an integral or 10960 // unscoped enumeration type 10961 ExprResult Converted; 10962 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10963 public: 10964 CXX11ConvertDiagnoser(bool Silent) 10965 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10966 Silent, true) {} 10967 10968 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10969 QualType T) { 10970 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10971 } 10972 10973 virtual SemaDiagnosticBuilder diagnoseIncomplete( 10974 Sema &S, SourceLocation Loc, QualType T) { 10975 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10976 } 10977 10978 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 10979 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10980 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10981 } 10982 10983 virtual SemaDiagnosticBuilder noteExplicitConv( 10984 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10985 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10986 << ConvTy->isEnumeralType() << ConvTy; 10987 } 10988 10989 virtual SemaDiagnosticBuilder diagnoseAmbiguous( 10990 Sema &S, SourceLocation Loc, QualType T) { 10991 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10992 } 10993 10994 virtual SemaDiagnosticBuilder noteAmbiguous( 10995 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10996 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10997 << ConvTy->isEnumeralType() << ConvTy; 10998 } 10999 11000 virtual SemaDiagnosticBuilder diagnoseConversion( 11001 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 11002 llvm_unreachable("conversion functions are permitted"); 11003 } 11004 } ConvertDiagnoser(Diagnoser.Suppress); 11005 11006 Converted = PerformContextualImplicitConversion(DiagLoc, E, 11007 ConvertDiagnoser); 11008 if (Converted.isInvalid()) 11009 return Converted; 11010 E = Converted.take(); 11011 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 11012 return ExprError(); 11013 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11014 // An ICE must be of integral or unscoped enumeration type. 11015 if (!Diagnoser.Suppress) 11016 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11017 return ExprError(); 11018 } 11019 11020 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 11021 // in the non-ICE case. 11022 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 11023 if (Result) 11024 *Result = E->EvaluateKnownConstInt(Context); 11025 return Owned(E); 11026 } 11027 11028 Expr::EvalResult EvalResult; 11029 SmallVector<PartialDiagnosticAt, 8> Notes; 11030 EvalResult.Diag = &Notes; 11031 11032 // Try to evaluate the expression, and produce diagnostics explaining why it's 11033 // not a constant expression as a side-effect. 11034 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 11035 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 11036 11037 // In C++11, we can rely on diagnostics being produced for any expression 11038 // which is not a constant expression. If no diagnostics were produced, then 11039 // this is a constant expression. 11040 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 11041 if (Result) 11042 *Result = EvalResult.Val.getInt(); 11043 return Owned(E); 11044 } 11045 11046 // If our only note is the usual "invalid subexpression" note, just point 11047 // the caret at its location rather than producing an essentially 11048 // redundant note. 11049 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11050 diag::note_invalid_subexpr_in_const_expr) { 11051 DiagLoc = Notes[0].first; 11052 Notes.clear(); 11053 } 11054 11055 if (!Folded || !AllowFold) { 11056 if (!Diagnoser.Suppress) { 11057 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11058 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11059 Diag(Notes[I].first, Notes[I].second); 11060 } 11061 11062 return ExprError(); 11063 } 11064 11065 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 11066 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11067 Diag(Notes[I].first, Notes[I].second); 11068 11069 if (Result) 11070 *Result = EvalResult.Val.getInt(); 11071 return Owned(E); 11072 } 11073 11074 namespace { 11075 // Handle the case where we conclude a expression which we speculatively 11076 // considered to be unevaluated is actually evaluated. 11077 class TransformToPE : public TreeTransform<TransformToPE> { 11078 typedef TreeTransform<TransformToPE> BaseTransform; 11079 11080 public: 11081 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 11082 11083 // Make sure we redo semantic analysis 11084 bool AlwaysRebuild() { return true; } 11085 11086 // Make sure we handle LabelStmts correctly. 11087 // FIXME: This does the right thing, but maybe we need a more general 11088 // fix to TreeTransform? 11089 StmtResult TransformLabelStmt(LabelStmt *S) { 11090 S->getDecl()->setStmt(0); 11091 return BaseTransform::TransformLabelStmt(S); 11092 } 11093 11094 // We need to special-case DeclRefExprs referring to FieldDecls which 11095 // are not part of a member pointer formation; normal TreeTransforming 11096 // doesn't catch this case because of the way we represent them in the AST. 11097 // FIXME: This is a bit ugly; is it really the best way to handle this 11098 // case? 11099 // 11100 // Error on DeclRefExprs referring to FieldDecls. 11101 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 11102 if (isa<FieldDecl>(E->getDecl()) && 11103 !SemaRef.isUnevaluatedContext()) 11104 return SemaRef.Diag(E->getLocation(), 11105 diag::err_invalid_non_static_member_use) 11106 << E->getDecl() << E->getSourceRange(); 11107 11108 return BaseTransform::TransformDeclRefExpr(E); 11109 } 11110 11111 // Exception: filter out member pointer formation 11112 ExprResult TransformUnaryOperator(UnaryOperator *E) { 11113 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 11114 return E; 11115 11116 return BaseTransform::TransformUnaryOperator(E); 11117 } 11118 11119 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11120 // Lambdas never need to be transformed. 11121 return E; 11122 } 11123 }; 11124 } 11125 11126 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 11127 assert(isUnevaluatedContext() && 11128 "Should only transform unevaluated expressions"); 11129 ExprEvalContexts.back().Context = 11130 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 11131 if (isUnevaluatedContext()) 11132 return E; 11133 return TransformToPE(*this).TransformExpr(E); 11134 } 11135 11136 void 11137 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11138 Decl *LambdaContextDecl, 11139 bool IsDecltype) { 11140 ExprEvalContexts.push_back( 11141 ExpressionEvaluationContextRecord(NewContext, 11142 ExprCleanupObjects.size(), 11143 ExprNeedsCleanups, 11144 LambdaContextDecl, 11145 IsDecltype)); 11146 ExprNeedsCleanups = false; 11147 if (!MaybeODRUseExprs.empty()) 11148 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11149 } 11150 11151 void 11152 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11153 ReuseLambdaContextDecl_t, 11154 bool IsDecltype) { 11155 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11156 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11157 } 11158 11159 void Sema::PopExpressionEvaluationContext() { 11160 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11161 11162 if (!Rec.Lambdas.empty()) { 11163 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11164 unsigned D; 11165 if (Rec.isUnevaluated()) { 11166 // C++11 [expr.prim.lambda]p2: 11167 // A lambda-expression shall not appear in an unevaluated operand 11168 // (Clause 5). 11169 D = diag::err_lambda_unevaluated_operand; 11170 } else { 11171 // C++1y [expr.const]p2: 11172 // A conditional-expression e is a core constant expression unless the 11173 // evaluation of e, following the rules of the abstract machine, would 11174 // evaluate [...] a lambda-expression. 11175 D = diag::err_lambda_in_constant_expression; 11176 } 11177 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 11178 Diag(Rec.Lambdas[I]->getLocStart(), D); 11179 } else { 11180 // Mark the capture expressions odr-used. This was deferred 11181 // during lambda expression creation. 11182 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 11183 LambdaExpr *Lambda = Rec.Lambdas[I]; 11184 for (LambdaExpr::capture_init_iterator 11185 C = Lambda->capture_init_begin(), 11186 CEnd = Lambda->capture_init_end(); 11187 C != CEnd; ++C) { 11188 MarkDeclarationsReferencedInExpr(*C); 11189 } 11190 } 11191 } 11192 } 11193 11194 // When are coming out of an unevaluated context, clear out any 11195 // temporaries that we may have created as part of the evaluation of 11196 // the expression in that context: they aren't relevant because they 11197 // will never be constructed. 11198 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11199 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 11200 ExprCleanupObjects.end()); 11201 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 11202 CleanupVarDeclMarking(); 11203 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 11204 // Otherwise, merge the contexts together. 11205 } else { 11206 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 11207 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 11208 Rec.SavedMaybeODRUseExprs.end()); 11209 } 11210 11211 // Pop the current expression evaluation context off the stack. 11212 ExprEvalContexts.pop_back(); 11213 } 11214 11215 void Sema::DiscardCleanupsInEvaluationContext() { 11216 ExprCleanupObjects.erase( 11217 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 11218 ExprCleanupObjects.end()); 11219 ExprNeedsCleanups = false; 11220 MaybeODRUseExprs.clear(); 11221 } 11222 11223 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 11224 if (!E->getType()->isVariablyModifiedType()) 11225 return E; 11226 return TransformToPotentiallyEvaluated(E); 11227 } 11228 11229 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11230 // Do not mark anything as "used" within a dependent context; wait for 11231 // an instantiation. 11232 if (SemaRef.CurContext->isDependentContext()) 11233 return false; 11234 11235 switch (SemaRef.ExprEvalContexts.back().Context) { 11236 case Sema::Unevaluated: 11237 case Sema::UnevaluatedAbstract: 11238 // We are in an expression that is not potentially evaluated; do nothing. 11239 // (Depending on how you read the standard, we actually do need to do 11240 // something here for null pointer constants, but the standard's 11241 // definition of a null pointer constant is completely crazy.) 11242 return false; 11243 11244 case Sema::ConstantEvaluated: 11245 case Sema::PotentiallyEvaluated: 11246 // We are in a potentially evaluated expression (or a constant-expression 11247 // in C++03); we need to do implicit template instantiation, implicitly 11248 // define class members, and mark most declarations as used. 11249 return true; 11250 11251 case Sema::PotentiallyEvaluatedIfUsed: 11252 // Referenced declarations will only be used if the construct in the 11253 // containing expression is used. 11254 return false; 11255 } 11256 llvm_unreachable("Invalid context"); 11257 } 11258 11259 /// \brief Mark a function referenced, and check whether it is odr-used 11260 /// (C++ [basic.def.odr]p2, C99 6.9p3) 11261 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 11262 assert(Func && "No function?"); 11263 11264 Func->setReferenced(); 11265 11266 // C++11 [basic.def.odr]p3: 11267 // A function whose name appears as a potentially-evaluated expression is 11268 // odr-used if it is the unique lookup result or the selected member of a 11269 // set of overloaded functions [...]. 11270 // 11271 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11272 // can just check that here. Skip the rest of this function if we've already 11273 // marked the function as used. 11274 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11275 // C++11 [temp.inst]p3: 11276 // Unless a function template specialization has been explicitly 11277 // instantiated or explicitly specialized, the function template 11278 // specialization is implicitly instantiated when the specialization is 11279 // referenced in a context that requires a function definition to exist. 11280 // 11281 // We consider constexpr function templates to be referenced in a context 11282 // that requires a definition to exist whenever they are referenced. 11283 // 11284 // FIXME: This instantiates constexpr functions too frequently. If this is 11285 // really an unevaluated context (and we're not just in the definition of a 11286 // function template or overload resolution or other cases which we 11287 // incorrectly consider to be unevaluated contexts), and we're not in a 11288 // subexpression which we actually need to evaluate (for instance, a 11289 // template argument, array bound or an expression in a braced-init-list), 11290 // we are not permitted to instantiate this constexpr function definition. 11291 // 11292 // FIXME: This also implicitly defines special members too frequently. They 11293 // are only supposed to be implicitly defined if they are odr-used, but they 11294 // are not odr-used from constant expressions in unevaluated contexts. 11295 // However, they cannot be referenced if they are deleted, and they are 11296 // deleted whenever the implicit definition of the special member would 11297 // fail. 11298 if (!Func->isConstexpr() || Func->getBody()) 11299 return; 11300 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11301 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11302 return; 11303 } 11304 11305 // Note that this declaration has been used. 11306 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11307 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 11308 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11309 if (Constructor->isDefaultConstructor()) { 11310 if (Constructor->isTrivial()) 11311 return; 11312 DefineImplicitDefaultConstructor(Loc, Constructor); 11313 } else if (Constructor->isCopyConstructor()) { 11314 DefineImplicitCopyConstructor(Loc, Constructor); 11315 } else if (Constructor->isMoveConstructor()) { 11316 DefineImplicitMoveConstructor(Loc, Constructor); 11317 } 11318 } else if (Constructor->getInheritedConstructor()) { 11319 DefineInheritingConstructor(Loc, Constructor); 11320 } 11321 11322 MarkVTableUsed(Loc, Constructor->getParent()); 11323 } else if (CXXDestructorDecl *Destructor = 11324 dyn_cast<CXXDestructorDecl>(Func)) { 11325 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 11326 if (Destructor->isDefaulted() && !Destructor->isDeleted()) 11327 DefineImplicitDestructor(Loc, Destructor); 11328 if (Destructor->isVirtual()) 11329 MarkVTableUsed(Loc, Destructor->getParent()); 11330 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11331 if (MethodDecl->isOverloadedOperator() && 11332 MethodDecl->getOverloadedOperator() == OO_Equal) { 11333 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 11334 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 11335 if (MethodDecl->isCopyAssignmentOperator()) 11336 DefineImplicitCopyAssignment(Loc, MethodDecl); 11337 else 11338 DefineImplicitMoveAssignment(Loc, MethodDecl); 11339 } 11340 } else if (isa<CXXConversionDecl>(MethodDecl) && 11341 MethodDecl->getParent()->isLambda()) { 11342 CXXConversionDecl *Conversion = 11343 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 11344 if (Conversion->isLambdaToBlockPointerConversion()) 11345 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11346 else 11347 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11348 } else if (MethodDecl->isVirtual()) 11349 MarkVTableUsed(Loc, MethodDecl->getParent()); 11350 } 11351 11352 // Recursive functions should be marked when used from another function. 11353 // FIXME: Is this really right? 11354 if (CurContext == Func) return; 11355 11356 // Resolve the exception specification for any function which is 11357 // used: CodeGen will need it. 11358 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11359 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11360 ResolveExceptionSpec(Loc, FPT); 11361 11362 // Implicit instantiation of function templates and member functions of 11363 // class templates. 11364 if (Func->isImplicitlyInstantiable()) { 11365 bool AlreadyInstantiated = false; 11366 SourceLocation PointOfInstantiation = Loc; 11367 if (FunctionTemplateSpecializationInfo *SpecInfo 11368 = Func->getTemplateSpecializationInfo()) { 11369 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11370 SpecInfo->setPointOfInstantiation(Loc); 11371 else if (SpecInfo->getTemplateSpecializationKind() 11372 == TSK_ImplicitInstantiation) { 11373 AlreadyInstantiated = true; 11374 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11375 } 11376 } else if (MemberSpecializationInfo *MSInfo 11377 = Func->getMemberSpecializationInfo()) { 11378 if (MSInfo->getPointOfInstantiation().isInvalid()) 11379 MSInfo->setPointOfInstantiation(Loc); 11380 else if (MSInfo->getTemplateSpecializationKind() 11381 == TSK_ImplicitInstantiation) { 11382 AlreadyInstantiated = true; 11383 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11384 } 11385 } 11386 11387 if (!AlreadyInstantiated || Func->isConstexpr()) { 11388 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11389 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11390 ActiveTemplateInstantiations.size()) 11391 PendingLocalImplicitInstantiations.push_back( 11392 std::make_pair(Func, PointOfInstantiation)); 11393 else if (Func->isConstexpr()) 11394 // Do not defer instantiations of constexpr functions, to avoid the 11395 // expression evaluator needing to call back into Sema if it sees a 11396 // call to such a function. 11397 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11398 else { 11399 PendingInstantiations.push_back(std::make_pair(Func, 11400 PointOfInstantiation)); 11401 // Notify the consumer that a function was implicitly instantiated. 11402 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11403 } 11404 } 11405 } else { 11406 // Walk redefinitions, as some of them may be instantiable. 11407 for (auto i : Func->redecls()) { 11408 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11409 MarkFunctionReferenced(Loc, i); 11410 } 11411 } 11412 11413 // Keep track of used but undefined functions. 11414 if (!Func->isDefined()) { 11415 if (mightHaveNonExternalLinkage(Func)) 11416 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11417 else if (Func->getMostRecentDecl()->isInlined() && 11418 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11419 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11420 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11421 } 11422 11423 // Normally the most current decl is marked used while processing the use and 11424 // any subsequent decls are marked used by decl merging. This fails with 11425 // template instantiation since marking can happen at the end of the file 11426 // and, because of the two phase lookup, this function is called with at 11427 // decl in the middle of a decl chain. We loop to maintain the invariant 11428 // that once a decl is used, all decls after it are also used. 11429 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11430 F->markUsed(Context); 11431 if (F == Func) 11432 break; 11433 } 11434 } 11435 11436 static void 11437 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11438 VarDecl *var, DeclContext *DC) { 11439 DeclContext *VarDC = var->getDeclContext(); 11440 11441 // If the parameter still belongs to the translation unit, then 11442 // we're actually just using one parameter in the declaration of 11443 // the next. 11444 if (isa<ParmVarDecl>(var) && 11445 isa<TranslationUnitDecl>(VarDC)) 11446 return; 11447 11448 // For C code, don't diagnose about capture if we're not actually in code 11449 // right now; it's impossible to write a non-constant expression outside of 11450 // function context, so we'll get other (more useful) diagnostics later. 11451 // 11452 // For C++, things get a bit more nasty... it would be nice to suppress this 11453 // diagnostic for certain cases like using a local variable in an array bound 11454 // for a member of a local class, but the correct predicate is not obvious. 11455 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11456 return; 11457 11458 if (isa<CXXMethodDecl>(VarDC) && 11459 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11460 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11461 << var->getIdentifier(); 11462 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11463 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11464 << var->getIdentifier() << fn->getDeclName(); 11465 } else if (isa<BlockDecl>(VarDC)) { 11466 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11467 << var->getIdentifier(); 11468 } else { 11469 // FIXME: Is there any other context where a local variable can be 11470 // declared? 11471 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11472 << var->getIdentifier(); 11473 } 11474 11475 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 11476 << var->getIdentifier(); 11477 11478 // FIXME: Add additional diagnostic info about class etc. which prevents 11479 // capture. 11480 } 11481 11482 11483 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11484 bool &SubCapturesAreNested, 11485 QualType &CaptureType, 11486 QualType &DeclRefType) { 11487 // Check whether we've already captured it. 11488 if (CSI->CaptureMap.count(Var)) { 11489 // If we found a capture, any subcaptures are nested. 11490 SubCapturesAreNested = true; 11491 11492 // Retrieve the capture type for this variable. 11493 CaptureType = CSI->getCapture(Var).getCaptureType(); 11494 11495 // Compute the type of an expression that refers to this variable. 11496 DeclRefType = CaptureType.getNonReferenceType(); 11497 11498 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11499 if (Cap.isCopyCapture() && 11500 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11501 DeclRefType.addConst(); 11502 return true; 11503 } 11504 return false; 11505 } 11506 11507 // Only block literals, captured statements, and lambda expressions can 11508 // capture; other scopes don't work. 11509 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11510 SourceLocation Loc, 11511 const bool Diagnose, Sema &S) { 11512 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 11513 return getLambdaAwareParentOfDeclContext(DC); 11514 else { 11515 if (Diagnose) 11516 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11517 } 11518 return 0; 11519 } 11520 11521 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11522 // certain types of variables (unnamed, variably modified types etc.) 11523 // so check for eligibility. 11524 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11525 SourceLocation Loc, 11526 const bool Diagnose, Sema &S) { 11527 11528 bool IsBlock = isa<BlockScopeInfo>(CSI); 11529 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11530 11531 // Lambdas are not allowed to capture unnamed variables 11532 // (e.g. anonymous unions). 11533 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11534 // assuming that's the intent. 11535 if (IsLambda && !Var->getDeclName()) { 11536 if (Diagnose) { 11537 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11538 S.Diag(Var->getLocation(), diag::note_declared_at); 11539 } 11540 return false; 11541 } 11542 11543 // Prohibit variably-modified types; they're difficult to deal with. 11544 if (Var->getType()->isVariablyModifiedType()) { 11545 if (Diagnose) { 11546 if (IsBlock) 11547 S.Diag(Loc, diag::err_ref_vm_type); 11548 else 11549 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11550 S.Diag(Var->getLocation(), diag::note_previous_decl) 11551 << Var->getDeclName(); 11552 } 11553 return false; 11554 } 11555 // Prohibit structs with flexible array members too. 11556 // We cannot capture what is in the tail end of the struct. 11557 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11558 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11559 if (Diagnose) { 11560 if (IsBlock) 11561 S.Diag(Loc, diag::err_ref_flexarray_type); 11562 else 11563 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11564 << Var->getDeclName(); 11565 S.Diag(Var->getLocation(), diag::note_previous_decl) 11566 << Var->getDeclName(); 11567 } 11568 return false; 11569 } 11570 } 11571 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11572 // Lambdas and captured statements are not allowed to capture __block 11573 // variables; they don't support the expected semantics. 11574 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11575 if (Diagnose) { 11576 S.Diag(Loc, diag::err_capture_block_variable) 11577 << Var->getDeclName() << !IsLambda; 11578 S.Diag(Var->getLocation(), diag::note_previous_decl) 11579 << Var->getDeclName(); 11580 } 11581 return false; 11582 } 11583 11584 return true; 11585 } 11586 11587 // Returns true if the capture by block was successful. 11588 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11589 SourceLocation Loc, 11590 const bool BuildAndDiagnose, 11591 QualType &CaptureType, 11592 QualType &DeclRefType, 11593 const bool Nested, 11594 Sema &S) { 11595 Expr *CopyExpr = 0; 11596 bool ByRef = false; 11597 11598 // Blocks are not allowed to capture arrays. 11599 if (CaptureType->isArrayType()) { 11600 if (BuildAndDiagnose) { 11601 S.Diag(Loc, diag::err_ref_array_type); 11602 S.Diag(Var->getLocation(), diag::note_previous_decl) 11603 << Var->getDeclName(); 11604 } 11605 return false; 11606 } 11607 11608 // Forbid the block-capture of autoreleasing variables. 11609 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11610 if (BuildAndDiagnose) { 11611 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11612 << /*block*/ 0; 11613 S.Diag(Var->getLocation(), diag::note_previous_decl) 11614 << Var->getDeclName(); 11615 } 11616 return false; 11617 } 11618 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11619 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11620 // Block capture by reference does not change the capture or 11621 // declaration reference types. 11622 ByRef = true; 11623 } else { 11624 // Block capture by copy introduces 'const'. 11625 CaptureType = CaptureType.getNonReferenceType().withConst(); 11626 DeclRefType = CaptureType; 11627 11628 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11629 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11630 // The capture logic needs the destructor, so make sure we mark it. 11631 // Usually this is unnecessary because most local variables have 11632 // their destructors marked at declaration time, but parameters are 11633 // an exception because it's technically only the call site that 11634 // actually requires the destructor. 11635 if (isa<ParmVarDecl>(Var)) 11636 S.FinalizeVarWithDestructor(Var, Record); 11637 11638 // Enter a new evaluation context to insulate the copy 11639 // full-expression. 11640 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11641 11642 // According to the blocks spec, the capture of a variable from 11643 // the stack requires a const copy constructor. This is not true 11644 // of the copy/move done to move a __block variable to the heap. 11645 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11646 DeclRefType.withConst(), 11647 VK_LValue, Loc); 11648 11649 ExprResult Result 11650 = S.PerformCopyInitialization( 11651 InitializedEntity::InitializeBlock(Var->getLocation(), 11652 CaptureType, false), 11653 Loc, S.Owned(DeclRef)); 11654 11655 // Build a full-expression copy expression if initialization 11656 // succeeded and used a non-trivial constructor. Recover from 11657 // errors by pretending that the copy isn't necessary. 11658 if (!Result.isInvalid() && 11659 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11660 ->isTrivial()) { 11661 Result = S.MaybeCreateExprWithCleanups(Result); 11662 CopyExpr = Result.take(); 11663 } 11664 } 11665 } 11666 } 11667 11668 // Actually capture the variable. 11669 if (BuildAndDiagnose) 11670 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11671 SourceLocation(), CaptureType, CopyExpr); 11672 11673 return true; 11674 11675 } 11676 11677 11678 /// \brief Capture the given variable in the captured region. 11679 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11680 VarDecl *Var, 11681 SourceLocation Loc, 11682 const bool BuildAndDiagnose, 11683 QualType &CaptureType, 11684 QualType &DeclRefType, 11685 const bool RefersToEnclosingLocal, 11686 Sema &S) { 11687 11688 // By default, capture variables by reference. 11689 bool ByRef = true; 11690 // Using an LValue reference type is consistent with Lambdas (see below). 11691 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11692 Expr *CopyExpr = 0; 11693 if (BuildAndDiagnose) { 11694 // The current implementation assumes that all variables are captured 11695 // by references. Since there is no capture by copy, no expression evaluation 11696 // will be needed. 11697 // 11698 RecordDecl *RD = RSI->TheRecordDecl; 11699 11700 FieldDecl *Field 11701 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType, 11702 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11703 0, false, ICIS_NoInit); 11704 Field->setImplicit(true); 11705 Field->setAccess(AS_private); 11706 RD->addDecl(Field); 11707 11708 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11709 DeclRefType, VK_LValue, Loc); 11710 Var->setReferenced(true); 11711 Var->markUsed(S.Context); 11712 } 11713 11714 // Actually capture the variable. 11715 if (BuildAndDiagnose) 11716 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11717 SourceLocation(), CaptureType, CopyExpr); 11718 11719 11720 return true; 11721 } 11722 11723 /// \brief Create a field within the lambda class for the variable 11724 /// being captured. Handle Array captures. 11725 static ExprResult addAsFieldToClosureType(Sema &S, 11726 LambdaScopeInfo *LSI, 11727 VarDecl *Var, QualType FieldType, 11728 QualType DeclRefType, 11729 SourceLocation Loc, 11730 bool RefersToEnclosingLocal) { 11731 CXXRecordDecl *Lambda = LSI->Lambda; 11732 11733 // Build the non-static data member. 11734 FieldDecl *Field 11735 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11736 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11737 0, false, ICIS_NoInit); 11738 Field->setImplicit(true); 11739 Field->setAccess(AS_private); 11740 Lambda->addDecl(Field); 11741 11742 // C++11 [expr.prim.lambda]p21: 11743 // When the lambda-expression is evaluated, the entities that 11744 // are captured by copy are used to direct-initialize each 11745 // corresponding non-static data member of the resulting closure 11746 // object. (For array members, the array elements are 11747 // direct-initialized in increasing subscript order.) These 11748 // initializations are performed in the (unspecified) order in 11749 // which the non-static data members are declared. 11750 11751 // Introduce a new evaluation context for the initialization, so 11752 // that temporaries introduced as part of the capture are retained 11753 // to be re-"exported" from the lambda expression itself. 11754 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11755 11756 // C++ [expr.prim.labda]p12: 11757 // An entity captured by a lambda-expression is odr-used (3.2) in 11758 // the scope containing the lambda-expression. 11759 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11760 DeclRefType, VK_LValue, Loc); 11761 Var->setReferenced(true); 11762 Var->markUsed(S.Context); 11763 11764 // When the field has array type, create index variables for each 11765 // dimension of the array. We use these index variables to subscript 11766 // the source array, and other clients (e.g., CodeGen) will perform 11767 // the necessary iteration with these index variables. 11768 SmallVector<VarDecl *, 4> IndexVariables; 11769 QualType BaseType = FieldType; 11770 QualType SizeType = S.Context.getSizeType(); 11771 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11772 while (const ConstantArrayType *Array 11773 = S.Context.getAsConstantArrayType(BaseType)) { 11774 // Create the iteration variable for this array index. 11775 IdentifierInfo *IterationVarName = 0; 11776 { 11777 SmallString<8> Str; 11778 llvm::raw_svector_ostream OS(Str); 11779 OS << "__i" << IndexVariables.size(); 11780 IterationVarName = &S.Context.Idents.get(OS.str()); 11781 } 11782 VarDecl *IterationVar 11783 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11784 IterationVarName, SizeType, 11785 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11786 SC_None); 11787 IndexVariables.push_back(IterationVar); 11788 LSI->ArrayIndexVars.push_back(IterationVar); 11789 11790 // Create a reference to the iteration variable. 11791 ExprResult IterationVarRef 11792 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11793 assert(!IterationVarRef.isInvalid() && 11794 "Reference to invented variable cannot fail!"); 11795 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11796 assert(!IterationVarRef.isInvalid() && 11797 "Conversion of invented variable cannot fail!"); 11798 11799 // Subscript the array with this iteration variable. 11800 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11801 Ref, Loc, IterationVarRef.take(), Loc); 11802 if (Subscript.isInvalid()) { 11803 S.CleanupVarDeclMarking(); 11804 S.DiscardCleanupsInEvaluationContext(); 11805 return ExprError(); 11806 } 11807 11808 Ref = Subscript.take(); 11809 BaseType = Array->getElementType(); 11810 } 11811 11812 // Construct the entity that we will be initializing. For an array, this 11813 // will be first element in the array, which may require several levels 11814 // of array-subscript entities. 11815 SmallVector<InitializedEntity, 4> Entities; 11816 Entities.reserve(1 + IndexVariables.size()); 11817 Entities.push_back( 11818 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(), 11819 Field->getType(), Loc)); 11820 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11821 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11822 0, 11823 Entities.back())); 11824 11825 InitializationKind InitKind 11826 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11827 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11828 ExprResult Result(true); 11829 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11830 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11831 11832 // If this initialization requires any cleanups (e.g., due to a 11833 // default argument to a copy constructor), note that for the 11834 // lambda. 11835 if (S.ExprNeedsCleanups) 11836 LSI->ExprNeedsCleanups = true; 11837 11838 // Exit the expression evaluation context used for the capture. 11839 S.CleanupVarDeclMarking(); 11840 S.DiscardCleanupsInEvaluationContext(); 11841 return Result; 11842 } 11843 11844 11845 11846 /// \brief Capture the given variable in the lambda. 11847 static bool captureInLambda(LambdaScopeInfo *LSI, 11848 VarDecl *Var, 11849 SourceLocation Loc, 11850 const bool BuildAndDiagnose, 11851 QualType &CaptureType, 11852 QualType &DeclRefType, 11853 const bool RefersToEnclosingLocal, 11854 const Sema::TryCaptureKind Kind, 11855 SourceLocation EllipsisLoc, 11856 const bool IsTopScope, 11857 Sema &S) { 11858 11859 // Determine whether we are capturing by reference or by value. 11860 bool ByRef = false; 11861 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11862 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11863 } else { 11864 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11865 } 11866 11867 // Compute the type of the field that will capture this variable. 11868 if (ByRef) { 11869 // C++11 [expr.prim.lambda]p15: 11870 // An entity is captured by reference if it is implicitly or 11871 // explicitly captured but not captured by copy. It is 11872 // unspecified whether additional unnamed non-static data 11873 // members are declared in the closure type for entities 11874 // captured by reference. 11875 // 11876 // FIXME: It is not clear whether we want to build an lvalue reference 11877 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11878 // to do the former, while EDG does the latter. Core issue 1249 will 11879 // clarify, but for now we follow GCC because it's a more permissive and 11880 // easily defensible position. 11881 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11882 } else { 11883 // C++11 [expr.prim.lambda]p14: 11884 // For each entity captured by copy, an unnamed non-static 11885 // data member is declared in the closure type. The 11886 // declaration order of these members is unspecified. The type 11887 // of such a data member is the type of the corresponding 11888 // captured entity if the entity is not a reference to an 11889 // object, or the referenced type otherwise. [Note: If the 11890 // captured entity is a reference to a function, the 11891 // corresponding data member is also a reference to a 11892 // function. - end note ] 11893 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11894 if (!RefType->getPointeeType()->isFunctionType()) 11895 CaptureType = RefType->getPointeeType(); 11896 } 11897 11898 // Forbid the lambda copy-capture of autoreleasing variables. 11899 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11900 if (BuildAndDiagnose) { 11901 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11902 S.Diag(Var->getLocation(), diag::note_previous_decl) 11903 << Var->getDeclName(); 11904 } 11905 return false; 11906 } 11907 11908 // Make sure that by-copy captures are of a complete and non-abstract type. 11909 if (BuildAndDiagnose) { 11910 if (!CaptureType->isDependentType() && 11911 S.RequireCompleteType(Loc, CaptureType, 11912 diag::err_capture_of_incomplete_type, 11913 Var->getDeclName())) 11914 return false; 11915 11916 if (S.RequireNonAbstractType(Loc, CaptureType, 11917 diag::err_capture_of_abstract_type)) 11918 return false; 11919 } 11920 } 11921 11922 // Capture this variable in the lambda. 11923 Expr *CopyExpr = 0; 11924 if (BuildAndDiagnose) { 11925 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 11926 CaptureType, DeclRefType, Loc, 11927 RefersToEnclosingLocal); 11928 if (!Result.isInvalid()) 11929 CopyExpr = Result.take(); 11930 } 11931 11932 // Compute the type of a reference to this captured variable. 11933 if (ByRef) 11934 DeclRefType = CaptureType.getNonReferenceType(); 11935 else { 11936 // C++ [expr.prim.lambda]p5: 11937 // The closure type for a lambda-expression has a public inline 11938 // function call operator [...]. This function call operator is 11939 // declared const (9.3.1) if and only if the lambda-expression’s 11940 // parameter-declaration-clause is not followed by mutable. 11941 DeclRefType = CaptureType.getNonReferenceType(); 11942 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11943 DeclRefType.addConst(); 11944 } 11945 11946 // Add the capture. 11947 if (BuildAndDiagnose) 11948 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 11949 Loc, EllipsisLoc, CaptureType, CopyExpr); 11950 11951 return true; 11952 } 11953 11954 11955 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 11956 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11957 bool BuildAndDiagnose, 11958 QualType &CaptureType, 11959 QualType &DeclRefType, 11960 const unsigned *const FunctionScopeIndexToStopAt) { 11961 bool Nested = false; 11962 11963 DeclContext *DC = CurContext; 11964 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 11965 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 11966 // We need to sync up the Declaration Context with the 11967 // FunctionScopeIndexToStopAt 11968 if (FunctionScopeIndexToStopAt) { 11969 unsigned FSIndex = FunctionScopes.size() - 1; 11970 while (FSIndex != MaxFunctionScopesIndex) { 11971 DC = getLambdaAwareParentOfDeclContext(DC); 11972 --FSIndex; 11973 } 11974 } 11975 11976 11977 // If the variable is declared in the current context (and is not an 11978 // init-capture), there is no need to capture it. 11979 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 11980 if (!Var->hasLocalStorage()) return true; 11981 11982 // Walk up the stack to determine whether we can capture the variable, 11983 // performing the "simple" checks that don't depend on type. We stop when 11984 // we've either hit the declared scope of the variable or find an existing 11985 // capture of that variable. We start from the innermost capturing-entity 11986 // (the DC) and ensure that all intervening capturing-entities 11987 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 11988 // declcontext can either capture the variable or have already captured 11989 // the variable. 11990 CaptureType = Var->getType(); 11991 DeclRefType = CaptureType.getNonReferenceType(); 11992 bool Explicit = (Kind != TryCapture_Implicit); 11993 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 11994 do { 11995 // Only block literals, captured statements, and lambda expressions can 11996 // capture; other scopes don't work. 11997 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 11998 ExprLoc, 11999 BuildAndDiagnose, 12000 *this); 12001 if (!ParentDC) return true; 12002 12003 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 12004 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 12005 12006 12007 // Check whether we've already captured it. 12008 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 12009 DeclRefType)) 12010 break; 12011 // If we are instantiating a generic lambda call operator body, 12012 // we do not want to capture new variables. What was captured 12013 // during either a lambdas transformation or initial parsing 12014 // should be used. 12015 if (isGenericLambdaCallOperatorSpecialization(DC)) { 12016 if (BuildAndDiagnose) { 12017 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12018 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 12019 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12020 Diag(Var->getLocation(), diag::note_previous_decl) 12021 << Var->getDeclName(); 12022 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 12023 } else 12024 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 12025 } 12026 return true; 12027 } 12028 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12029 // certain types of variables (unnamed, variably modified types etc.) 12030 // so check for eligibility. 12031 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 12032 return true; 12033 12034 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 12035 // No capture-default, and this is not an explicit capture 12036 // so cannot capture this variable. 12037 if (BuildAndDiagnose) { 12038 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12039 Diag(Var->getLocation(), diag::note_previous_decl) 12040 << Var->getDeclName(); 12041 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 12042 diag::note_lambda_decl); 12043 // FIXME: If we error out because an outer lambda can not implicitly 12044 // capture a variable that an inner lambda explicitly captures, we 12045 // should have the inner lambda do the explicit capture - because 12046 // it makes for cleaner diagnostics later. This would purely be done 12047 // so that the diagnostic does not misleadingly claim that a variable 12048 // can not be captured by a lambda implicitly even though it is captured 12049 // explicitly. Suggestion: 12050 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 12051 // at the function head 12052 // - cache the StartingDeclContext - this must be a lambda 12053 // - captureInLambda in the innermost lambda the variable. 12054 } 12055 return true; 12056 } 12057 12058 FunctionScopesIndex--; 12059 DC = ParentDC; 12060 Explicit = false; 12061 } while (!Var->getDeclContext()->Equals(DC)); 12062 12063 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 12064 // computing the type of the capture at each step, checking type-specific 12065 // requirements, and adding captures if requested. 12066 // If the variable had already been captured previously, we start capturing 12067 // at the lambda nested within that one. 12068 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 12069 ++I) { 12070 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 12071 12072 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 12073 if (!captureInBlock(BSI, Var, ExprLoc, 12074 BuildAndDiagnose, CaptureType, 12075 DeclRefType, Nested, *this)) 12076 return true; 12077 Nested = true; 12078 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 12079 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 12080 BuildAndDiagnose, CaptureType, 12081 DeclRefType, Nested, *this)) 12082 return true; 12083 Nested = true; 12084 } else { 12085 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12086 if (!captureInLambda(LSI, Var, ExprLoc, 12087 BuildAndDiagnose, CaptureType, 12088 DeclRefType, Nested, Kind, EllipsisLoc, 12089 /*IsTopScope*/I == N - 1, *this)) 12090 return true; 12091 Nested = true; 12092 } 12093 } 12094 return false; 12095 } 12096 12097 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 12098 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 12099 QualType CaptureType; 12100 QualType DeclRefType; 12101 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 12102 /*BuildAndDiagnose=*/true, CaptureType, 12103 DeclRefType, 0); 12104 } 12105 12106 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 12107 QualType CaptureType; 12108 QualType DeclRefType; 12109 12110 // Determine whether we can capture this variable. 12111 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 12112 /*BuildAndDiagnose=*/false, CaptureType, 12113 DeclRefType, 0)) 12114 return QualType(); 12115 12116 return DeclRefType; 12117 } 12118 12119 12120 12121 // If either the type of the variable or the initializer is dependent, 12122 // return false. Otherwise, determine whether the variable is a constant 12123 // expression. Use this if you need to know if a variable that might or 12124 // might not be dependent is truly a constant expression. 12125 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 12126 ASTContext &Context) { 12127 12128 if (Var->getType()->isDependentType()) 12129 return false; 12130 const VarDecl *DefVD = 0; 12131 Var->getAnyInitializer(DefVD); 12132 if (!DefVD) 12133 return false; 12134 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 12135 Expr *Init = cast<Expr>(Eval->Value); 12136 if (Init->isValueDependent()) 12137 return false; 12138 return IsVariableAConstantExpression(Var, Context); 12139 } 12140 12141 12142 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 12143 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 12144 // an object that satisfies the requirements for appearing in a 12145 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 12146 // is immediately applied." This function handles the lvalue-to-rvalue 12147 // conversion part. 12148 MaybeODRUseExprs.erase(E->IgnoreParens()); 12149 12150 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 12151 // to a variable that is a constant expression, and if so, identify it as 12152 // a reference to a variable that does not involve an odr-use of that 12153 // variable. 12154 if (LambdaScopeInfo *LSI = getCurLambda()) { 12155 Expr *SansParensExpr = E->IgnoreParens(); 12156 VarDecl *Var = 0; 12157 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 12158 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 12159 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 12160 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 12161 12162 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 12163 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 12164 } 12165 } 12166 12167 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 12168 if (!Res.isUsable()) 12169 return Res; 12170 12171 // If a constant-expression is a reference to a variable where we delay 12172 // deciding whether it is an odr-use, just assume we will apply the 12173 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 12174 // (a non-type template argument), we have special handling anyway. 12175 UpdateMarkingForLValueToRValue(Res.get()); 12176 return Res; 12177 } 12178 12179 void Sema::CleanupVarDeclMarking() { 12180 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 12181 e = MaybeODRUseExprs.end(); 12182 i != e; ++i) { 12183 VarDecl *Var; 12184 SourceLocation Loc; 12185 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 12186 Var = cast<VarDecl>(DRE->getDecl()); 12187 Loc = DRE->getLocation(); 12188 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 12189 Var = cast<VarDecl>(ME->getMemberDecl()); 12190 Loc = ME->getMemberLoc(); 12191 } else { 12192 llvm_unreachable("Unexpcted expression"); 12193 } 12194 12195 MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0); 12196 } 12197 12198 MaybeODRUseExprs.clear(); 12199 } 12200 12201 12202 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 12203 VarDecl *Var, Expr *E) { 12204 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 12205 "Invalid Expr argument to DoMarkVarDeclReferenced"); 12206 Var->setReferenced(); 12207 12208 // If the context is not potentially evaluated, this is not an odr-use and 12209 // does not trigger instantiation. 12210 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 12211 if (SemaRef.isUnevaluatedContext()) 12212 return; 12213 12214 // If we don't yet know whether this context is going to end up being an 12215 // evaluated context, and we're referencing a variable from an enclosing 12216 // scope, add a potential capture. 12217 // 12218 // FIXME: Is this necessary? These contexts are only used for default 12219 // arguments, where local variables can't be used. 12220 const bool RefersToEnclosingScope = 12221 (SemaRef.CurContext != Var->getDeclContext() && 12222 Var->getDeclContext()->isFunctionOrMethod() && 12223 Var->hasLocalStorage()); 12224 if (!RefersToEnclosingScope) 12225 return; 12226 12227 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 12228 // If a variable could potentially be odr-used, defer marking it so 12229 // until we finish analyzing the full expression for any lvalue-to-rvalue 12230 // or discarded value conversions that would obviate odr-use. 12231 // Add it to the list of potential captures that will be analyzed 12232 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 12233 // unless the variable is a reference that was initialized by a constant 12234 // expression (this will never need to be captured or odr-used). 12235 assert(E && "Capture variable should be used in an expression."); 12236 if (!Var->getType()->isReferenceType() || 12237 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 12238 LSI->addPotentialCapture(E->IgnoreParens()); 12239 } 12240 return; 12241 } 12242 12243 VarTemplateSpecializationDecl *VarSpec = 12244 dyn_cast<VarTemplateSpecializationDecl>(Var); 12245 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 12246 "Can't instantiate a partial template specialization."); 12247 12248 // Perform implicit instantiation of static data members, static data member 12249 // templates of class templates, and variable template specializations. Delay 12250 // instantiations of variable templates, except for those that could be used 12251 // in a constant expression. 12252 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 12253 if (isTemplateInstantiation(TSK)) { 12254 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 12255 12256 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 12257 if (Var->getPointOfInstantiation().isInvalid()) { 12258 // This is a modification of an existing AST node. Notify listeners. 12259 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 12260 L->StaticDataMemberInstantiated(Var); 12261 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 12262 // Don't bother trying to instantiate it again, unless we might need 12263 // its initializer before we get to the end of the TU. 12264 TryInstantiating = false; 12265 } 12266 12267 if (Var->getPointOfInstantiation().isInvalid()) 12268 Var->setTemplateSpecializationKind(TSK, Loc); 12269 12270 if (TryInstantiating) { 12271 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 12272 bool InstantiationDependent = false; 12273 bool IsNonDependent = 12274 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 12275 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 12276 : true; 12277 12278 // Do not instantiate specializations that are still type-dependent. 12279 if (IsNonDependent) { 12280 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 12281 // Do not defer instantiations of variables which could be used in a 12282 // constant expression. 12283 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 12284 } else { 12285 SemaRef.PendingInstantiations 12286 .push_back(std::make_pair(Var, PointOfInstantiation)); 12287 } 12288 } 12289 } 12290 } 12291 12292 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 12293 // the requirements for appearing in a constant expression (5.19) and, if 12294 // it is an object, the lvalue-to-rvalue conversion (4.1) 12295 // is immediately applied." We check the first part here, and 12296 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 12297 // Note that we use the C++11 definition everywhere because nothing in 12298 // C++03 depends on whether we get the C++03 version correct. The second 12299 // part does not apply to references, since they are not objects. 12300 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 12301 // A reference initialized by a constant expression can never be 12302 // odr-used, so simply ignore it. 12303 if (!Var->getType()->isReferenceType()) 12304 SemaRef.MaybeODRUseExprs.insert(E); 12305 } else 12306 MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0); 12307 } 12308 12309 /// \brief Mark a variable referenced, and check whether it is odr-used 12310 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 12311 /// used directly for normal expressions referring to VarDecl. 12312 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 12313 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 12314 } 12315 12316 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 12317 Decl *D, Expr *E, bool OdrUse) { 12318 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 12319 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 12320 return; 12321 } 12322 12323 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 12324 12325 // If this is a call to a method via a cast, also mark the method in the 12326 // derived class used in case codegen can devirtualize the call. 12327 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12328 if (!ME) 12329 return; 12330 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12331 if (!MD) 12332 return; 12333 const Expr *Base = ME->getBase(); 12334 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12335 if (!MostDerivedClassDecl) 12336 return; 12337 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12338 if (!DM || DM->isPure()) 12339 return; 12340 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12341 } 12342 12343 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12344 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12345 // TODO: update this with DR# once a defect report is filed. 12346 // C++11 defect. The address of a pure member should not be an ODR use, even 12347 // if it's a qualified reference. 12348 bool OdrUse = true; 12349 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12350 if (Method->isVirtual()) 12351 OdrUse = false; 12352 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12353 } 12354 12355 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12356 void Sema::MarkMemberReferenced(MemberExpr *E) { 12357 // C++11 [basic.def.odr]p2: 12358 // A non-overloaded function whose name appears as a potentially-evaluated 12359 // expression or a member of a set of candidate functions, if selected by 12360 // overload resolution when referred to from a potentially-evaluated 12361 // expression, is odr-used, unless it is a pure virtual function and its 12362 // name is not explicitly qualified. 12363 bool OdrUse = true; 12364 if (!E->hasQualifier()) { 12365 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12366 if (Method->isPure()) 12367 OdrUse = false; 12368 } 12369 SourceLocation Loc = E->getMemberLoc().isValid() ? 12370 E->getMemberLoc() : E->getLocStart(); 12371 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12372 } 12373 12374 /// \brief Perform marking for a reference to an arbitrary declaration. It 12375 /// marks the declaration referenced, and performs odr-use checking for functions 12376 /// and variables. This method should not be used when building an normal 12377 /// expression which refers to a variable. 12378 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12379 if (OdrUse) { 12380 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12381 MarkVariableReferenced(Loc, VD); 12382 return; 12383 } 12384 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12385 MarkFunctionReferenced(Loc, FD); 12386 return; 12387 } 12388 } 12389 D->setReferenced(); 12390 } 12391 12392 namespace { 12393 // Mark all of the declarations referenced 12394 // FIXME: Not fully implemented yet! We need to have a better understanding 12395 // of when we're entering 12396 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12397 Sema &S; 12398 SourceLocation Loc; 12399 12400 public: 12401 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12402 12403 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12404 12405 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12406 bool TraverseRecordType(RecordType *T); 12407 }; 12408 } 12409 12410 bool MarkReferencedDecls::TraverseTemplateArgument( 12411 const TemplateArgument &Arg) { 12412 if (Arg.getKind() == TemplateArgument::Declaration) { 12413 if (Decl *D = Arg.getAsDecl()) 12414 S.MarkAnyDeclReferenced(Loc, D, true); 12415 } 12416 12417 return Inherited::TraverseTemplateArgument(Arg); 12418 } 12419 12420 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12421 if (ClassTemplateSpecializationDecl *Spec 12422 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12423 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12424 return TraverseTemplateArguments(Args.data(), Args.size()); 12425 } 12426 12427 return true; 12428 } 12429 12430 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12431 MarkReferencedDecls Marker(*this, Loc); 12432 Marker.TraverseType(Context.getCanonicalType(T)); 12433 } 12434 12435 namespace { 12436 /// \brief Helper class that marks all of the declarations referenced by 12437 /// potentially-evaluated subexpressions as "referenced". 12438 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12439 Sema &S; 12440 bool SkipLocalVariables; 12441 12442 public: 12443 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12444 12445 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12446 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12447 12448 void VisitDeclRefExpr(DeclRefExpr *E) { 12449 // If we were asked not to visit local variables, don't. 12450 if (SkipLocalVariables) { 12451 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12452 if (VD->hasLocalStorage()) 12453 return; 12454 } 12455 12456 S.MarkDeclRefReferenced(E); 12457 } 12458 12459 void VisitMemberExpr(MemberExpr *E) { 12460 S.MarkMemberReferenced(E); 12461 Inherited::VisitMemberExpr(E); 12462 } 12463 12464 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12465 S.MarkFunctionReferenced(E->getLocStart(), 12466 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12467 Visit(E->getSubExpr()); 12468 } 12469 12470 void VisitCXXNewExpr(CXXNewExpr *E) { 12471 if (E->getOperatorNew()) 12472 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12473 if (E->getOperatorDelete()) 12474 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12475 Inherited::VisitCXXNewExpr(E); 12476 } 12477 12478 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12479 if (E->getOperatorDelete()) 12480 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12481 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12482 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12483 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12484 S.MarkFunctionReferenced(E->getLocStart(), 12485 S.LookupDestructor(Record)); 12486 } 12487 12488 Inherited::VisitCXXDeleteExpr(E); 12489 } 12490 12491 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12492 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12493 Inherited::VisitCXXConstructExpr(E); 12494 } 12495 12496 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12497 Visit(E->getExpr()); 12498 } 12499 12500 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12501 Inherited::VisitImplicitCastExpr(E); 12502 12503 if (E->getCastKind() == CK_LValueToRValue) 12504 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12505 } 12506 }; 12507 } 12508 12509 /// \brief Mark any declarations that appear within this expression or any 12510 /// potentially-evaluated subexpressions as "referenced". 12511 /// 12512 /// \param SkipLocalVariables If true, don't mark local variables as 12513 /// 'referenced'. 12514 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12515 bool SkipLocalVariables) { 12516 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12517 } 12518 12519 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 12520 /// of the program being compiled. 12521 /// 12522 /// This routine emits the given diagnostic when the code currently being 12523 /// type-checked is "potentially evaluated", meaning that there is a 12524 /// possibility that the code will actually be executable. Code in sizeof() 12525 /// expressions, code used only during overload resolution, etc., are not 12526 /// potentially evaluated. This routine will suppress such diagnostics or, 12527 /// in the absolutely nutty case of potentially potentially evaluated 12528 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 12529 /// later. 12530 /// 12531 /// This routine should be used for all diagnostics that describe the run-time 12532 /// behavior of a program, such as passing a non-POD value through an ellipsis. 12533 /// Failure to do so will likely result in spurious diagnostics or failures 12534 /// during overload resolution or within sizeof/alignof/typeof/typeid. 12535 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12536 const PartialDiagnostic &PD) { 12537 switch (ExprEvalContexts.back().Context) { 12538 case Unevaluated: 12539 case UnevaluatedAbstract: 12540 // The argument will never be evaluated, so don't complain. 12541 break; 12542 12543 case ConstantEvaluated: 12544 // Relevant diagnostics should be produced by constant evaluation. 12545 break; 12546 12547 case PotentiallyEvaluated: 12548 case PotentiallyEvaluatedIfUsed: 12549 if (Statement && getCurFunctionOrMethodDecl()) { 12550 FunctionScopes.back()->PossiblyUnreachableDiags. 12551 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12552 } 12553 else 12554 Diag(Loc, PD); 12555 12556 return true; 12557 } 12558 12559 return false; 12560 } 12561 12562 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12563 CallExpr *CE, FunctionDecl *FD) { 12564 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12565 return false; 12566 12567 // If we're inside a decltype's expression, don't check for a valid return 12568 // type or construct temporaries until we know whether this is the last call. 12569 if (ExprEvalContexts.back().IsDecltype) { 12570 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12571 return false; 12572 } 12573 12574 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12575 FunctionDecl *FD; 12576 CallExpr *CE; 12577 12578 public: 12579 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12580 : FD(FD), CE(CE) { } 12581 12582 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 12583 if (!FD) { 12584 S.Diag(Loc, diag::err_call_incomplete_return) 12585 << T << CE->getSourceRange(); 12586 return; 12587 } 12588 12589 S.Diag(Loc, diag::err_call_function_incomplete_return) 12590 << CE->getSourceRange() << FD->getDeclName() << T; 12591 S.Diag(FD->getLocation(), 12592 diag::note_function_with_incomplete_return_type_declared_here) 12593 << FD->getDeclName(); 12594 } 12595 } Diagnoser(FD, CE); 12596 12597 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12598 return true; 12599 12600 return false; 12601 } 12602 12603 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12604 // will prevent this condition from triggering, which is what we want. 12605 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12606 SourceLocation Loc; 12607 12608 unsigned diagnostic = diag::warn_condition_is_assignment; 12609 bool IsOrAssign = false; 12610 12611 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12612 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12613 return; 12614 12615 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12616 12617 // Greylist some idioms by putting them into a warning subcategory. 12618 if (ObjCMessageExpr *ME 12619 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12620 Selector Sel = ME->getSelector(); 12621 12622 // self = [<foo> init...] 12623 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12624 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12625 12626 // <foo> = [<bar> nextObject] 12627 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12628 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12629 } 12630 12631 Loc = Op->getOperatorLoc(); 12632 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12633 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12634 return; 12635 12636 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12637 Loc = Op->getOperatorLoc(); 12638 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12639 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12640 else { 12641 // Not an assignment. 12642 return; 12643 } 12644 12645 Diag(Loc, diagnostic) << E->getSourceRange(); 12646 12647 SourceLocation Open = E->getLocStart(); 12648 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12649 Diag(Loc, diag::note_condition_assign_silence) 12650 << FixItHint::CreateInsertion(Open, "(") 12651 << FixItHint::CreateInsertion(Close, ")"); 12652 12653 if (IsOrAssign) 12654 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12655 << FixItHint::CreateReplacement(Loc, "!="); 12656 else 12657 Diag(Loc, diag::note_condition_assign_to_comparison) 12658 << FixItHint::CreateReplacement(Loc, "=="); 12659 } 12660 12661 /// \brief Redundant parentheses over an equality comparison can indicate 12662 /// that the user intended an assignment used as condition. 12663 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12664 // Don't warn if the parens came from a macro. 12665 SourceLocation parenLoc = ParenE->getLocStart(); 12666 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12667 return; 12668 // Don't warn for dependent expressions. 12669 if (ParenE->isTypeDependent()) 12670 return; 12671 12672 Expr *E = ParenE->IgnoreParens(); 12673 12674 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12675 if (opE->getOpcode() == BO_EQ && 12676 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12677 == Expr::MLV_Valid) { 12678 SourceLocation Loc = opE->getOperatorLoc(); 12679 12680 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12681 SourceRange ParenERange = ParenE->getSourceRange(); 12682 Diag(Loc, diag::note_equality_comparison_silence) 12683 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12684 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12685 Diag(Loc, diag::note_equality_comparison_to_assign) 12686 << FixItHint::CreateReplacement(Loc, "="); 12687 } 12688 } 12689 12690 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12691 DiagnoseAssignmentAsCondition(E); 12692 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12693 DiagnoseEqualityWithExtraParens(parenE); 12694 12695 ExprResult result = CheckPlaceholderExpr(E); 12696 if (result.isInvalid()) return ExprError(); 12697 E = result.take(); 12698 12699 if (!E->isTypeDependent()) { 12700 if (getLangOpts().CPlusPlus) 12701 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12702 12703 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12704 if (ERes.isInvalid()) 12705 return ExprError(); 12706 E = ERes.take(); 12707 12708 QualType T = E->getType(); 12709 if (!T->isScalarType()) { // C99 6.8.4.1p1 12710 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12711 << T << E->getSourceRange(); 12712 return ExprError(); 12713 } 12714 } 12715 12716 return Owned(E); 12717 } 12718 12719 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12720 Expr *SubExpr) { 12721 if (!SubExpr) 12722 return ExprError(); 12723 12724 return CheckBooleanCondition(SubExpr, Loc); 12725 } 12726 12727 namespace { 12728 /// A visitor for rebuilding a call to an __unknown_any expression 12729 /// to have an appropriate type. 12730 struct RebuildUnknownAnyFunction 12731 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12732 12733 Sema &S; 12734 12735 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12736 12737 ExprResult VisitStmt(Stmt *S) { 12738 llvm_unreachable("unexpected statement!"); 12739 } 12740 12741 ExprResult VisitExpr(Expr *E) { 12742 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12743 << E->getSourceRange(); 12744 return ExprError(); 12745 } 12746 12747 /// Rebuild an expression which simply semantically wraps another 12748 /// expression which it shares the type and value kind of. 12749 template <class T> ExprResult rebuildSugarExpr(T *E) { 12750 ExprResult SubResult = Visit(E->getSubExpr()); 12751 if (SubResult.isInvalid()) return ExprError(); 12752 12753 Expr *SubExpr = SubResult.take(); 12754 E->setSubExpr(SubExpr); 12755 E->setType(SubExpr->getType()); 12756 E->setValueKind(SubExpr->getValueKind()); 12757 assert(E->getObjectKind() == OK_Ordinary); 12758 return E; 12759 } 12760 12761 ExprResult VisitParenExpr(ParenExpr *E) { 12762 return rebuildSugarExpr(E); 12763 } 12764 12765 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12766 return rebuildSugarExpr(E); 12767 } 12768 12769 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12770 ExprResult SubResult = Visit(E->getSubExpr()); 12771 if (SubResult.isInvalid()) return ExprError(); 12772 12773 Expr *SubExpr = SubResult.take(); 12774 E->setSubExpr(SubExpr); 12775 E->setType(S.Context.getPointerType(SubExpr->getType())); 12776 assert(E->getValueKind() == VK_RValue); 12777 assert(E->getObjectKind() == OK_Ordinary); 12778 return E; 12779 } 12780 12781 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12782 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12783 12784 E->setType(VD->getType()); 12785 12786 assert(E->getValueKind() == VK_RValue); 12787 if (S.getLangOpts().CPlusPlus && 12788 !(isa<CXXMethodDecl>(VD) && 12789 cast<CXXMethodDecl>(VD)->isInstance())) 12790 E->setValueKind(VK_LValue); 12791 12792 return E; 12793 } 12794 12795 ExprResult VisitMemberExpr(MemberExpr *E) { 12796 return resolveDecl(E, E->getMemberDecl()); 12797 } 12798 12799 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12800 return resolveDecl(E, E->getDecl()); 12801 } 12802 }; 12803 } 12804 12805 /// Given a function expression of unknown-any type, try to rebuild it 12806 /// to have a function type. 12807 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12808 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12809 if (Result.isInvalid()) return ExprError(); 12810 return S.DefaultFunctionArrayConversion(Result.take()); 12811 } 12812 12813 namespace { 12814 /// A visitor for rebuilding an expression of type __unknown_anytype 12815 /// into one which resolves the type directly on the referring 12816 /// expression. Strict preservation of the original source 12817 /// structure is not a goal. 12818 struct RebuildUnknownAnyExpr 12819 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12820 12821 Sema &S; 12822 12823 /// The current destination type. 12824 QualType DestType; 12825 12826 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12827 : S(S), DestType(CastType) {} 12828 12829 ExprResult VisitStmt(Stmt *S) { 12830 llvm_unreachable("unexpected statement!"); 12831 } 12832 12833 ExprResult VisitExpr(Expr *E) { 12834 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12835 << E->getSourceRange(); 12836 return ExprError(); 12837 } 12838 12839 ExprResult VisitCallExpr(CallExpr *E); 12840 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12841 12842 /// Rebuild an expression which simply semantically wraps another 12843 /// expression which it shares the type and value kind of. 12844 template <class T> ExprResult rebuildSugarExpr(T *E) { 12845 ExprResult SubResult = Visit(E->getSubExpr()); 12846 if (SubResult.isInvalid()) return ExprError(); 12847 Expr *SubExpr = SubResult.take(); 12848 E->setSubExpr(SubExpr); 12849 E->setType(SubExpr->getType()); 12850 E->setValueKind(SubExpr->getValueKind()); 12851 assert(E->getObjectKind() == OK_Ordinary); 12852 return E; 12853 } 12854 12855 ExprResult VisitParenExpr(ParenExpr *E) { 12856 return rebuildSugarExpr(E); 12857 } 12858 12859 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12860 return rebuildSugarExpr(E); 12861 } 12862 12863 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12864 const PointerType *Ptr = DestType->getAs<PointerType>(); 12865 if (!Ptr) { 12866 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12867 << E->getSourceRange(); 12868 return ExprError(); 12869 } 12870 assert(E->getValueKind() == VK_RValue); 12871 assert(E->getObjectKind() == OK_Ordinary); 12872 E->setType(DestType); 12873 12874 // Build the sub-expression as if it were an object of the pointee type. 12875 DestType = Ptr->getPointeeType(); 12876 ExprResult SubResult = Visit(E->getSubExpr()); 12877 if (SubResult.isInvalid()) return ExprError(); 12878 E->setSubExpr(SubResult.take()); 12879 return E; 12880 } 12881 12882 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12883 12884 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12885 12886 ExprResult VisitMemberExpr(MemberExpr *E) { 12887 return resolveDecl(E, E->getMemberDecl()); 12888 } 12889 12890 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12891 return resolveDecl(E, E->getDecl()); 12892 } 12893 }; 12894 } 12895 12896 /// Rebuilds a call expression which yielded __unknown_anytype. 12897 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12898 Expr *CalleeExpr = E->getCallee(); 12899 12900 enum FnKind { 12901 FK_MemberFunction, 12902 FK_FunctionPointer, 12903 FK_BlockPointer 12904 }; 12905 12906 FnKind Kind; 12907 QualType CalleeType = CalleeExpr->getType(); 12908 if (CalleeType == S.Context.BoundMemberTy) { 12909 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12910 Kind = FK_MemberFunction; 12911 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12912 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12913 CalleeType = Ptr->getPointeeType(); 12914 Kind = FK_FunctionPointer; 12915 } else { 12916 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12917 Kind = FK_BlockPointer; 12918 } 12919 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12920 12921 // Verify that this is a legal result type of a function. 12922 if (DestType->isArrayType() || DestType->isFunctionType()) { 12923 unsigned diagID = diag::err_func_returning_array_function; 12924 if (Kind == FK_BlockPointer) 12925 diagID = diag::err_block_returning_array_function; 12926 12927 S.Diag(E->getExprLoc(), diagID) 12928 << DestType->isFunctionType() << DestType; 12929 return ExprError(); 12930 } 12931 12932 // Otherwise, go ahead and set DestType as the call's result. 12933 E->setType(DestType.getNonLValueExprType(S.Context)); 12934 E->setValueKind(Expr::getValueKindForType(DestType)); 12935 assert(E->getObjectKind() == OK_Ordinary); 12936 12937 // Rebuild the function type, replacing the result type with DestType. 12938 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12939 if (Proto) { 12940 // __unknown_anytype(...) is a special case used by the debugger when 12941 // it has no idea what a function's signature is. 12942 // 12943 // We want to build this call essentially under the K&R 12944 // unprototyped rules, but making a FunctionNoProtoType in C++ 12945 // would foul up all sorts of assumptions. However, we cannot 12946 // simply pass all arguments as variadic arguments, nor can we 12947 // portably just call the function under a non-variadic type; see 12948 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12949 // However, it turns out that in practice it is generally safe to 12950 // call a function declared as "A foo(B,C,D);" under the prototype 12951 // "A foo(B,C,D,...);". The only known exception is with the 12952 // Windows ABI, where any variadic function is implicitly cdecl 12953 // regardless of its normal CC. Therefore we change the parameter 12954 // types to match the types of the arguments. 12955 // 12956 // This is a hack, but it is far superior to moving the 12957 // corresponding target-specific code from IR-gen to Sema/AST. 12958 12959 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 12960 SmallVector<QualType, 8> ArgTypes; 12961 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12962 ArgTypes.reserve(E->getNumArgs()); 12963 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12964 Expr *Arg = E->getArg(i); 12965 QualType ArgType = Arg->getType(); 12966 if (E->isLValue()) { 12967 ArgType = S.Context.getLValueReferenceType(ArgType); 12968 } else if (E->isXValue()) { 12969 ArgType = S.Context.getRValueReferenceType(ArgType); 12970 } 12971 ArgTypes.push_back(ArgType); 12972 } 12973 ParamTypes = ArgTypes; 12974 } 12975 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12976 Proto->getExtProtoInfo()); 12977 } else { 12978 DestType = S.Context.getFunctionNoProtoType(DestType, 12979 FnType->getExtInfo()); 12980 } 12981 12982 // Rebuild the appropriate pointer-to-function type. 12983 switch (Kind) { 12984 case FK_MemberFunction: 12985 // Nothing to do. 12986 break; 12987 12988 case FK_FunctionPointer: 12989 DestType = S.Context.getPointerType(DestType); 12990 break; 12991 12992 case FK_BlockPointer: 12993 DestType = S.Context.getBlockPointerType(DestType); 12994 break; 12995 } 12996 12997 // Finally, we can recurse. 12998 ExprResult CalleeResult = Visit(CalleeExpr); 12999 if (!CalleeResult.isUsable()) return ExprError(); 13000 E->setCallee(CalleeResult.take()); 13001 13002 // Bind a temporary if necessary. 13003 return S.MaybeBindToTemporary(E); 13004 } 13005 13006 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 13007 // Verify that this is a legal result type of a call. 13008 if (DestType->isArrayType() || DestType->isFunctionType()) { 13009 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 13010 << DestType->isFunctionType() << DestType; 13011 return ExprError(); 13012 } 13013 13014 // Rewrite the method result type if available. 13015 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 13016 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 13017 Method->setReturnType(DestType); 13018 } 13019 13020 // Change the type of the message. 13021 E->setType(DestType.getNonReferenceType()); 13022 E->setValueKind(Expr::getValueKindForType(DestType)); 13023 13024 return S.MaybeBindToTemporary(E); 13025 } 13026 13027 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 13028 // The only case we should ever see here is a function-to-pointer decay. 13029 if (E->getCastKind() == CK_FunctionToPointerDecay) { 13030 assert(E->getValueKind() == VK_RValue); 13031 assert(E->getObjectKind() == OK_Ordinary); 13032 13033 E->setType(DestType); 13034 13035 // Rebuild the sub-expression as the pointee (function) type. 13036 DestType = DestType->castAs<PointerType>()->getPointeeType(); 13037 13038 ExprResult Result = Visit(E->getSubExpr()); 13039 if (!Result.isUsable()) return ExprError(); 13040 13041 E->setSubExpr(Result.take()); 13042 return S.Owned(E); 13043 } else if (E->getCastKind() == CK_LValueToRValue) { 13044 assert(E->getValueKind() == VK_RValue); 13045 assert(E->getObjectKind() == OK_Ordinary); 13046 13047 assert(isa<BlockPointerType>(E->getType())); 13048 13049 E->setType(DestType); 13050 13051 // The sub-expression has to be a lvalue reference, so rebuild it as such. 13052 DestType = S.Context.getLValueReferenceType(DestType); 13053 13054 ExprResult Result = Visit(E->getSubExpr()); 13055 if (!Result.isUsable()) return ExprError(); 13056 13057 E->setSubExpr(Result.take()); 13058 return S.Owned(E); 13059 } else { 13060 llvm_unreachable("Unhandled cast type!"); 13061 } 13062 } 13063 13064 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 13065 ExprValueKind ValueKind = VK_LValue; 13066 QualType Type = DestType; 13067 13068 // We know how to make this work for certain kinds of decls: 13069 13070 // - functions 13071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 13072 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 13073 DestType = Ptr->getPointeeType(); 13074 ExprResult Result = resolveDecl(E, VD); 13075 if (Result.isInvalid()) return ExprError(); 13076 return S.ImpCastExprToType(Result.take(), Type, 13077 CK_FunctionToPointerDecay, VK_RValue); 13078 } 13079 13080 if (!Type->isFunctionType()) { 13081 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 13082 << VD << E->getSourceRange(); 13083 return ExprError(); 13084 } 13085 13086 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 13087 if (MD->isInstance()) { 13088 ValueKind = VK_RValue; 13089 Type = S.Context.BoundMemberTy; 13090 } 13091 13092 // Function references aren't l-values in C. 13093 if (!S.getLangOpts().CPlusPlus) 13094 ValueKind = VK_RValue; 13095 13096 // - variables 13097 } else if (isa<VarDecl>(VD)) { 13098 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 13099 Type = RefTy->getPointeeType(); 13100 } else if (Type->isFunctionType()) { 13101 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 13102 << VD << E->getSourceRange(); 13103 return ExprError(); 13104 } 13105 13106 // - nothing else 13107 } else { 13108 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 13109 << VD << E->getSourceRange(); 13110 return ExprError(); 13111 } 13112 13113 // Modifying the declaration like this is friendly to IR-gen but 13114 // also really dangerous. 13115 VD->setType(DestType); 13116 E->setType(Type); 13117 E->setValueKind(ValueKind); 13118 return S.Owned(E); 13119 } 13120 13121 /// Check a cast of an unknown-any type. We intentionally only 13122 /// trigger this for C-style casts. 13123 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 13124 Expr *CastExpr, CastKind &CastKind, 13125 ExprValueKind &VK, CXXCastPath &Path) { 13126 // Rewrite the casted expression from scratch. 13127 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 13128 if (!result.isUsable()) return ExprError(); 13129 13130 CastExpr = result.take(); 13131 VK = CastExpr->getValueKind(); 13132 CastKind = CK_NoOp; 13133 13134 return CastExpr; 13135 } 13136 13137 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 13138 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 13139 } 13140 13141 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 13142 Expr *arg, QualType ¶mType) { 13143 // If the syntactic form of the argument is not an explicit cast of 13144 // any sort, just do default argument promotion. 13145 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 13146 if (!castArg) { 13147 ExprResult result = DefaultArgumentPromotion(arg); 13148 if (result.isInvalid()) return ExprError(); 13149 paramType = result.get()->getType(); 13150 return result; 13151 } 13152 13153 // Otherwise, use the type that was written in the explicit cast. 13154 assert(!arg->hasPlaceholderType()); 13155 paramType = castArg->getTypeAsWritten(); 13156 13157 // Copy-initialize a parameter of that type. 13158 InitializedEntity entity = 13159 InitializedEntity::InitializeParameter(Context, paramType, 13160 /*consumed*/ false); 13161 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 13162 } 13163 13164 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 13165 Expr *orig = E; 13166 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 13167 while (true) { 13168 E = E->IgnoreParenImpCasts(); 13169 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 13170 E = call->getCallee(); 13171 diagID = diag::err_uncasted_call_of_unknown_any; 13172 } else { 13173 break; 13174 } 13175 } 13176 13177 SourceLocation loc; 13178 NamedDecl *d; 13179 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 13180 loc = ref->getLocation(); 13181 d = ref->getDecl(); 13182 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 13183 loc = mem->getMemberLoc(); 13184 d = mem->getMemberDecl(); 13185 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 13186 diagID = diag::err_uncasted_call_of_unknown_any; 13187 loc = msg->getSelectorStartLoc(); 13188 d = msg->getMethodDecl(); 13189 if (!d) { 13190 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 13191 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 13192 << orig->getSourceRange(); 13193 return ExprError(); 13194 } 13195 } else { 13196 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13197 << E->getSourceRange(); 13198 return ExprError(); 13199 } 13200 13201 S.Diag(loc, diagID) << d << orig->getSourceRange(); 13202 13203 // Never recoverable. 13204 return ExprError(); 13205 } 13206 13207 /// Check for operands with placeholder types and complain if found. 13208 /// Returns true if there was an error and no recovery was possible. 13209 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 13210 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 13211 if (!placeholderType) return Owned(E); 13212 13213 switch (placeholderType->getKind()) { 13214 13215 // Overloaded expressions. 13216 case BuiltinType::Overload: { 13217 // Try to resolve a single function template specialization. 13218 // This is obligatory. 13219 ExprResult result = Owned(E); 13220 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 13221 return result; 13222 13223 // If that failed, try to recover with a call. 13224 } else { 13225 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 13226 /*complain*/ true); 13227 return result; 13228 } 13229 } 13230 13231 // Bound member functions. 13232 case BuiltinType::BoundMember: { 13233 ExprResult result = Owned(E); 13234 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 13235 /*complain*/ true); 13236 return result; 13237 } 13238 13239 // ARC unbridged casts. 13240 case BuiltinType::ARCUnbridgedCast: { 13241 Expr *realCast = stripARCUnbridgedCast(E); 13242 diagnoseARCUnbridgedCast(realCast); 13243 return Owned(realCast); 13244 } 13245 13246 // Expressions of unknown type. 13247 case BuiltinType::UnknownAny: 13248 return diagnoseUnknownAnyExpr(*this, E); 13249 13250 // Pseudo-objects. 13251 case BuiltinType::PseudoObject: 13252 return checkPseudoObjectRValue(E); 13253 13254 case BuiltinType::BuiltinFn: 13255 Diag(E->getLocStart(), diag::err_builtin_fn_use); 13256 return ExprError(); 13257 13258 // Everything else should be impossible. 13259 #define BUILTIN_TYPE(Id, SingletonId) \ 13260 case BuiltinType::Id: 13261 #define PLACEHOLDER_TYPE(Id, SingletonId) 13262 #include "clang/AST/BuiltinTypes.def" 13263 break; 13264 } 13265 13266 llvm_unreachable("invalid placeholder type!"); 13267 } 13268 13269 bool Sema::CheckCaseExpression(Expr *E) { 13270 if (E->isTypeDependent()) 13271 return true; 13272 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 13273 return E->getType()->isIntegralOrEnumerationType(); 13274 return false; 13275 } 13276 13277 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 13278 ExprResult 13279 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 13280 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 13281 "Unknown Objective-C Boolean value!"); 13282 QualType BoolT = Context.ObjCBuiltinBoolTy; 13283 if (!Context.getBOOLDecl()) { 13284 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 13285 Sema::LookupOrdinaryName); 13286 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 13287 NamedDecl *ND = Result.getFoundDecl(); 13288 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 13289 Context.setBOOLDecl(TD); 13290 } 13291 } 13292 if (Context.getBOOLDecl()) 13293 BoolT = Context.getBOOLType(); 13294 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 13295 BoolT, OpLoc)); 13296 } 13297