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::CSK_Normal); 1859 OverloadCandidateSet::iterator Best; 1860 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1861 CDEnd = Corrected.end(); 1862 CD != CDEnd; ++CD) { 1863 if (FunctionTemplateDecl *FTD = 1864 dyn_cast<FunctionTemplateDecl>(*CD)) 1865 AddTemplateOverloadCandidate( 1866 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1867 Args, OCS); 1868 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1869 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1870 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1871 Args, OCS); 1872 } 1873 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1874 case OR_Success: 1875 ND = Best->Function; 1876 Corrected.setCorrectionDecl(ND); 1877 break; 1878 default: 1879 // FIXME: Arbitrarily pick the first declaration for the note. 1880 Corrected.setCorrectionDecl(ND); 1881 break; 1882 } 1883 } 1884 R.addDecl(ND); 1885 1886 AcceptableWithRecovery = 1887 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1888 // FIXME: If we ended up with a typo for a type name or 1889 // Objective-C class name, we're in trouble because the parser 1890 // is in the wrong place to recover. Suggest the typo 1891 // correction, but don't make it a fix-it since we're not going 1892 // to recover well anyway. 1893 AcceptableWithoutRecovery = 1894 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1895 } else { 1896 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1897 // because we aren't able to recover. 1898 AcceptableWithoutRecovery = true; 1899 } 1900 1901 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1902 unsigned NoteID = (Corrected.getCorrectionDecl() && 1903 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1904 ? diag::note_implicit_param_decl 1905 : diag::note_previous_decl; 1906 if (SS.isEmpty()) 1907 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1908 PDiag(NoteID), AcceptableWithRecovery); 1909 else 1910 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1911 << Name << computeDeclContext(SS, false) 1912 << DroppedSpecifier << SS.getRange(), 1913 PDiag(NoteID), AcceptableWithRecovery); 1914 1915 // Tell the callee whether to try to recover. 1916 return !AcceptableWithRecovery; 1917 } 1918 } 1919 R.clear(); 1920 1921 // Emit a special diagnostic for failed member lookups. 1922 // FIXME: computing the declaration context might fail here (?) 1923 if (!SS.isEmpty()) { 1924 Diag(R.getNameLoc(), diag::err_no_member) 1925 << Name << computeDeclContext(SS, false) 1926 << SS.getRange(); 1927 return true; 1928 } 1929 1930 // Give up, we can't recover. 1931 Diag(R.getNameLoc(), diagnostic) << Name; 1932 return true; 1933 } 1934 1935 ExprResult Sema::ActOnIdExpression(Scope *S, 1936 CXXScopeSpec &SS, 1937 SourceLocation TemplateKWLoc, 1938 UnqualifiedId &Id, 1939 bool HasTrailingLParen, 1940 bool IsAddressOfOperand, 1941 CorrectionCandidateCallback *CCC, 1942 bool IsInlineAsmIdentifier) { 1943 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1944 "cannot be direct & operand and have a trailing lparen"); 1945 if (SS.isInvalid()) 1946 return ExprError(); 1947 1948 TemplateArgumentListInfo TemplateArgsBuffer; 1949 1950 // Decompose the UnqualifiedId into the following data. 1951 DeclarationNameInfo NameInfo; 1952 const TemplateArgumentListInfo *TemplateArgs; 1953 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1954 1955 DeclarationName Name = NameInfo.getName(); 1956 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1957 SourceLocation NameLoc = NameInfo.getLoc(); 1958 1959 // C++ [temp.dep.expr]p3: 1960 // An id-expression is type-dependent if it contains: 1961 // -- an identifier that was declared with a dependent type, 1962 // (note: handled after lookup) 1963 // -- a template-id that is dependent, 1964 // (note: handled in BuildTemplateIdExpr) 1965 // -- a conversion-function-id that specifies a dependent type, 1966 // -- a nested-name-specifier that contains a class-name that 1967 // names a dependent type. 1968 // Determine whether this is a member of an unknown specialization; 1969 // we need to handle these differently. 1970 bool DependentID = false; 1971 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1972 Name.getCXXNameType()->isDependentType()) { 1973 DependentID = true; 1974 } else if (SS.isSet()) { 1975 if (DeclContext *DC = computeDeclContext(SS, false)) { 1976 if (RequireCompleteDeclContext(SS, DC)) 1977 return ExprError(); 1978 } else { 1979 DependentID = true; 1980 } 1981 } 1982 1983 if (DependentID) 1984 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1985 IsAddressOfOperand, TemplateArgs); 1986 1987 // Perform the required lookup. 1988 LookupResult R(*this, NameInfo, 1989 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1990 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1991 if (TemplateArgs) { 1992 // Lookup the template name again to correctly establish the context in 1993 // which it was found. This is really unfortunate as we already did the 1994 // lookup to determine that it was a template name in the first place. If 1995 // this becomes a performance hit, we can work harder to preserve those 1996 // results until we get here but it's likely not worth it. 1997 bool MemberOfUnknownSpecialization; 1998 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1999 MemberOfUnknownSpecialization); 2000 2001 if (MemberOfUnknownSpecialization || 2002 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2003 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2004 IsAddressOfOperand, TemplateArgs); 2005 } else { 2006 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2007 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2008 2009 // If the result might be in a dependent base class, this is a dependent 2010 // id-expression. 2011 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2012 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2013 IsAddressOfOperand, TemplateArgs); 2014 2015 // If this reference is in an Objective-C method, then we need to do 2016 // some special Objective-C lookup, too. 2017 if (IvarLookupFollowUp) { 2018 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2019 if (E.isInvalid()) 2020 return ExprError(); 2021 2022 if (Expr *Ex = E.takeAs<Expr>()) 2023 return Owned(Ex); 2024 } 2025 } 2026 2027 if (R.isAmbiguous()) 2028 return ExprError(); 2029 2030 // Determine whether this name might be a candidate for 2031 // argument-dependent lookup. 2032 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2033 2034 if (R.empty() && !ADL) { 2035 2036 // Otherwise, this could be an implicitly declared function reference (legal 2037 // in C90, extension in C99, forbidden in C++). 2038 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2039 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2040 if (D) R.addDecl(D); 2041 } 2042 2043 // If this name wasn't predeclared and if this is not a function 2044 // call, diagnose the problem. 2045 if (R.empty()) { 2046 // In Microsoft mode, if we are inside a template class member function 2047 // whose parent class has dependent base classes, and we can't resolve 2048 // an unqualified identifier, then assume the identifier is a member of a 2049 // dependent base class. The goal is to postpone name lookup to 2050 // instantiation time to be able to search into the type dependent base 2051 // classes. 2052 // FIXME: If we want 100% compatibility with MSVC, we will have delay all 2053 // unqualified name lookup. Any name lookup during template parsing means 2054 // clang might find something that MSVC doesn't. For now, we only handle 2055 // the common case of members of a dependent base class. 2056 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2057 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 2058 if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) { 2059 QualType ThisType = MD->getThisType(Context); 2060 // Since the 'this' expression is synthesized, we don't need to 2061 // perform the double-lookup check. 2062 NamedDecl *FirstQualifierInScope = 0; 2063 return Owned(CXXDependentScopeMemberExpr::Create( 2064 Context, /*This=*/0, ThisType, /*IsArrow=*/true, 2065 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), 2066 TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs)); 2067 } 2068 } 2069 2070 // Don't diagnose an empty lookup for inline assmebly. 2071 if (IsInlineAsmIdentifier) 2072 return ExprError(); 2073 2074 CorrectionCandidateCallback DefaultValidator; 2075 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2076 return ExprError(); 2077 2078 assert(!R.empty() && 2079 "DiagnoseEmptyLookup returned false but added no results"); 2080 2081 // If we found an Objective-C instance variable, let 2082 // LookupInObjCMethod build the appropriate expression to 2083 // reference the ivar. 2084 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2085 R.clear(); 2086 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2087 // In a hopelessly buggy code, Objective-C instance variable 2088 // lookup fails and no expression will be built to reference it. 2089 if (!E.isInvalid() && !E.get()) 2090 return ExprError(); 2091 return E; 2092 } 2093 } 2094 } 2095 2096 // This is guaranteed from this point on. 2097 assert(!R.empty() || ADL); 2098 2099 // Check whether this might be a C++ implicit instance member access. 2100 // C++ [class.mfct.non-static]p3: 2101 // When an id-expression that is not part of a class member access 2102 // syntax and not used to form a pointer to member is used in the 2103 // body of a non-static member function of class X, if name lookup 2104 // resolves the name in the id-expression to a non-static non-type 2105 // member of some class C, the id-expression is transformed into a 2106 // class member access expression using (*this) as the 2107 // postfix-expression to the left of the . operator. 2108 // 2109 // But we don't actually need to do this for '&' operands if R 2110 // resolved to a function or overloaded function set, because the 2111 // expression is ill-formed if it actually works out to be a 2112 // non-static member function: 2113 // 2114 // C++ [expr.ref]p4: 2115 // Otherwise, if E1.E2 refers to a non-static member function. . . 2116 // [t]he expression can be used only as the left-hand operand of a 2117 // member function call. 2118 // 2119 // There are other safeguards against such uses, but it's important 2120 // to get this right here so that we don't end up making a 2121 // spuriously dependent expression if we're inside a dependent 2122 // instance method. 2123 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2124 bool MightBeImplicitMember; 2125 if (!IsAddressOfOperand) 2126 MightBeImplicitMember = true; 2127 else if (!SS.isEmpty()) 2128 MightBeImplicitMember = false; 2129 else if (R.isOverloadedResult()) 2130 MightBeImplicitMember = false; 2131 else if (R.isUnresolvableResult()) 2132 MightBeImplicitMember = true; 2133 else 2134 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2135 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2136 isa<MSPropertyDecl>(R.getFoundDecl()); 2137 2138 if (MightBeImplicitMember) 2139 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2140 R, TemplateArgs); 2141 } 2142 2143 if (TemplateArgs || TemplateKWLoc.isValid()) { 2144 2145 // In C++1y, if this is a variable template id, then check it 2146 // in BuildTemplateIdExpr(). 2147 // The single lookup result must be a variable template declaration. 2148 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2149 Id.TemplateId->Kind == TNK_Var_template) { 2150 assert(R.getAsSingle<VarTemplateDecl>() && 2151 "There should only be one declaration found."); 2152 } 2153 2154 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2155 } 2156 2157 return BuildDeclarationNameExpr(SS, R, ADL); 2158 } 2159 2160 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2161 /// declaration name, generally during template instantiation. 2162 /// There's a large number of things which don't need to be done along 2163 /// this path. 2164 ExprResult 2165 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2166 const DeclarationNameInfo &NameInfo, 2167 bool IsAddressOfOperand) { 2168 DeclContext *DC = computeDeclContext(SS, false); 2169 if (!DC) 2170 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2171 NameInfo, /*TemplateArgs=*/0); 2172 2173 if (RequireCompleteDeclContext(SS, DC)) 2174 return ExprError(); 2175 2176 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2177 LookupQualifiedName(R, DC); 2178 2179 if (R.isAmbiguous()) 2180 return ExprError(); 2181 2182 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2183 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2184 NameInfo, /*TemplateArgs=*/0); 2185 2186 if (R.empty()) { 2187 Diag(NameInfo.getLoc(), diag::err_no_member) 2188 << NameInfo.getName() << DC << SS.getRange(); 2189 return ExprError(); 2190 } 2191 2192 // Defend against this resolving to an implicit member access. We usually 2193 // won't get here if this might be a legitimate a class member (we end up in 2194 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2195 // a pointer-to-member or in an unevaluated context in C++11. 2196 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2197 return BuildPossibleImplicitMemberExpr(SS, 2198 /*TemplateKWLoc=*/SourceLocation(), 2199 R, /*TemplateArgs=*/0); 2200 2201 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2202 } 2203 2204 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2205 /// detected that we're currently inside an ObjC method. Perform some 2206 /// additional lookup. 2207 /// 2208 /// Ideally, most of this would be done by lookup, but there's 2209 /// actually quite a lot of extra work involved. 2210 /// 2211 /// Returns a null sentinel to indicate trivial success. 2212 ExprResult 2213 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2214 IdentifierInfo *II, bool AllowBuiltinCreation) { 2215 SourceLocation Loc = Lookup.getNameLoc(); 2216 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2217 2218 // Check for error condition which is already reported. 2219 if (!CurMethod) 2220 return ExprError(); 2221 2222 // There are two cases to handle here. 1) scoped lookup could have failed, 2223 // in which case we should look for an ivar. 2) scoped lookup could have 2224 // found a decl, but that decl is outside the current instance method (i.e. 2225 // a global variable). In these two cases, we do a lookup for an ivar with 2226 // this name, if the lookup sucedes, we replace it our current decl. 2227 2228 // If we're in a class method, we don't normally want to look for 2229 // ivars. But if we don't find anything else, and there's an 2230 // ivar, that's an error. 2231 bool IsClassMethod = CurMethod->isClassMethod(); 2232 2233 bool LookForIvars; 2234 if (Lookup.empty()) 2235 LookForIvars = true; 2236 else if (IsClassMethod) 2237 LookForIvars = false; 2238 else 2239 LookForIvars = (Lookup.isSingleResult() && 2240 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2241 ObjCInterfaceDecl *IFace = 0; 2242 if (LookForIvars) { 2243 IFace = CurMethod->getClassInterface(); 2244 ObjCInterfaceDecl *ClassDeclared; 2245 ObjCIvarDecl *IV = 0; 2246 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2247 // Diagnose using an ivar in a class method. 2248 if (IsClassMethod) 2249 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2250 << IV->getDeclName()); 2251 2252 // If we're referencing an invalid decl, just return this as a silent 2253 // error node. The error diagnostic was already emitted on the decl. 2254 if (IV->isInvalidDecl()) 2255 return ExprError(); 2256 2257 // Check if referencing a field with __attribute__((deprecated)). 2258 if (DiagnoseUseOfDecl(IV, Loc)) 2259 return ExprError(); 2260 2261 // Diagnose the use of an ivar outside of the declaring class. 2262 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2263 !declaresSameEntity(ClassDeclared, IFace) && 2264 !getLangOpts().DebuggerSupport) 2265 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2266 2267 // FIXME: This should use a new expr for a direct reference, don't 2268 // turn this into Self->ivar, just return a BareIVarExpr or something. 2269 IdentifierInfo &II = Context.Idents.get("self"); 2270 UnqualifiedId SelfName; 2271 SelfName.setIdentifier(&II, SourceLocation()); 2272 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2273 CXXScopeSpec SelfScopeSpec; 2274 SourceLocation TemplateKWLoc; 2275 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2276 SelfName, false, false); 2277 if (SelfExpr.isInvalid()) 2278 return ExprError(); 2279 2280 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2281 if (SelfExpr.isInvalid()) 2282 return ExprError(); 2283 2284 MarkAnyDeclReferenced(Loc, IV, true); 2285 2286 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2287 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2288 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2289 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2290 2291 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2292 Loc, IV->getLocation(), 2293 SelfExpr.take(), 2294 true, true); 2295 2296 if (getLangOpts().ObjCAutoRefCount) { 2297 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2298 DiagnosticsEngine::Level Level = 2299 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2300 if (Level != DiagnosticsEngine::Ignored) 2301 recordUseOfEvaluatedWeak(Result); 2302 } 2303 if (CurContext->isClosure()) 2304 Diag(Loc, diag::warn_implicitly_retains_self) 2305 << FixItHint::CreateInsertion(Loc, "self->"); 2306 } 2307 2308 return Owned(Result); 2309 } 2310 } else if (CurMethod->isInstanceMethod()) { 2311 // We should warn if a local variable hides an ivar. 2312 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2313 ObjCInterfaceDecl *ClassDeclared; 2314 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2315 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2316 declaresSameEntity(IFace, ClassDeclared)) 2317 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2318 } 2319 } 2320 } else if (Lookup.isSingleResult() && 2321 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2322 // If accessing a stand-alone ivar in a class method, this is an error. 2323 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2324 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2325 << IV->getDeclName()); 2326 } 2327 2328 if (Lookup.empty() && II && AllowBuiltinCreation) { 2329 // FIXME. Consolidate this with similar code in LookupName. 2330 if (unsigned BuiltinID = II->getBuiltinID()) { 2331 if (!(getLangOpts().CPlusPlus && 2332 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2333 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2334 S, Lookup.isForRedeclaration(), 2335 Lookup.getNameLoc()); 2336 if (D) Lookup.addDecl(D); 2337 } 2338 } 2339 } 2340 // Sentinel value saying that we didn't do anything special. 2341 return Owned((Expr*) 0); 2342 } 2343 2344 /// \brief Cast a base object to a member's actual type. 2345 /// 2346 /// Logically this happens in three phases: 2347 /// 2348 /// * First we cast from the base type to the naming class. 2349 /// The naming class is the class into which we were looking 2350 /// when we found the member; it's the qualifier type if a 2351 /// qualifier was provided, and otherwise it's the base type. 2352 /// 2353 /// * Next we cast from the naming class to the declaring class. 2354 /// If the member we found was brought into a class's scope by 2355 /// a using declaration, this is that class; otherwise it's 2356 /// the class declaring the member. 2357 /// 2358 /// * Finally we cast from the declaring class to the "true" 2359 /// declaring class of the member. This conversion does not 2360 /// obey access control. 2361 ExprResult 2362 Sema::PerformObjectMemberConversion(Expr *From, 2363 NestedNameSpecifier *Qualifier, 2364 NamedDecl *FoundDecl, 2365 NamedDecl *Member) { 2366 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2367 if (!RD) 2368 return Owned(From); 2369 2370 QualType DestRecordType; 2371 QualType DestType; 2372 QualType FromRecordType; 2373 QualType FromType = From->getType(); 2374 bool PointerConversions = false; 2375 if (isa<FieldDecl>(Member)) { 2376 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2377 2378 if (FromType->getAs<PointerType>()) { 2379 DestType = Context.getPointerType(DestRecordType); 2380 FromRecordType = FromType->getPointeeType(); 2381 PointerConversions = true; 2382 } else { 2383 DestType = DestRecordType; 2384 FromRecordType = FromType; 2385 } 2386 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2387 if (Method->isStatic()) 2388 return Owned(From); 2389 2390 DestType = Method->getThisType(Context); 2391 DestRecordType = DestType->getPointeeType(); 2392 2393 if (FromType->getAs<PointerType>()) { 2394 FromRecordType = FromType->getPointeeType(); 2395 PointerConversions = true; 2396 } else { 2397 FromRecordType = FromType; 2398 DestType = DestRecordType; 2399 } 2400 } else { 2401 // No conversion necessary. 2402 return Owned(From); 2403 } 2404 2405 if (DestType->isDependentType() || FromType->isDependentType()) 2406 return Owned(From); 2407 2408 // If the unqualified types are the same, no conversion is necessary. 2409 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2410 return Owned(From); 2411 2412 SourceRange FromRange = From->getSourceRange(); 2413 SourceLocation FromLoc = FromRange.getBegin(); 2414 2415 ExprValueKind VK = From->getValueKind(); 2416 2417 // C++ [class.member.lookup]p8: 2418 // [...] Ambiguities can often be resolved by qualifying a name with its 2419 // class name. 2420 // 2421 // If the member was a qualified name and the qualified referred to a 2422 // specific base subobject type, we'll cast to that intermediate type 2423 // first and then to the object in which the member is declared. That allows 2424 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2425 // 2426 // class Base { public: int x; }; 2427 // class Derived1 : public Base { }; 2428 // class Derived2 : public Base { }; 2429 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2430 // 2431 // void VeryDerived::f() { 2432 // x = 17; // error: ambiguous base subobjects 2433 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2434 // } 2435 if (Qualifier && Qualifier->getAsType()) { 2436 QualType QType = QualType(Qualifier->getAsType(), 0); 2437 assert(QType->isRecordType() && "lookup done with non-record type"); 2438 2439 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2440 2441 // In C++98, the qualifier type doesn't actually have to be a base 2442 // type of the object type, in which case we just ignore it. 2443 // Otherwise build the appropriate casts. 2444 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2445 CXXCastPath BasePath; 2446 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2447 FromLoc, FromRange, &BasePath)) 2448 return ExprError(); 2449 2450 if (PointerConversions) 2451 QType = Context.getPointerType(QType); 2452 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2453 VK, &BasePath).take(); 2454 2455 FromType = QType; 2456 FromRecordType = QRecordType; 2457 2458 // If the qualifier type was the same as the destination type, 2459 // we're done. 2460 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2461 return Owned(From); 2462 } 2463 } 2464 2465 bool IgnoreAccess = false; 2466 2467 // If we actually found the member through a using declaration, cast 2468 // down to the using declaration's type. 2469 // 2470 // Pointer equality is fine here because only one declaration of a 2471 // class ever has member declarations. 2472 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2473 assert(isa<UsingShadowDecl>(FoundDecl)); 2474 QualType URecordType = Context.getTypeDeclType( 2475 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2476 2477 // We only need to do this if the naming-class to declaring-class 2478 // conversion is non-trivial. 2479 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2480 assert(IsDerivedFrom(FromRecordType, URecordType)); 2481 CXXCastPath BasePath; 2482 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2483 FromLoc, FromRange, &BasePath)) 2484 return ExprError(); 2485 2486 QualType UType = URecordType; 2487 if (PointerConversions) 2488 UType = Context.getPointerType(UType); 2489 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2490 VK, &BasePath).take(); 2491 FromType = UType; 2492 FromRecordType = URecordType; 2493 } 2494 2495 // We don't do access control for the conversion from the 2496 // declaring class to the true declaring class. 2497 IgnoreAccess = true; 2498 } 2499 2500 CXXCastPath BasePath; 2501 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2502 FromLoc, FromRange, &BasePath, 2503 IgnoreAccess)) 2504 return ExprError(); 2505 2506 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2507 VK, &BasePath); 2508 } 2509 2510 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2511 const LookupResult &R, 2512 bool HasTrailingLParen) { 2513 // Only when used directly as the postfix-expression of a call. 2514 if (!HasTrailingLParen) 2515 return false; 2516 2517 // Never if a scope specifier was provided. 2518 if (SS.isSet()) 2519 return false; 2520 2521 // Only in C++ or ObjC++. 2522 if (!getLangOpts().CPlusPlus) 2523 return false; 2524 2525 // Turn off ADL when we find certain kinds of declarations during 2526 // normal lookup: 2527 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2528 NamedDecl *D = *I; 2529 2530 // C++0x [basic.lookup.argdep]p3: 2531 // -- a declaration of a class member 2532 // Since using decls preserve this property, we check this on the 2533 // original decl. 2534 if (D->isCXXClassMember()) 2535 return false; 2536 2537 // C++0x [basic.lookup.argdep]p3: 2538 // -- a block-scope function declaration that is not a 2539 // using-declaration 2540 // NOTE: we also trigger this for function templates (in fact, we 2541 // don't check the decl type at all, since all other decl types 2542 // turn off ADL anyway). 2543 if (isa<UsingShadowDecl>(D)) 2544 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2545 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2546 return false; 2547 2548 // C++0x [basic.lookup.argdep]p3: 2549 // -- a declaration that is neither a function or a function 2550 // template 2551 // And also for builtin functions. 2552 if (isa<FunctionDecl>(D)) { 2553 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2554 2555 // But also builtin functions. 2556 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2557 return false; 2558 } else if (!isa<FunctionTemplateDecl>(D)) 2559 return false; 2560 } 2561 2562 return true; 2563 } 2564 2565 2566 /// Diagnoses obvious problems with the use of the given declaration 2567 /// as an expression. This is only actually called for lookups that 2568 /// were not overloaded, and it doesn't promise that the declaration 2569 /// will in fact be used. 2570 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2571 if (isa<TypedefNameDecl>(D)) { 2572 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2573 return true; 2574 } 2575 2576 if (isa<ObjCInterfaceDecl>(D)) { 2577 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2578 return true; 2579 } 2580 2581 if (isa<NamespaceDecl>(D)) { 2582 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2583 return true; 2584 } 2585 2586 return false; 2587 } 2588 2589 ExprResult 2590 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2591 LookupResult &R, 2592 bool NeedsADL) { 2593 // If this is a single, fully-resolved result and we don't need ADL, 2594 // just build an ordinary singleton decl ref. 2595 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2596 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2597 R.getRepresentativeDecl()); 2598 2599 // We only need to check the declaration if there's exactly one 2600 // result, because in the overloaded case the results can only be 2601 // functions and function templates. 2602 if (R.isSingleResult() && 2603 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2604 return ExprError(); 2605 2606 // Otherwise, just build an unresolved lookup expression. Suppress 2607 // any lookup-related diagnostics; we'll hash these out later, when 2608 // we've picked a target. 2609 R.suppressDiagnostics(); 2610 2611 UnresolvedLookupExpr *ULE 2612 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2613 SS.getWithLocInContext(Context), 2614 R.getLookupNameInfo(), 2615 NeedsADL, R.isOverloadedResult(), 2616 R.begin(), R.end()); 2617 2618 return Owned(ULE); 2619 } 2620 2621 /// \brief Complete semantic analysis for a reference to the given declaration. 2622 ExprResult Sema::BuildDeclarationNameExpr( 2623 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2624 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2625 assert(D && "Cannot refer to a NULL declaration"); 2626 assert(!isa<FunctionTemplateDecl>(D) && 2627 "Cannot refer unambiguously to a function template"); 2628 2629 SourceLocation Loc = NameInfo.getLoc(); 2630 if (CheckDeclInExpr(*this, Loc, D)) 2631 return ExprError(); 2632 2633 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2634 // Specifically diagnose references to class templates that are missing 2635 // a template argument list. 2636 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2637 << Template << SS.getRange(); 2638 Diag(Template->getLocation(), diag::note_template_decl_here); 2639 return ExprError(); 2640 } 2641 2642 // Make sure that we're referring to a value. 2643 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2644 if (!VD) { 2645 Diag(Loc, diag::err_ref_non_value) 2646 << D << SS.getRange(); 2647 Diag(D->getLocation(), diag::note_declared_at); 2648 return ExprError(); 2649 } 2650 2651 // Check whether this declaration can be used. Note that we suppress 2652 // this check when we're going to perform argument-dependent lookup 2653 // on this function name, because this might not be the function 2654 // that overload resolution actually selects. 2655 if (DiagnoseUseOfDecl(VD, Loc)) 2656 return ExprError(); 2657 2658 // Only create DeclRefExpr's for valid Decl's. 2659 if (VD->isInvalidDecl()) 2660 return ExprError(); 2661 2662 // Handle members of anonymous structs and unions. If we got here, 2663 // and the reference is to a class member indirect field, then this 2664 // must be the subject of a pointer-to-member expression. 2665 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2666 if (!indirectField->isCXXClassMember()) 2667 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2668 indirectField); 2669 2670 { 2671 QualType type = VD->getType(); 2672 ExprValueKind valueKind = VK_RValue; 2673 2674 switch (D->getKind()) { 2675 // Ignore all the non-ValueDecl kinds. 2676 #define ABSTRACT_DECL(kind) 2677 #define VALUE(type, base) 2678 #define DECL(type, base) \ 2679 case Decl::type: 2680 #include "clang/AST/DeclNodes.inc" 2681 llvm_unreachable("invalid value decl kind"); 2682 2683 // These shouldn't make it here. 2684 case Decl::ObjCAtDefsField: 2685 case Decl::ObjCIvar: 2686 llvm_unreachable("forming non-member reference to ivar?"); 2687 2688 // Enum constants are always r-values and never references. 2689 // Unresolved using declarations are dependent. 2690 case Decl::EnumConstant: 2691 case Decl::UnresolvedUsingValue: 2692 valueKind = VK_RValue; 2693 break; 2694 2695 // Fields and indirect fields that got here must be for 2696 // pointer-to-member expressions; we just call them l-values for 2697 // internal consistency, because this subexpression doesn't really 2698 // exist in the high-level semantics. 2699 case Decl::Field: 2700 case Decl::IndirectField: 2701 assert(getLangOpts().CPlusPlus && 2702 "building reference to field in C?"); 2703 2704 // These can't have reference type in well-formed programs, but 2705 // for internal consistency we do this anyway. 2706 type = type.getNonReferenceType(); 2707 valueKind = VK_LValue; 2708 break; 2709 2710 // Non-type template parameters are either l-values or r-values 2711 // depending on the type. 2712 case Decl::NonTypeTemplateParm: { 2713 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2714 type = reftype->getPointeeType(); 2715 valueKind = VK_LValue; // even if the parameter is an r-value reference 2716 break; 2717 } 2718 2719 // For non-references, we need to strip qualifiers just in case 2720 // the template parameter was declared as 'const int' or whatever. 2721 valueKind = VK_RValue; 2722 type = type.getUnqualifiedType(); 2723 break; 2724 } 2725 2726 case Decl::Var: 2727 case Decl::VarTemplateSpecialization: 2728 case Decl::VarTemplatePartialSpecialization: 2729 // In C, "extern void blah;" is valid and is an r-value. 2730 if (!getLangOpts().CPlusPlus && 2731 !type.hasQualifiers() && 2732 type->isVoidType()) { 2733 valueKind = VK_RValue; 2734 break; 2735 } 2736 // fallthrough 2737 2738 case Decl::ImplicitParam: 2739 case Decl::ParmVar: { 2740 // These are always l-values. 2741 valueKind = VK_LValue; 2742 type = type.getNonReferenceType(); 2743 2744 // FIXME: Does the addition of const really only apply in 2745 // potentially-evaluated contexts? Since the variable isn't actually 2746 // captured in an unevaluated context, it seems that the answer is no. 2747 if (!isUnevaluatedContext()) { 2748 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2749 if (!CapturedType.isNull()) 2750 type = CapturedType; 2751 } 2752 2753 break; 2754 } 2755 2756 case Decl::Function: { 2757 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2758 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2759 type = Context.BuiltinFnTy; 2760 valueKind = VK_RValue; 2761 break; 2762 } 2763 } 2764 2765 const FunctionType *fty = type->castAs<FunctionType>(); 2766 2767 // If we're referring to a function with an __unknown_anytype 2768 // result type, make the entire expression __unknown_anytype. 2769 if (fty->getReturnType() == Context.UnknownAnyTy) { 2770 type = Context.UnknownAnyTy; 2771 valueKind = VK_RValue; 2772 break; 2773 } 2774 2775 // Functions are l-values in C++. 2776 if (getLangOpts().CPlusPlus) { 2777 valueKind = VK_LValue; 2778 break; 2779 } 2780 2781 // C99 DR 316 says that, if a function type comes from a 2782 // function definition (without a prototype), that type is only 2783 // used for checking compatibility. Therefore, when referencing 2784 // the function, we pretend that we don't have the full function 2785 // type. 2786 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2787 isa<FunctionProtoType>(fty)) 2788 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2789 fty->getExtInfo()); 2790 2791 // Functions are r-values in C. 2792 valueKind = VK_RValue; 2793 break; 2794 } 2795 2796 case Decl::MSProperty: 2797 valueKind = VK_LValue; 2798 break; 2799 2800 case Decl::CXXMethod: 2801 // If we're referring to a method with an __unknown_anytype 2802 // result type, make the entire expression __unknown_anytype. 2803 // This should only be possible with a type written directly. 2804 if (const FunctionProtoType *proto 2805 = dyn_cast<FunctionProtoType>(VD->getType())) 2806 if (proto->getReturnType() == Context.UnknownAnyTy) { 2807 type = Context.UnknownAnyTy; 2808 valueKind = VK_RValue; 2809 break; 2810 } 2811 2812 // C++ methods are l-values if static, r-values if non-static. 2813 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2814 valueKind = VK_LValue; 2815 break; 2816 } 2817 // fallthrough 2818 2819 case Decl::CXXConversion: 2820 case Decl::CXXDestructor: 2821 case Decl::CXXConstructor: 2822 valueKind = VK_RValue; 2823 break; 2824 } 2825 2826 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2827 TemplateArgs); 2828 } 2829 } 2830 2831 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2832 PredefinedExpr::IdentType IT) { 2833 // Pick the current block, lambda, captured statement or function. 2834 Decl *currentDecl = 0; 2835 if (const BlockScopeInfo *BSI = getCurBlock()) 2836 currentDecl = BSI->TheDecl; 2837 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2838 currentDecl = LSI->CallOperator; 2839 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2840 currentDecl = CSI->TheCapturedDecl; 2841 else 2842 currentDecl = getCurFunctionOrMethodDecl(); 2843 2844 if (!currentDecl) { 2845 Diag(Loc, diag::ext_predef_outside_function); 2846 currentDecl = Context.getTranslationUnitDecl(); 2847 } 2848 2849 QualType ResTy; 2850 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2851 ResTy = Context.DependentTy; 2852 else { 2853 // Pre-defined identifiers are of type char[x], where x is the length of 2854 // the string. 2855 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2856 2857 llvm::APInt LengthI(32, Length + 1); 2858 if (IT == PredefinedExpr::LFunction) 2859 ResTy = Context.WideCharTy.withConst(); 2860 else 2861 ResTy = Context.CharTy.withConst(); 2862 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2863 } 2864 2865 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2866 } 2867 2868 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2869 PredefinedExpr::IdentType IT; 2870 2871 switch (Kind) { 2872 default: llvm_unreachable("Unknown simple primary expr!"); 2873 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2874 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2875 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 2876 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 2877 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2878 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2879 } 2880 2881 return BuildPredefinedExpr(Loc, IT); 2882 } 2883 2884 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2885 SmallString<16> CharBuffer; 2886 bool Invalid = false; 2887 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2888 if (Invalid) 2889 return ExprError(); 2890 2891 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2892 PP, Tok.getKind()); 2893 if (Literal.hadError()) 2894 return ExprError(); 2895 2896 QualType Ty; 2897 if (Literal.isWide()) 2898 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2899 else if (Literal.isUTF16()) 2900 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2901 else if (Literal.isUTF32()) 2902 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2903 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2904 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2905 else 2906 Ty = Context.CharTy; // 'x' -> char in C++ 2907 2908 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2909 if (Literal.isWide()) 2910 Kind = CharacterLiteral::Wide; 2911 else if (Literal.isUTF16()) 2912 Kind = CharacterLiteral::UTF16; 2913 else if (Literal.isUTF32()) 2914 Kind = CharacterLiteral::UTF32; 2915 2916 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2917 Tok.getLocation()); 2918 2919 if (Literal.getUDSuffix().empty()) 2920 return Owned(Lit); 2921 2922 // We're building a user-defined literal. 2923 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2924 SourceLocation UDSuffixLoc = 2925 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2926 2927 // Make sure we're allowed user-defined literals here. 2928 if (!UDLScope) 2929 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2930 2931 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2932 // operator "" X (ch) 2933 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2934 Lit, Tok.getLocation()); 2935 } 2936 2937 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2938 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2939 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2940 Context.IntTy, Loc)); 2941 } 2942 2943 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2944 QualType Ty, SourceLocation Loc) { 2945 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2946 2947 using llvm::APFloat; 2948 APFloat Val(Format); 2949 2950 APFloat::opStatus result = Literal.GetFloatValue(Val); 2951 2952 // Overflow is always an error, but underflow is only an error if 2953 // we underflowed to zero (APFloat reports denormals as underflow). 2954 if ((result & APFloat::opOverflow) || 2955 ((result & APFloat::opUnderflow) && Val.isZero())) { 2956 unsigned diagnostic; 2957 SmallString<20> buffer; 2958 if (result & APFloat::opOverflow) { 2959 diagnostic = diag::warn_float_overflow; 2960 APFloat::getLargest(Format).toString(buffer); 2961 } else { 2962 diagnostic = diag::warn_float_underflow; 2963 APFloat::getSmallest(Format).toString(buffer); 2964 } 2965 2966 S.Diag(Loc, diagnostic) 2967 << Ty 2968 << StringRef(buffer.data(), buffer.size()); 2969 } 2970 2971 bool isExact = (result == APFloat::opOK); 2972 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2973 } 2974 2975 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2976 // Fast path for a single digit (which is quite common). A single digit 2977 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2978 if (Tok.getLength() == 1) { 2979 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2980 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2981 } 2982 2983 SmallString<128> SpellingBuffer; 2984 // NumericLiteralParser wants to overread by one character. Add padding to 2985 // the buffer in case the token is copied to the buffer. If getSpelling() 2986 // returns a StringRef to the memory buffer, it should have a null char at 2987 // the EOF, so it is also safe. 2988 SpellingBuffer.resize(Tok.getLength() + 1); 2989 2990 // Get the spelling of the token, which eliminates trigraphs, etc. 2991 bool Invalid = false; 2992 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2993 if (Invalid) 2994 return ExprError(); 2995 2996 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2997 if (Literal.hadError) 2998 return ExprError(); 2999 3000 if (Literal.hasUDSuffix()) { 3001 // We're building a user-defined literal. 3002 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3003 SourceLocation UDSuffixLoc = 3004 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3005 3006 // Make sure we're allowed user-defined literals here. 3007 if (!UDLScope) 3008 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3009 3010 QualType CookedTy; 3011 if (Literal.isFloatingLiteral()) { 3012 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3013 // long double, the literal is treated as a call of the form 3014 // operator "" X (f L) 3015 CookedTy = Context.LongDoubleTy; 3016 } else { 3017 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3018 // unsigned long long, the literal is treated as a call of the form 3019 // operator "" X (n ULL) 3020 CookedTy = Context.UnsignedLongLongTy; 3021 } 3022 3023 DeclarationName OpName = 3024 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3025 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3026 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3027 3028 SourceLocation TokLoc = Tok.getLocation(); 3029 3030 // Perform literal operator lookup to determine if we're building a raw 3031 // literal or a cooked one. 3032 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3033 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3034 /*AllowRaw*/true, /*AllowTemplate*/true, 3035 /*AllowStringTemplate*/false)) { 3036 case LOLR_Error: 3037 return ExprError(); 3038 3039 case LOLR_Cooked: { 3040 Expr *Lit; 3041 if (Literal.isFloatingLiteral()) { 3042 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3043 } else { 3044 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3045 if (Literal.GetIntegerValue(ResultVal)) 3046 Diag(Tok.getLocation(), diag::err_integer_too_large); 3047 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3048 Tok.getLocation()); 3049 } 3050 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3051 } 3052 3053 case LOLR_Raw: { 3054 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3055 // literal is treated as a call of the form 3056 // operator "" X ("n") 3057 unsigned Length = Literal.getUDSuffixOffset(); 3058 QualType StrTy = Context.getConstantArrayType( 3059 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3060 ArrayType::Normal, 0); 3061 Expr *Lit = StringLiteral::Create( 3062 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3063 /*Pascal*/false, StrTy, &TokLoc, 1); 3064 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3065 } 3066 3067 case LOLR_Template: { 3068 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3069 // template), L is treated as a call fo the form 3070 // operator "" X <'c1', 'c2', ... 'ck'>() 3071 // where n is the source character sequence c1 c2 ... ck. 3072 TemplateArgumentListInfo ExplicitArgs; 3073 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3074 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3075 llvm::APSInt Value(CharBits, CharIsUnsigned); 3076 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3077 Value = TokSpelling[I]; 3078 TemplateArgument Arg(Context, Value, Context.CharTy); 3079 TemplateArgumentLocInfo ArgInfo; 3080 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3081 } 3082 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3083 &ExplicitArgs); 3084 } 3085 case LOLR_StringTemplate: 3086 llvm_unreachable("unexpected literal operator lookup result"); 3087 } 3088 } 3089 3090 Expr *Res; 3091 3092 if (Literal.isFloatingLiteral()) { 3093 QualType Ty; 3094 if (Literal.isFloat) 3095 Ty = Context.FloatTy; 3096 else if (!Literal.isLong) 3097 Ty = Context.DoubleTy; 3098 else 3099 Ty = Context.LongDoubleTy; 3100 3101 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3102 3103 if (Ty == Context.DoubleTy) { 3104 if (getLangOpts().SinglePrecisionConstants) { 3105 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3106 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3107 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3108 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3109 } 3110 } 3111 } else if (!Literal.isIntegerLiteral()) { 3112 return ExprError(); 3113 } else { 3114 QualType Ty; 3115 3116 // 'long long' is a C99 or C++11 feature. 3117 if (!getLangOpts().C99 && Literal.isLongLong) { 3118 if (getLangOpts().CPlusPlus) 3119 Diag(Tok.getLocation(), 3120 getLangOpts().CPlusPlus11 ? 3121 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3122 else 3123 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3124 } 3125 3126 // Get the value in the widest-possible width. 3127 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3128 // The microsoft literal suffix extensions support 128-bit literals, which 3129 // may be wider than [u]intmax_t. 3130 // FIXME: Actually, they don't. We seem to have accidentally invented the 3131 // i128 suffix. 3132 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 3133 PP.getTargetInfo().hasInt128Type()) 3134 MaxWidth = 128; 3135 llvm::APInt ResultVal(MaxWidth, 0); 3136 3137 if (Literal.GetIntegerValue(ResultVal)) { 3138 // If this value didn't fit into uintmax_t, error and force to ull. 3139 Diag(Tok.getLocation(), diag::err_integer_too_large); 3140 Ty = Context.UnsignedLongLongTy; 3141 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3142 "long long is not intmax_t?"); 3143 } else { 3144 // If this value fits into a ULL, try to figure out what else it fits into 3145 // according to the rules of C99 6.4.4.1p5. 3146 3147 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3148 // be an unsigned int. 3149 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3150 3151 // Check from smallest to largest, picking the smallest type we can. 3152 unsigned Width = 0; 3153 if (!Literal.isLong && !Literal.isLongLong) { 3154 // Are int/unsigned possibilities? 3155 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3156 3157 // Does it fit in a unsigned int? 3158 if (ResultVal.isIntN(IntSize)) { 3159 // Does it fit in a signed int? 3160 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3161 Ty = Context.IntTy; 3162 else if (AllowUnsigned) 3163 Ty = Context.UnsignedIntTy; 3164 Width = IntSize; 3165 } 3166 } 3167 3168 // Are long/unsigned long possibilities? 3169 if (Ty.isNull() && !Literal.isLongLong) { 3170 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3171 3172 // Does it fit in a unsigned long? 3173 if (ResultVal.isIntN(LongSize)) { 3174 // Does it fit in a signed long? 3175 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3176 Ty = Context.LongTy; 3177 else if (AllowUnsigned) 3178 Ty = Context.UnsignedLongTy; 3179 Width = LongSize; 3180 } 3181 } 3182 3183 // Check long long if needed. 3184 if (Ty.isNull()) { 3185 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3186 3187 // Does it fit in a unsigned long long? 3188 if (ResultVal.isIntN(LongLongSize)) { 3189 // Does it fit in a signed long long? 3190 // To be compatible with MSVC, hex integer literals ending with the 3191 // LL or i64 suffix are always signed in Microsoft mode. 3192 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3193 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3194 Ty = Context.LongLongTy; 3195 else if (AllowUnsigned) 3196 Ty = Context.UnsignedLongLongTy; 3197 Width = LongLongSize; 3198 } 3199 } 3200 3201 // If it doesn't fit in unsigned long long, and we're using Microsoft 3202 // extensions, then its a 128-bit integer literal. 3203 if (Ty.isNull() && Literal.isMicrosoftInteger && 3204 PP.getTargetInfo().hasInt128Type()) { 3205 if (Literal.isUnsigned) 3206 Ty = Context.UnsignedInt128Ty; 3207 else 3208 Ty = Context.Int128Ty; 3209 Width = 128; 3210 } 3211 3212 // If we still couldn't decide a type, we probably have something that 3213 // does not fit in a signed long long, but has no U suffix. 3214 if (Ty.isNull()) { 3215 Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed); 3216 Ty = Context.UnsignedLongLongTy; 3217 Width = Context.getTargetInfo().getLongLongWidth(); 3218 } 3219 3220 if (ResultVal.getBitWidth() != Width) 3221 ResultVal = ResultVal.trunc(Width); 3222 } 3223 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3224 } 3225 3226 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3227 if (Literal.isImaginary) 3228 Res = new (Context) ImaginaryLiteral(Res, 3229 Context.getComplexType(Res->getType())); 3230 3231 return Owned(Res); 3232 } 3233 3234 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3235 assert((E != 0) && "ActOnParenExpr() missing expr"); 3236 return Owned(new (Context) ParenExpr(L, R, E)); 3237 } 3238 3239 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3240 SourceLocation Loc, 3241 SourceRange ArgRange) { 3242 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3243 // scalar or vector data type argument..." 3244 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3245 // type (C99 6.2.5p18) or void. 3246 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3247 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3248 << T << ArgRange; 3249 return true; 3250 } 3251 3252 assert((T->isVoidType() || !T->isIncompleteType()) && 3253 "Scalar types should always be complete"); 3254 return false; 3255 } 3256 3257 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3258 SourceLocation Loc, 3259 SourceRange ArgRange, 3260 UnaryExprOrTypeTrait TraitKind) { 3261 // Invalid types must be hard errors for SFINAE in C++. 3262 if (S.LangOpts.CPlusPlus) 3263 return true; 3264 3265 // C99 6.5.3.4p1: 3266 if (T->isFunctionType() && 3267 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3268 // sizeof(function)/alignof(function) is allowed as an extension. 3269 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3270 << TraitKind << ArgRange; 3271 return false; 3272 } 3273 3274 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3275 // this is an error (OpenCL v1.1 s6.3.k) 3276 if (T->isVoidType()) { 3277 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3278 : diag::ext_sizeof_alignof_void_type; 3279 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3280 return false; 3281 } 3282 3283 return true; 3284 } 3285 3286 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3287 SourceLocation Loc, 3288 SourceRange ArgRange, 3289 UnaryExprOrTypeTrait TraitKind) { 3290 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3291 // runtime doesn't allow it. 3292 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3293 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3294 << T << (TraitKind == UETT_SizeOf) 3295 << ArgRange; 3296 return true; 3297 } 3298 3299 return false; 3300 } 3301 3302 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3303 /// pointer type is equal to T) and emit a warning if it is. 3304 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3305 Expr *E) { 3306 // Don't warn if the operation changed the type. 3307 if (T != E->getType()) 3308 return; 3309 3310 // Now look for array decays. 3311 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3312 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3313 return; 3314 3315 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3316 << ICE->getType() 3317 << ICE->getSubExpr()->getType(); 3318 } 3319 3320 /// \brief Check the constraints on expression operands to unary type expression 3321 /// and type traits. 3322 /// 3323 /// Completes any types necessary and validates the constraints on the operand 3324 /// expression. The logic mostly mirrors the type-based overload, but may modify 3325 /// the expression as it completes the type for that expression through template 3326 /// instantiation, etc. 3327 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3328 UnaryExprOrTypeTrait ExprKind) { 3329 QualType ExprTy = E->getType(); 3330 assert(!ExprTy->isReferenceType()); 3331 3332 if (ExprKind == UETT_VecStep) 3333 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3334 E->getSourceRange()); 3335 3336 // Whitelist some types as extensions 3337 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3338 E->getSourceRange(), ExprKind)) 3339 return false; 3340 3341 if (RequireCompleteExprType(E, 3342 diag::err_sizeof_alignof_incomplete_type, 3343 ExprKind, E->getSourceRange())) 3344 return true; 3345 3346 // Completing the expression's type may have changed it. 3347 ExprTy = E->getType(); 3348 assert(!ExprTy->isReferenceType()); 3349 3350 if (ExprTy->isFunctionType()) { 3351 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3352 << ExprKind << E->getSourceRange(); 3353 return true; 3354 } 3355 3356 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3357 E->getSourceRange(), ExprKind)) 3358 return true; 3359 3360 if (ExprKind == UETT_SizeOf) { 3361 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3362 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3363 QualType OType = PVD->getOriginalType(); 3364 QualType Type = PVD->getType(); 3365 if (Type->isPointerType() && OType->isArrayType()) { 3366 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3367 << Type << OType; 3368 Diag(PVD->getLocation(), diag::note_declared_at); 3369 } 3370 } 3371 } 3372 3373 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3374 // decays into a pointer and returns an unintended result. This is most 3375 // likely a typo for "sizeof(array) op x". 3376 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3377 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3378 BO->getLHS()); 3379 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3380 BO->getRHS()); 3381 } 3382 } 3383 3384 return false; 3385 } 3386 3387 /// \brief Check the constraints on operands to unary expression and type 3388 /// traits. 3389 /// 3390 /// This will complete any types necessary, and validate the various constraints 3391 /// on those operands. 3392 /// 3393 /// The UsualUnaryConversions() function is *not* called by this routine. 3394 /// C99 6.3.2.1p[2-4] all state: 3395 /// Except when it is the operand of the sizeof operator ... 3396 /// 3397 /// C++ [expr.sizeof]p4 3398 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3399 /// standard conversions are not applied to the operand of sizeof. 3400 /// 3401 /// This policy is followed for all of the unary trait expressions. 3402 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3403 SourceLocation OpLoc, 3404 SourceRange ExprRange, 3405 UnaryExprOrTypeTrait ExprKind) { 3406 if (ExprType->isDependentType()) 3407 return false; 3408 3409 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3410 // the result is the size of the referenced type." 3411 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3412 // result shall be the alignment of the referenced type." 3413 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3414 ExprType = Ref->getPointeeType(); 3415 3416 if (ExprKind == UETT_VecStep) 3417 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3418 3419 // Whitelist some types as extensions 3420 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3421 ExprKind)) 3422 return false; 3423 3424 if (RequireCompleteType(OpLoc, ExprType, 3425 diag::err_sizeof_alignof_incomplete_type, 3426 ExprKind, ExprRange)) 3427 return true; 3428 3429 if (ExprType->isFunctionType()) { 3430 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3431 << ExprKind << ExprRange; 3432 return true; 3433 } 3434 3435 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3436 ExprKind)) 3437 return true; 3438 3439 return false; 3440 } 3441 3442 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3443 E = E->IgnoreParens(); 3444 3445 // Cannot know anything else if the expression is dependent. 3446 if (E->isTypeDependent()) 3447 return false; 3448 3449 if (E->getObjectKind() == OK_BitField) { 3450 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3451 << 1 << E->getSourceRange(); 3452 return true; 3453 } 3454 3455 ValueDecl *D = 0; 3456 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3457 D = DRE->getDecl(); 3458 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3459 D = ME->getMemberDecl(); 3460 } 3461 3462 // If it's a field, require the containing struct to have a 3463 // complete definition so that we can compute the layout. 3464 // 3465 // This requires a very particular set of circumstances. For a 3466 // field to be contained within an incomplete type, we must in the 3467 // process of parsing that type. To have an expression refer to a 3468 // field, it must be an id-expression or a member-expression, but 3469 // the latter are always ill-formed when the base type is 3470 // incomplete, including only being partially complete. An 3471 // id-expression can never refer to a field in C because fields 3472 // are not in the ordinary namespace. In C++, an id-expression 3473 // can implicitly be a member access, but only if there's an 3474 // implicit 'this' value, and all such contexts are subject to 3475 // delayed parsing --- except for trailing return types in C++11. 3476 // And if an id-expression referring to a field occurs in a 3477 // context that lacks a 'this' value, it's ill-formed --- except, 3478 // again, in C++11, where such references are allowed in an 3479 // unevaluated context. So C++11 introduces some new complexity. 3480 // 3481 // For the record, since __alignof__ on expressions is a GCC 3482 // extension, GCC seems to permit this but always gives the 3483 // nonsensical answer 0. 3484 // 3485 // We don't really need the layout here --- we could instead just 3486 // directly check for all the appropriate alignment-lowing 3487 // attributes --- but that would require duplicating a lot of 3488 // logic that just isn't worth duplicating for such a marginal 3489 // use-case. 3490 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3491 // Fast path this check, since we at least know the record has a 3492 // definition if we can find a member of it. 3493 if (!FD->getParent()->isCompleteDefinition()) { 3494 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3495 << E->getSourceRange(); 3496 return true; 3497 } 3498 3499 // Otherwise, if it's a field, and the field doesn't have 3500 // reference type, then it must have a complete type (or be a 3501 // flexible array member, which we explicitly want to 3502 // white-list anyway), which makes the following checks trivial. 3503 if (!FD->getType()->isReferenceType()) 3504 return false; 3505 } 3506 3507 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3508 } 3509 3510 bool Sema::CheckVecStepExpr(Expr *E) { 3511 E = E->IgnoreParens(); 3512 3513 // Cannot know anything else if the expression is dependent. 3514 if (E->isTypeDependent()) 3515 return false; 3516 3517 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3518 } 3519 3520 /// \brief Build a sizeof or alignof expression given a type operand. 3521 ExprResult 3522 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3523 SourceLocation OpLoc, 3524 UnaryExprOrTypeTrait ExprKind, 3525 SourceRange R) { 3526 if (!TInfo) 3527 return ExprError(); 3528 3529 QualType T = TInfo->getType(); 3530 3531 if (!T->isDependentType() && 3532 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3533 return ExprError(); 3534 3535 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3536 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3537 Context.getSizeType(), 3538 OpLoc, R.getEnd())); 3539 } 3540 3541 /// \brief Build a sizeof or alignof expression given an expression 3542 /// operand. 3543 ExprResult 3544 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3545 UnaryExprOrTypeTrait ExprKind) { 3546 ExprResult PE = CheckPlaceholderExpr(E); 3547 if (PE.isInvalid()) 3548 return ExprError(); 3549 3550 E = PE.get(); 3551 3552 // Verify that the operand is valid. 3553 bool isInvalid = false; 3554 if (E->isTypeDependent()) { 3555 // Delay type-checking for type-dependent expressions. 3556 } else if (ExprKind == UETT_AlignOf) { 3557 isInvalid = CheckAlignOfExpr(*this, E); 3558 } else if (ExprKind == UETT_VecStep) { 3559 isInvalid = CheckVecStepExpr(E); 3560 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3561 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3562 isInvalid = true; 3563 } else { 3564 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3565 } 3566 3567 if (isInvalid) 3568 return ExprError(); 3569 3570 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3571 PE = TransformToPotentiallyEvaluated(E); 3572 if (PE.isInvalid()) return ExprError(); 3573 E = PE.take(); 3574 } 3575 3576 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3577 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3578 ExprKind, E, Context.getSizeType(), OpLoc, 3579 E->getSourceRange().getEnd())); 3580 } 3581 3582 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3583 /// expr and the same for @c alignof and @c __alignof 3584 /// Note that the ArgRange is invalid if isType is false. 3585 ExprResult 3586 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3587 UnaryExprOrTypeTrait ExprKind, bool IsType, 3588 void *TyOrEx, const SourceRange &ArgRange) { 3589 // If error parsing type, ignore. 3590 if (TyOrEx == 0) return ExprError(); 3591 3592 if (IsType) { 3593 TypeSourceInfo *TInfo; 3594 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3595 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3596 } 3597 3598 Expr *ArgEx = (Expr *)TyOrEx; 3599 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3600 return Result; 3601 } 3602 3603 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3604 bool IsReal) { 3605 if (V.get()->isTypeDependent()) 3606 return S.Context.DependentTy; 3607 3608 // _Real and _Imag are only l-values for normal l-values. 3609 if (V.get()->getObjectKind() != OK_Ordinary) { 3610 V = S.DefaultLvalueConversion(V.take()); 3611 if (V.isInvalid()) 3612 return QualType(); 3613 } 3614 3615 // These operators return the element type of a complex type. 3616 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3617 return CT->getElementType(); 3618 3619 // Otherwise they pass through real integer and floating point types here. 3620 if (V.get()->getType()->isArithmeticType()) 3621 return V.get()->getType(); 3622 3623 // Test for placeholders. 3624 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3625 if (PR.isInvalid()) return QualType(); 3626 if (PR.get() != V.get()) { 3627 V = PR; 3628 return CheckRealImagOperand(S, V, Loc, IsReal); 3629 } 3630 3631 // Reject anything else. 3632 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3633 << (IsReal ? "__real" : "__imag"); 3634 return QualType(); 3635 } 3636 3637 3638 3639 ExprResult 3640 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3641 tok::TokenKind Kind, Expr *Input) { 3642 UnaryOperatorKind Opc; 3643 switch (Kind) { 3644 default: llvm_unreachable("Unknown unary op!"); 3645 case tok::plusplus: Opc = UO_PostInc; break; 3646 case tok::minusminus: Opc = UO_PostDec; break; 3647 } 3648 3649 // Since this might is a postfix expression, get rid of ParenListExprs. 3650 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3651 if (Result.isInvalid()) return ExprError(); 3652 Input = Result.take(); 3653 3654 return BuildUnaryOp(S, OpLoc, Opc, Input); 3655 } 3656 3657 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3658 /// 3659 /// \return true on error 3660 static bool checkArithmeticOnObjCPointer(Sema &S, 3661 SourceLocation opLoc, 3662 Expr *op) { 3663 assert(op->getType()->isObjCObjectPointerType()); 3664 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3665 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3666 return false; 3667 3668 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3669 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3670 << op->getSourceRange(); 3671 return true; 3672 } 3673 3674 ExprResult 3675 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3676 Expr *idx, SourceLocation rbLoc) { 3677 // Since this might be a postfix expression, get rid of ParenListExprs. 3678 if (isa<ParenListExpr>(base)) { 3679 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3680 if (result.isInvalid()) return ExprError(); 3681 base = result.take(); 3682 } 3683 3684 // Handle any non-overload placeholder types in the base and index 3685 // expressions. We can't handle overloads here because the other 3686 // operand might be an overloadable type, in which case the overload 3687 // resolution for the operator overload should get the first crack 3688 // at the overload. 3689 if (base->getType()->isNonOverloadPlaceholderType()) { 3690 ExprResult result = CheckPlaceholderExpr(base); 3691 if (result.isInvalid()) return ExprError(); 3692 base = result.take(); 3693 } 3694 if (idx->getType()->isNonOverloadPlaceholderType()) { 3695 ExprResult result = CheckPlaceholderExpr(idx); 3696 if (result.isInvalid()) return ExprError(); 3697 idx = result.take(); 3698 } 3699 3700 // Build an unanalyzed expression if either operand is type-dependent. 3701 if (getLangOpts().CPlusPlus && 3702 (base->isTypeDependent() || idx->isTypeDependent())) { 3703 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3704 Context.DependentTy, 3705 VK_LValue, OK_Ordinary, 3706 rbLoc)); 3707 } 3708 3709 // Use C++ overloaded-operator rules if either operand has record 3710 // type. The spec says to do this if either type is *overloadable*, 3711 // but enum types can't declare subscript operators or conversion 3712 // operators, so there's nothing interesting for overload resolution 3713 // to do if there aren't any record types involved. 3714 // 3715 // ObjC pointers have their own subscripting logic that is not tied 3716 // to overload resolution and so should not take this path. 3717 if (getLangOpts().CPlusPlus && 3718 (base->getType()->isRecordType() || 3719 (!base->getType()->isObjCObjectPointerType() && 3720 idx->getType()->isRecordType()))) { 3721 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3722 } 3723 3724 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3725 } 3726 3727 ExprResult 3728 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3729 Expr *Idx, SourceLocation RLoc) { 3730 Expr *LHSExp = Base; 3731 Expr *RHSExp = Idx; 3732 3733 // Perform default conversions. 3734 if (!LHSExp->getType()->getAs<VectorType>()) { 3735 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3736 if (Result.isInvalid()) 3737 return ExprError(); 3738 LHSExp = Result.take(); 3739 } 3740 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3741 if (Result.isInvalid()) 3742 return ExprError(); 3743 RHSExp = Result.take(); 3744 3745 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3746 ExprValueKind VK = VK_LValue; 3747 ExprObjectKind OK = OK_Ordinary; 3748 3749 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3750 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3751 // in the subscript position. As a result, we need to derive the array base 3752 // and index from the expression types. 3753 Expr *BaseExpr, *IndexExpr; 3754 QualType ResultType; 3755 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3756 BaseExpr = LHSExp; 3757 IndexExpr = RHSExp; 3758 ResultType = Context.DependentTy; 3759 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3760 BaseExpr = LHSExp; 3761 IndexExpr = RHSExp; 3762 ResultType = PTy->getPointeeType(); 3763 } else if (const ObjCObjectPointerType *PTy = 3764 LHSTy->getAs<ObjCObjectPointerType>()) { 3765 BaseExpr = LHSExp; 3766 IndexExpr = RHSExp; 3767 3768 // Use custom logic if this should be the pseudo-object subscript 3769 // expression. 3770 if (!LangOpts.isSubscriptPointerArithmetic()) 3771 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3772 3773 ResultType = PTy->getPointeeType(); 3774 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3775 // Handle the uncommon case of "123[Ptr]". 3776 BaseExpr = RHSExp; 3777 IndexExpr = LHSExp; 3778 ResultType = PTy->getPointeeType(); 3779 } else if (const ObjCObjectPointerType *PTy = 3780 RHSTy->getAs<ObjCObjectPointerType>()) { 3781 // Handle the uncommon case of "123[Ptr]". 3782 BaseExpr = RHSExp; 3783 IndexExpr = LHSExp; 3784 ResultType = PTy->getPointeeType(); 3785 if (!LangOpts.isSubscriptPointerArithmetic()) { 3786 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3787 << ResultType << BaseExpr->getSourceRange(); 3788 return ExprError(); 3789 } 3790 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3791 BaseExpr = LHSExp; // vectors: V[123] 3792 IndexExpr = RHSExp; 3793 VK = LHSExp->getValueKind(); 3794 if (VK != VK_RValue) 3795 OK = OK_VectorComponent; 3796 3797 // FIXME: need to deal with const... 3798 ResultType = VTy->getElementType(); 3799 } else if (LHSTy->isArrayType()) { 3800 // If we see an array that wasn't promoted by 3801 // DefaultFunctionArrayLvalueConversion, it must be an array that 3802 // wasn't promoted because of the C90 rule that doesn't 3803 // allow promoting non-lvalue arrays. Warn, then 3804 // force the promotion here. 3805 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3806 LHSExp->getSourceRange(); 3807 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3808 CK_ArrayToPointerDecay).take(); 3809 LHSTy = LHSExp->getType(); 3810 3811 BaseExpr = LHSExp; 3812 IndexExpr = RHSExp; 3813 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3814 } else if (RHSTy->isArrayType()) { 3815 // Same as previous, except for 123[f().a] case 3816 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3817 RHSExp->getSourceRange(); 3818 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3819 CK_ArrayToPointerDecay).take(); 3820 RHSTy = RHSExp->getType(); 3821 3822 BaseExpr = RHSExp; 3823 IndexExpr = LHSExp; 3824 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3825 } else { 3826 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3827 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3828 } 3829 // C99 6.5.2.1p1 3830 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3831 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3832 << IndexExpr->getSourceRange()); 3833 3834 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3835 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3836 && !IndexExpr->isTypeDependent()) 3837 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3838 3839 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3840 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3841 // type. Note that Functions are not objects, and that (in C99 parlance) 3842 // incomplete types are not object types. 3843 if (ResultType->isFunctionType()) { 3844 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3845 << ResultType << BaseExpr->getSourceRange(); 3846 return ExprError(); 3847 } 3848 3849 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3850 // GNU extension: subscripting on pointer to void 3851 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3852 << BaseExpr->getSourceRange(); 3853 3854 // C forbids expressions of unqualified void type from being l-values. 3855 // See IsCForbiddenLValueType. 3856 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3857 } else if (!ResultType->isDependentType() && 3858 RequireCompleteType(LLoc, ResultType, 3859 diag::err_subscript_incomplete_type, BaseExpr)) 3860 return ExprError(); 3861 3862 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3863 !ResultType.isCForbiddenLValueType()); 3864 3865 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3866 ResultType, VK, OK, RLoc)); 3867 } 3868 3869 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3870 FunctionDecl *FD, 3871 ParmVarDecl *Param) { 3872 if (Param->hasUnparsedDefaultArg()) { 3873 Diag(CallLoc, 3874 diag::err_use_of_default_argument_to_function_declared_later) << 3875 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3876 Diag(UnparsedDefaultArgLocs[Param], 3877 diag::note_default_argument_declared_here); 3878 return ExprError(); 3879 } 3880 3881 if (Param->hasUninstantiatedDefaultArg()) { 3882 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3883 3884 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3885 Param); 3886 3887 // Instantiate the expression. 3888 MultiLevelTemplateArgumentList MutiLevelArgList 3889 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3890 3891 InstantiatingTemplate Inst(*this, CallLoc, Param, 3892 MutiLevelArgList.getInnermost()); 3893 if (Inst.isInvalid()) 3894 return ExprError(); 3895 3896 ExprResult Result; 3897 { 3898 // C++ [dcl.fct.default]p5: 3899 // The names in the [default argument] expression are bound, and 3900 // the semantic constraints are checked, at the point where the 3901 // default argument expression appears. 3902 ContextRAII SavedContext(*this, FD); 3903 LocalInstantiationScope Local(*this); 3904 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3905 } 3906 if (Result.isInvalid()) 3907 return ExprError(); 3908 3909 // Check the expression as an initializer for the parameter. 3910 InitializedEntity Entity 3911 = InitializedEntity::InitializeParameter(Context, Param); 3912 InitializationKind Kind 3913 = InitializationKind::CreateCopy(Param->getLocation(), 3914 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3915 Expr *ResultE = Result.takeAs<Expr>(); 3916 3917 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3918 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3919 if (Result.isInvalid()) 3920 return ExprError(); 3921 3922 Expr *Arg = Result.takeAs<Expr>(); 3923 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3924 // Build the default argument expression. 3925 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3926 } 3927 3928 // If the default expression creates temporaries, we need to 3929 // push them to the current stack of expression temporaries so they'll 3930 // be properly destroyed. 3931 // FIXME: We should really be rebuilding the default argument with new 3932 // bound temporaries; see the comment in PR5810. 3933 // We don't need to do that with block decls, though, because 3934 // blocks in default argument expression can never capture anything. 3935 if (isa<ExprWithCleanups>(Param->getInit())) { 3936 // Set the "needs cleanups" bit regardless of whether there are 3937 // any explicit objects. 3938 ExprNeedsCleanups = true; 3939 3940 // Append all the objects to the cleanup list. Right now, this 3941 // should always be a no-op, because blocks in default argument 3942 // expressions should never be able to capture anything. 3943 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3944 "default argument expression has capturing blocks?"); 3945 } 3946 3947 // We already type-checked the argument, so we know it works. 3948 // Just mark all of the declarations in this potentially-evaluated expression 3949 // as being "referenced". 3950 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3951 /*SkipLocalVariables=*/true); 3952 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3953 } 3954 3955 3956 Sema::VariadicCallType 3957 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3958 Expr *Fn) { 3959 if (Proto && Proto->isVariadic()) { 3960 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3961 return VariadicConstructor; 3962 else if (Fn && Fn->getType()->isBlockPointerType()) 3963 return VariadicBlock; 3964 else if (FDecl) { 3965 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3966 if (Method->isInstance()) 3967 return VariadicMethod; 3968 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 3969 return VariadicMethod; 3970 return VariadicFunction; 3971 } 3972 return VariadicDoesNotApply; 3973 } 3974 3975 namespace { 3976 class FunctionCallCCC : public FunctionCallFilterCCC { 3977 public: 3978 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 3979 unsigned NumArgs, MemberExpr *ME) 3980 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 3981 FunctionName(FuncName) {} 3982 3983 bool ValidateCandidate(const TypoCorrection &candidate) override { 3984 if (!candidate.getCorrectionSpecifier() || 3985 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 3986 return false; 3987 } 3988 3989 return FunctionCallFilterCCC::ValidateCandidate(candidate); 3990 } 3991 3992 private: 3993 const IdentifierInfo *const FunctionName; 3994 }; 3995 } 3996 3997 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 3998 FunctionDecl *FDecl, 3999 ArrayRef<Expr *> Args) { 4000 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4001 DeclarationName FuncName = FDecl->getDeclName(); 4002 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4003 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4004 4005 if (TypoCorrection Corrected = S.CorrectTypo( 4006 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4007 S.getScopeForContext(S.CurContext), NULL, CCC)) { 4008 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4009 if (Corrected.isOverloaded()) { 4010 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4011 OverloadCandidateSet::iterator Best; 4012 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4013 CDEnd = Corrected.end(); 4014 CD != CDEnd; ++CD) { 4015 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4016 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4017 OCS); 4018 } 4019 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4020 case OR_Success: 4021 ND = Best->Function; 4022 Corrected.setCorrectionDecl(ND); 4023 break; 4024 default: 4025 break; 4026 } 4027 } 4028 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4029 return Corrected; 4030 } 4031 } 4032 } 4033 return TypoCorrection(); 4034 } 4035 4036 /// ConvertArgumentsForCall - Converts the arguments specified in 4037 /// Args/NumArgs to the parameter types of the function FDecl with 4038 /// function prototype Proto. Call is the call expression itself, and 4039 /// Fn is the function expression. For a C++ member function, this 4040 /// routine does not attempt to convert the object argument. Returns 4041 /// true if the call is ill-formed. 4042 bool 4043 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4044 FunctionDecl *FDecl, 4045 const FunctionProtoType *Proto, 4046 ArrayRef<Expr *> Args, 4047 SourceLocation RParenLoc, 4048 bool IsExecConfig) { 4049 // Bail out early if calling a builtin with custom typechecking. 4050 // We don't need to do this in the 4051 if (FDecl) 4052 if (unsigned ID = FDecl->getBuiltinID()) 4053 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4054 return false; 4055 4056 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4057 // assignment, to the types of the corresponding parameter, ... 4058 unsigned NumParams = Proto->getNumParams(); 4059 bool Invalid = false; 4060 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4061 unsigned FnKind = Fn->getType()->isBlockPointerType() 4062 ? 1 /* block */ 4063 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4064 : 0 /* function */); 4065 4066 // If too few arguments are available (and we don't have default 4067 // arguments for the remaining parameters), don't make the call. 4068 if (Args.size() < NumParams) { 4069 if (Args.size() < MinArgs) { 4070 TypoCorrection TC; 4071 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, 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 TypoCorrection TC; 4107 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4108 unsigned diag_id = 4109 MinArgs == NumParams && !Proto->isVariadic() 4110 ? diag::err_typecheck_call_too_many_args_suggest 4111 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4112 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4113 << static_cast<unsigned>(Args.size()) 4114 << TC.getCorrectionRange()); 4115 } else if (NumParams == 1 && FDecl && 4116 FDecl->getParamDecl(0)->getDeclName()) 4117 Diag(Args[NumParams]->getLocStart(), 4118 MinArgs == NumParams 4119 ? diag::err_typecheck_call_too_many_args_one 4120 : diag::err_typecheck_call_too_many_args_at_most_one) 4121 << FnKind << FDecl->getParamDecl(0) 4122 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4123 << SourceRange(Args[NumParams]->getLocStart(), 4124 Args.back()->getLocEnd()); 4125 else 4126 Diag(Args[NumParams]->getLocStart(), 4127 MinArgs == NumParams 4128 ? diag::err_typecheck_call_too_many_args 4129 : diag::err_typecheck_call_too_many_args_at_most) 4130 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4131 << Fn->getSourceRange() 4132 << SourceRange(Args[NumParams]->getLocStart(), 4133 Args.back()->getLocEnd()); 4134 4135 // Emit the location of the prototype. 4136 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4137 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4138 << FDecl; 4139 4140 // This deletes the extra arguments. 4141 Call->setNumArgs(Context, NumParams); 4142 return true; 4143 } 4144 } 4145 SmallVector<Expr *, 8> AllArgs; 4146 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4147 4148 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4149 Proto, 0, Args, AllArgs, CallType); 4150 if (Invalid) 4151 return true; 4152 unsigned TotalNumArgs = AllArgs.size(); 4153 for (unsigned i = 0; i < TotalNumArgs; ++i) 4154 Call->setArg(i, AllArgs[i]); 4155 4156 return false; 4157 } 4158 4159 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4160 const FunctionProtoType *Proto, 4161 unsigned FirstParam, ArrayRef<Expr *> Args, 4162 SmallVectorImpl<Expr *> &AllArgs, 4163 VariadicCallType CallType, bool AllowExplicit, 4164 bool IsListInitialization) { 4165 unsigned NumParams = Proto->getNumParams(); 4166 unsigned NumArgsToCheck = Args.size(); 4167 bool Invalid = false; 4168 if (Args.size() != NumParams) 4169 // Use default arguments for missing arguments 4170 NumArgsToCheck = NumParams; 4171 unsigned ArgIx = 0; 4172 // Continue to check argument types (even if we have too few/many args). 4173 for (unsigned i = FirstParam; i != NumArgsToCheck; i++) { 4174 QualType ProtoArgType = Proto->getParamType(i); 4175 4176 Expr *Arg; 4177 ParmVarDecl *Param; 4178 if (ArgIx < Args.size()) { 4179 Arg = Args[ArgIx++]; 4180 4181 if (RequireCompleteType(Arg->getLocStart(), 4182 ProtoArgType, 4183 diag::err_call_incomplete_argument, Arg)) 4184 return true; 4185 4186 // Pass the argument 4187 Param = 0; 4188 if (FDecl && i < FDecl->getNumParams()) 4189 Param = FDecl->getParamDecl(i); 4190 4191 // Strip the unbridged-cast placeholder expression off, if applicable. 4192 bool CFAudited = false; 4193 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4194 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4195 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4196 Arg = stripARCUnbridgedCast(Arg); 4197 else if (getLangOpts().ObjCAutoRefCount && 4198 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4199 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4200 CFAudited = true; 4201 4202 InitializedEntity Entity = 4203 Param ? InitializedEntity::InitializeParameter(Context, Param, 4204 ProtoArgType) 4205 : InitializedEntity::InitializeParameter( 4206 Context, ProtoArgType, Proto->isParamConsumed(i)); 4207 4208 // Remember that parameter belongs to a CF audited API. 4209 if (CFAudited) 4210 Entity.setParameterCFAudited(); 4211 4212 ExprResult ArgE = PerformCopyInitialization(Entity, 4213 SourceLocation(), 4214 Owned(Arg), 4215 IsListInitialization, 4216 AllowExplicit); 4217 if (ArgE.isInvalid()) 4218 return true; 4219 4220 Arg = ArgE.takeAs<Expr>(); 4221 } else { 4222 assert(FDecl && "can't use default arguments without a known callee"); 4223 Param = FDecl->getParamDecl(i); 4224 4225 ExprResult ArgExpr = 4226 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4227 if (ArgExpr.isInvalid()) 4228 return true; 4229 4230 Arg = ArgExpr.takeAs<Expr>(); 4231 } 4232 4233 // Check for array bounds violations for each argument to the call. This 4234 // check only triggers warnings when the argument isn't a more complex Expr 4235 // with its own checking, such as a BinaryOperator. 4236 CheckArrayAccess(Arg); 4237 4238 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4239 CheckStaticArrayArgument(CallLoc, Param, Arg); 4240 4241 AllArgs.push_back(Arg); 4242 } 4243 4244 // If this is a variadic call, handle args passed through "...". 4245 if (CallType != VariadicDoesNotApply) { 4246 // Assume that extern "C" functions with variadic arguments that 4247 // return __unknown_anytype aren't *really* variadic. 4248 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4249 FDecl->isExternC()) { 4250 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4251 QualType paramType; // ignored 4252 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4253 Invalid |= arg.isInvalid(); 4254 AllArgs.push_back(arg.take()); 4255 } 4256 4257 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4258 } else { 4259 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4260 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4261 FDecl); 4262 Invalid |= Arg.isInvalid(); 4263 AllArgs.push_back(Arg.take()); 4264 } 4265 } 4266 4267 // Check for array bounds violations. 4268 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4269 CheckArrayAccess(Args[i]); 4270 } 4271 return Invalid; 4272 } 4273 4274 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4275 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4276 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4277 TL = DTL.getOriginalLoc(); 4278 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4279 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4280 << ATL.getLocalSourceRange(); 4281 } 4282 4283 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4284 /// array parameter, check that it is non-null, and that if it is formed by 4285 /// array-to-pointer decay, the underlying array is sufficiently large. 4286 /// 4287 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4288 /// array type derivation, then for each call to the function, the value of the 4289 /// corresponding actual argument shall provide access to the first element of 4290 /// an array with at least as many elements as specified by the size expression. 4291 void 4292 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4293 ParmVarDecl *Param, 4294 const Expr *ArgExpr) { 4295 // Static array parameters are not supported in C++. 4296 if (!Param || getLangOpts().CPlusPlus) 4297 return; 4298 4299 QualType OrigTy = Param->getOriginalType(); 4300 4301 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4302 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4303 return; 4304 4305 if (ArgExpr->isNullPointerConstant(Context, 4306 Expr::NPC_NeverValueDependent)) { 4307 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4308 DiagnoseCalleeStaticArrayParam(*this, Param); 4309 return; 4310 } 4311 4312 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4313 if (!CAT) 4314 return; 4315 4316 const ConstantArrayType *ArgCAT = 4317 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4318 if (!ArgCAT) 4319 return; 4320 4321 if (ArgCAT->getSize().ult(CAT->getSize())) { 4322 Diag(CallLoc, diag::warn_static_array_too_small) 4323 << ArgExpr->getSourceRange() 4324 << (unsigned) ArgCAT->getSize().getZExtValue() 4325 << (unsigned) CAT->getSize().getZExtValue(); 4326 DiagnoseCalleeStaticArrayParam(*this, Param); 4327 } 4328 } 4329 4330 /// Given a function expression of unknown-any type, try to rebuild it 4331 /// to have a function type. 4332 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4333 4334 /// Is the given type a placeholder that we need to lower out 4335 /// immediately during argument processing? 4336 static bool isPlaceholderToRemoveAsArg(QualType type) { 4337 // Placeholders are never sugared. 4338 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4339 if (!placeholder) return false; 4340 4341 switch (placeholder->getKind()) { 4342 // Ignore all the non-placeholder types. 4343 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4344 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4345 #include "clang/AST/BuiltinTypes.def" 4346 return false; 4347 4348 // We cannot lower out overload sets; they might validly be resolved 4349 // by the call machinery. 4350 case BuiltinType::Overload: 4351 return false; 4352 4353 // Unbridged casts in ARC can be handled in some call positions and 4354 // should be left in place. 4355 case BuiltinType::ARCUnbridgedCast: 4356 return false; 4357 4358 // Pseudo-objects should be converted as soon as possible. 4359 case BuiltinType::PseudoObject: 4360 return true; 4361 4362 // The debugger mode could theoretically but currently does not try 4363 // to resolve unknown-typed arguments based on known parameter types. 4364 case BuiltinType::UnknownAny: 4365 return true; 4366 4367 // These are always invalid as call arguments and should be reported. 4368 case BuiltinType::BoundMember: 4369 case BuiltinType::BuiltinFn: 4370 return true; 4371 } 4372 llvm_unreachable("bad builtin type kind"); 4373 } 4374 4375 /// Check an argument list for placeholders that we won't try to 4376 /// handle later. 4377 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4378 // Apply this processing to all the arguments at once instead of 4379 // dying at the first failure. 4380 bool hasInvalid = false; 4381 for (size_t i = 0, e = args.size(); i != e; i++) { 4382 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4383 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4384 if (result.isInvalid()) hasInvalid = true; 4385 else args[i] = result.take(); 4386 } 4387 } 4388 return hasInvalid; 4389 } 4390 4391 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4392 /// This provides the location of the left/right parens and a list of comma 4393 /// locations. 4394 ExprResult 4395 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4396 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4397 Expr *ExecConfig, bool IsExecConfig) { 4398 // Since this might be a postfix expression, get rid of ParenListExprs. 4399 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4400 if (Result.isInvalid()) return ExprError(); 4401 Fn = Result.take(); 4402 4403 if (checkArgsForPlaceholders(*this, ArgExprs)) 4404 return ExprError(); 4405 4406 if (getLangOpts().CPlusPlus) { 4407 // If this is a pseudo-destructor expression, build the call immediately. 4408 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4409 if (!ArgExprs.empty()) { 4410 // Pseudo-destructor calls should not have any arguments. 4411 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4412 << FixItHint::CreateRemoval( 4413 SourceRange(ArgExprs[0]->getLocStart(), 4414 ArgExprs.back()->getLocEnd())); 4415 } 4416 4417 return Owned(new (Context) CallExpr(Context, Fn, None, 4418 Context.VoidTy, VK_RValue, 4419 RParenLoc)); 4420 } 4421 if (Fn->getType() == Context.PseudoObjectTy) { 4422 ExprResult result = CheckPlaceholderExpr(Fn); 4423 if (result.isInvalid()) return ExprError(); 4424 Fn = result.take(); 4425 } 4426 4427 // Determine whether this is a dependent call inside a C++ template, 4428 // in which case we won't do any semantic analysis now. 4429 // FIXME: Will need to cache the results of name lookup (including ADL) in 4430 // Fn. 4431 bool Dependent = false; 4432 if (Fn->isTypeDependent()) 4433 Dependent = true; 4434 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4435 Dependent = true; 4436 4437 if (Dependent) { 4438 if (ExecConfig) { 4439 return Owned(new (Context) CUDAKernelCallExpr( 4440 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4441 Context.DependentTy, VK_RValue, RParenLoc)); 4442 } else { 4443 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4444 Context.DependentTy, VK_RValue, 4445 RParenLoc)); 4446 } 4447 } 4448 4449 // Determine whether this is a call to an object (C++ [over.call.object]). 4450 if (Fn->getType()->isRecordType()) 4451 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4452 ArgExprs, RParenLoc)); 4453 4454 if (Fn->getType() == Context.UnknownAnyTy) { 4455 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4456 if (result.isInvalid()) return ExprError(); 4457 Fn = result.take(); 4458 } 4459 4460 if (Fn->getType() == Context.BoundMemberTy) { 4461 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4462 } 4463 } 4464 4465 // Check for overloaded calls. This can happen even in C due to extensions. 4466 if (Fn->getType() == Context.OverloadTy) { 4467 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4468 4469 // We aren't supposed to apply this logic for if there's an '&' involved. 4470 if (!find.HasFormOfMemberPointer) { 4471 OverloadExpr *ovl = find.Expression; 4472 if (isa<UnresolvedLookupExpr>(ovl)) { 4473 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4474 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4475 RParenLoc, ExecConfig); 4476 } else { 4477 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4478 RParenLoc); 4479 } 4480 } 4481 } 4482 4483 // If we're directly calling a function, get the appropriate declaration. 4484 if (Fn->getType() == Context.UnknownAnyTy) { 4485 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4486 if (result.isInvalid()) return ExprError(); 4487 Fn = result.take(); 4488 } 4489 4490 Expr *NakedFn = Fn->IgnoreParens(); 4491 4492 NamedDecl *NDecl = 0; 4493 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4494 if (UnOp->getOpcode() == UO_AddrOf) 4495 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4496 4497 if (isa<DeclRefExpr>(NakedFn)) 4498 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4499 else if (isa<MemberExpr>(NakedFn)) 4500 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4501 4502 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4503 if (FD->hasAttr<EnableIfAttr>()) { 4504 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4505 Diag(Fn->getLocStart(), 4506 isa<CXXMethodDecl>(FD) ? 4507 diag::err_ovl_no_viable_member_function_in_call : 4508 diag::err_ovl_no_viable_function_in_call) 4509 << FD << FD->getSourceRange(); 4510 Diag(FD->getLocation(), 4511 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4512 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4513 } 4514 } 4515 } 4516 4517 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4518 ExecConfig, IsExecConfig); 4519 } 4520 4521 ExprResult 4522 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4523 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4524 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4525 if (!ConfigDecl) 4526 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4527 << "cudaConfigureCall"); 4528 QualType ConfigQTy = ConfigDecl->getType(); 4529 4530 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4531 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4532 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4533 4534 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4535 /*IsExecConfig=*/true); 4536 } 4537 4538 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4539 /// 4540 /// __builtin_astype( value, dst type ) 4541 /// 4542 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4543 SourceLocation BuiltinLoc, 4544 SourceLocation RParenLoc) { 4545 ExprValueKind VK = VK_RValue; 4546 ExprObjectKind OK = OK_Ordinary; 4547 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4548 QualType SrcTy = E->getType(); 4549 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4550 return ExprError(Diag(BuiltinLoc, 4551 diag::err_invalid_astype_of_different_size) 4552 << DstTy 4553 << SrcTy 4554 << E->getSourceRange()); 4555 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4556 RParenLoc)); 4557 } 4558 4559 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4560 /// provided arguments. 4561 /// 4562 /// __builtin_convertvector( value, dst type ) 4563 /// 4564 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4565 SourceLocation BuiltinLoc, 4566 SourceLocation RParenLoc) { 4567 TypeSourceInfo *TInfo; 4568 GetTypeFromParser(ParsedDestTy, &TInfo); 4569 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4570 } 4571 4572 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4573 /// i.e. an expression not of \p OverloadTy. The expression should 4574 /// unary-convert to an expression of function-pointer or 4575 /// block-pointer type. 4576 /// 4577 /// \param NDecl the declaration being called, if available 4578 ExprResult 4579 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4580 SourceLocation LParenLoc, 4581 ArrayRef<Expr *> Args, 4582 SourceLocation RParenLoc, 4583 Expr *Config, bool IsExecConfig) { 4584 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4585 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4586 4587 // Promote the function operand. 4588 // We special-case function promotion here because we only allow promoting 4589 // builtin functions to function pointers in the callee of a call. 4590 ExprResult Result; 4591 if (BuiltinID && 4592 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4593 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4594 CK_BuiltinFnToFnPtr).take(); 4595 } else { 4596 Result = CallExprUnaryConversions(Fn); 4597 } 4598 if (Result.isInvalid()) 4599 return ExprError(); 4600 Fn = Result.take(); 4601 4602 // Make the call expr early, before semantic checks. This guarantees cleanup 4603 // of arguments and function on error. 4604 CallExpr *TheCall; 4605 if (Config) 4606 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4607 cast<CallExpr>(Config), Args, 4608 Context.BoolTy, VK_RValue, 4609 RParenLoc); 4610 else 4611 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4612 VK_RValue, RParenLoc); 4613 4614 // Bail out early if calling a builtin with custom typechecking. 4615 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4616 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4617 4618 retry: 4619 const FunctionType *FuncT; 4620 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4621 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4622 // have type pointer to function". 4623 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4624 if (FuncT == 0) 4625 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4626 << Fn->getType() << Fn->getSourceRange()); 4627 } else if (const BlockPointerType *BPT = 4628 Fn->getType()->getAs<BlockPointerType>()) { 4629 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4630 } else { 4631 // Handle calls to expressions of unknown-any type. 4632 if (Fn->getType() == Context.UnknownAnyTy) { 4633 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4634 if (rewrite.isInvalid()) return ExprError(); 4635 Fn = rewrite.take(); 4636 TheCall->setCallee(Fn); 4637 goto retry; 4638 } 4639 4640 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4641 << Fn->getType() << Fn->getSourceRange()); 4642 } 4643 4644 if (getLangOpts().CUDA) { 4645 if (Config) { 4646 // CUDA: Kernel calls must be to global functions 4647 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4648 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4649 << FDecl->getName() << Fn->getSourceRange()); 4650 4651 // CUDA: Kernel function must have 'void' return type 4652 if (!FuncT->getReturnType()->isVoidType()) 4653 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4654 << Fn->getType() << Fn->getSourceRange()); 4655 } else { 4656 // CUDA: Calls to global functions must be configured 4657 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4658 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4659 << FDecl->getName() << Fn->getSourceRange()); 4660 } 4661 } 4662 4663 // Check for a valid return type 4664 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 4665 FDecl)) 4666 return ExprError(); 4667 4668 // We know the result type of the call, set it. 4669 TheCall->setType(FuncT->getCallResultType(Context)); 4670 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 4671 4672 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4673 if (Proto) { 4674 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4675 IsExecConfig)) 4676 return ExprError(); 4677 } else { 4678 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4679 4680 if (FDecl) { 4681 // Check if we have too few/too many template arguments, based 4682 // on our knowledge of the function definition. 4683 const FunctionDecl *Def = 0; 4684 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4685 Proto = Def->getType()->getAs<FunctionProtoType>(); 4686 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4687 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4688 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4689 } 4690 4691 // If the function we're calling isn't a function prototype, but we have 4692 // a function prototype from a prior declaratiom, use that prototype. 4693 if (!FDecl->hasPrototype()) 4694 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4695 } 4696 4697 // Promote the arguments (C99 6.5.2.2p6). 4698 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4699 Expr *Arg = Args[i]; 4700 4701 if (Proto && i < Proto->getNumParams()) { 4702 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4703 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 4704 ExprResult ArgE = PerformCopyInitialization(Entity, 4705 SourceLocation(), 4706 Owned(Arg)); 4707 if (ArgE.isInvalid()) 4708 return true; 4709 4710 Arg = ArgE.takeAs<Expr>(); 4711 4712 } else { 4713 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4714 4715 if (ArgE.isInvalid()) 4716 return true; 4717 4718 Arg = ArgE.takeAs<Expr>(); 4719 } 4720 4721 if (RequireCompleteType(Arg->getLocStart(), 4722 Arg->getType(), 4723 diag::err_call_incomplete_argument, Arg)) 4724 return ExprError(); 4725 4726 TheCall->setArg(i, Arg); 4727 } 4728 } 4729 4730 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4731 if (!Method->isStatic()) 4732 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4733 << Fn->getSourceRange()); 4734 4735 // Check for sentinels 4736 if (NDecl) 4737 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4738 4739 // Do special checking on direct calls to functions. 4740 if (FDecl) { 4741 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4742 return ExprError(); 4743 4744 if (BuiltinID) 4745 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4746 } else if (NDecl) { 4747 if (CheckPointerCall(NDecl, TheCall, Proto)) 4748 return ExprError(); 4749 } else { 4750 if (CheckOtherCall(TheCall, Proto)) 4751 return ExprError(); 4752 } 4753 4754 return MaybeBindToTemporary(TheCall); 4755 } 4756 4757 ExprResult 4758 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4759 SourceLocation RParenLoc, Expr *InitExpr) { 4760 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4761 // FIXME: put back this assert when initializers are worked out. 4762 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4763 4764 TypeSourceInfo *TInfo; 4765 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4766 if (!TInfo) 4767 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4768 4769 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4770 } 4771 4772 ExprResult 4773 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4774 SourceLocation RParenLoc, Expr *LiteralExpr) { 4775 QualType literalType = TInfo->getType(); 4776 4777 if (literalType->isArrayType()) { 4778 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4779 diag::err_illegal_decl_array_incomplete_type, 4780 SourceRange(LParenLoc, 4781 LiteralExpr->getSourceRange().getEnd()))) 4782 return ExprError(); 4783 if (literalType->isVariableArrayType()) 4784 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4785 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4786 } else if (!literalType->isDependentType() && 4787 RequireCompleteType(LParenLoc, literalType, 4788 diag::err_typecheck_decl_incomplete_type, 4789 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4790 return ExprError(); 4791 4792 InitializedEntity Entity 4793 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4794 InitializationKind Kind 4795 = InitializationKind::CreateCStyleCast(LParenLoc, 4796 SourceRange(LParenLoc, RParenLoc), 4797 /*InitList=*/true); 4798 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4799 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4800 &literalType); 4801 if (Result.isInvalid()) 4802 return ExprError(); 4803 LiteralExpr = Result.get(); 4804 4805 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4806 if (isFileScope && 4807 !LiteralExpr->isTypeDependent() && 4808 !LiteralExpr->isValueDependent() && 4809 !literalType->isDependentType()) { // 6.5.2.5p3 4810 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4811 return ExprError(); 4812 } 4813 4814 // In C, compound literals are l-values for some reason. 4815 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4816 4817 return MaybeBindToTemporary( 4818 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4819 VK, LiteralExpr, isFileScope)); 4820 } 4821 4822 ExprResult 4823 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4824 SourceLocation RBraceLoc) { 4825 // Immediately handle non-overload placeholders. Overloads can be 4826 // resolved contextually, but everything else here can't. 4827 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4828 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4829 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4830 4831 // Ignore failures; dropping the entire initializer list because 4832 // of one failure would be terrible for indexing/etc. 4833 if (result.isInvalid()) continue; 4834 4835 InitArgList[I] = result.take(); 4836 } 4837 } 4838 4839 // Semantic analysis for initializers is done by ActOnDeclarator() and 4840 // CheckInitializer() - it requires knowledge of the object being intialized. 4841 4842 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4843 RBraceLoc); 4844 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4845 return Owned(E); 4846 } 4847 4848 /// Do an explicit extend of the given block pointer if we're in ARC. 4849 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4850 assert(E.get()->getType()->isBlockPointerType()); 4851 assert(E.get()->isRValue()); 4852 4853 // Only do this in an r-value context. 4854 if (!S.getLangOpts().ObjCAutoRefCount) return; 4855 4856 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4857 CK_ARCExtendBlockObject, E.get(), 4858 /*base path*/ 0, VK_RValue); 4859 S.ExprNeedsCleanups = true; 4860 } 4861 4862 /// Prepare a conversion of the given expression to an ObjC object 4863 /// pointer type. 4864 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4865 QualType type = E.get()->getType(); 4866 if (type->isObjCObjectPointerType()) { 4867 return CK_BitCast; 4868 } else if (type->isBlockPointerType()) { 4869 maybeExtendBlockObject(*this, E); 4870 return CK_BlockPointerToObjCPointerCast; 4871 } else { 4872 assert(type->isPointerType()); 4873 return CK_CPointerToObjCPointerCast; 4874 } 4875 } 4876 4877 /// Prepares for a scalar cast, performing all the necessary stages 4878 /// except the final cast and returning the kind required. 4879 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4880 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4881 // Also, callers should have filtered out the invalid cases with 4882 // pointers. Everything else should be possible. 4883 4884 QualType SrcTy = Src.get()->getType(); 4885 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4886 return CK_NoOp; 4887 4888 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4889 case Type::STK_MemberPointer: 4890 llvm_unreachable("member pointer type in C"); 4891 4892 case Type::STK_CPointer: 4893 case Type::STK_BlockPointer: 4894 case Type::STK_ObjCObjectPointer: 4895 switch (DestTy->getScalarTypeKind()) { 4896 case Type::STK_CPointer: { 4897 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 4898 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 4899 if (SrcAS != DestAS) 4900 return CK_AddressSpaceConversion; 4901 return CK_BitCast; 4902 } 4903 case Type::STK_BlockPointer: 4904 return (SrcKind == Type::STK_BlockPointer 4905 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4906 case Type::STK_ObjCObjectPointer: 4907 if (SrcKind == Type::STK_ObjCObjectPointer) 4908 return CK_BitCast; 4909 if (SrcKind == Type::STK_CPointer) 4910 return CK_CPointerToObjCPointerCast; 4911 maybeExtendBlockObject(*this, Src); 4912 return CK_BlockPointerToObjCPointerCast; 4913 case Type::STK_Bool: 4914 return CK_PointerToBoolean; 4915 case Type::STK_Integral: 4916 return CK_PointerToIntegral; 4917 case Type::STK_Floating: 4918 case Type::STK_FloatingComplex: 4919 case Type::STK_IntegralComplex: 4920 case Type::STK_MemberPointer: 4921 llvm_unreachable("illegal cast from pointer"); 4922 } 4923 llvm_unreachable("Should have returned before this"); 4924 4925 case Type::STK_Bool: // casting from bool is like casting from an integer 4926 case Type::STK_Integral: 4927 switch (DestTy->getScalarTypeKind()) { 4928 case Type::STK_CPointer: 4929 case Type::STK_ObjCObjectPointer: 4930 case Type::STK_BlockPointer: 4931 if (Src.get()->isNullPointerConstant(Context, 4932 Expr::NPC_ValueDependentIsNull)) 4933 return CK_NullToPointer; 4934 return CK_IntegralToPointer; 4935 case Type::STK_Bool: 4936 return CK_IntegralToBoolean; 4937 case Type::STK_Integral: 4938 return CK_IntegralCast; 4939 case Type::STK_Floating: 4940 return CK_IntegralToFloating; 4941 case Type::STK_IntegralComplex: 4942 Src = ImpCastExprToType(Src.take(), 4943 DestTy->castAs<ComplexType>()->getElementType(), 4944 CK_IntegralCast); 4945 return CK_IntegralRealToComplex; 4946 case Type::STK_FloatingComplex: 4947 Src = ImpCastExprToType(Src.take(), 4948 DestTy->castAs<ComplexType>()->getElementType(), 4949 CK_IntegralToFloating); 4950 return CK_FloatingRealToComplex; 4951 case Type::STK_MemberPointer: 4952 llvm_unreachable("member pointer type in C"); 4953 } 4954 llvm_unreachable("Should have returned before this"); 4955 4956 case Type::STK_Floating: 4957 switch (DestTy->getScalarTypeKind()) { 4958 case Type::STK_Floating: 4959 return CK_FloatingCast; 4960 case Type::STK_Bool: 4961 return CK_FloatingToBoolean; 4962 case Type::STK_Integral: 4963 return CK_FloatingToIntegral; 4964 case Type::STK_FloatingComplex: 4965 Src = ImpCastExprToType(Src.take(), 4966 DestTy->castAs<ComplexType>()->getElementType(), 4967 CK_FloatingCast); 4968 return CK_FloatingRealToComplex; 4969 case Type::STK_IntegralComplex: 4970 Src = ImpCastExprToType(Src.take(), 4971 DestTy->castAs<ComplexType>()->getElementType(), 4972 CK_FloatingToIntegral); 4973 return CK_IntegralRealToComplex; 4974 case Type::STK_CPointer: 4975 case Type::STK_ObjCObjectPointer: 4976 case Type::STK_BlockPointer: 4977 llvm_unreachable("valid float->pointer cast?"); 4978 case Type::STK_MemberPointer: 4979 llvm_unreachable("member pointer type in C"); 4980 } 4981 llvm_unreachable("Should have returned before this"); 4982 4983 case Type::STK_FloatingComplex: 4984 switch (DestTy->getScalarTypeKind()) { 4985 case Type::STK_FloatingComplex: 4986 return CK_FloatingComplexCast; 4987 case Type::STK_IntegralComplex: 4988 return CK_FloatingComplexToIntegralComplex; 4989 case Type::STK_Floating: { 4990 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4991 if (Context.hasSameType(ET, DestTy)) 4992 return CK_FloatingComplexToReal; 4993 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4994 return CK_FloatingCast; 4995 } 4996 case Type::STK_Bool: 4997 return CK_FloatingComplexToBoolean; 4998 case Type::STK_Integral: 4999 Src = ImpCastExprToType(Src.take(), 5000 SrcTy->castAs<ComplexType>()->getElementType(), 5001 CK_FloatingComplexToReal); 5002 return CK_FloatingToIntegral; 5003 case Type::STK_CPointer: 5004 case Type::STK_ObjCObjectPointer: 5005 case Type::STK_BlockPointer: 5006 llvm_unreachable("valid complex float->pointer cast?"); 5007 case Type::STK_MemberPointer: 5008 llvm_unreachable("member pointer type in C"); 5009 } 5010 llvm_unreachable("Should have returned before this"); 5011 5012 case Type::STK_IntegralComplex: 5013 switch (DestTy->getScalarTypeKind()) { 5014 case Type::STK_FloatingComplex: 5015 return CK_IntegralComplexToFloatingComplex; 5016 case Type::STK_IntegralComplex: 5017 return CK_IntegralComplexCast; 5018 case Type::STK_Integral: { 5019 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5020 if (Context.hasSameType(ET, DestTy)) 5021 return CK_IntegralComplexToReal; 5022 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 5023 return CK_IntegralCast; 5024 } 5025 case Type::STK_Bool: 5026 return CK_IntegralComplexToBoolean; 5027 case Type::STK_Floating: 5028 Src = ImpCastExprToType(Src.take(), 5029 SrcTy->castAs<ComplexType>()->getElementType(), 5030 CK_IntegralComplexToReal); 5031 return CK_IntegralToFloating; 5032 case Type::STK_CPointer: 5033 case Type::STK_ObjCObjectPointer: 5034 case Type::STK_BlockPointer: 5035 llvm_unreachable("valid complex int->pointer cast?"); 5036 case Type::STK_MemberPointer: 5037 llvm_unreachable("member pointer type in C"); 5038 } 5039 llvm_unreachable("Should have returned before this"); 5040 } 5041 5042 llvm_unreachable("Unhandled scalar cast"); 5043 } 5044 5045 static bool breakDownVectorType(QualType type, uint64_t &len, 5046 QualType &eltType) { 5047 // Vectors are simple. 5048 if (const VectorType *vecType = type->getAs<VectorType>()) { 5049 len = vecType->getNumElements(); 5050 eltType = vecType->getElementType(); 5051 assert(eltType->isScalarType()); 5052 return true; 5053 } 5054 5055 // We allow lax conversion to and from non-vector types, but only if 5056 // they're real types (i.e. non-complex, non-pointer scalar types). 5057 if (!type->isRealType()) return false; 5058 5059 len = 1; 5060 eltType = type; 5061 return true; 5062 } 5063 5064 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) { 5065 uint64_t srcLen, destLen; 5066 QualType srcElt, destElt; 5067 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 5068 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 5069 5070 // ASTContext::getTypeSize will return the size rounded up to a 5071 // power of 2, so instead of using that, we need to use the raw 5072 // element size multiplied by the element count. 5073 uint64_t srcEltSize = S.Context.getTypeSize(srcElt); 5074 uint64_t destEltSize = S.Context.getTypeSize(destElt); 5075 5076 return (srcLen * srcEltSize == destLen * destEltSize); 5077 } 5078 5079 /// Is this a legal conversion between two known vector types? 5080 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5081 assert(destTy->isVectorType() || srcTy->isVectorType()); 5082 5083 if (!Context.getLangOpts().LaxVectorConversions) 5084 return false; 5085 return VectorTypesMatch(*this, srcTy, destTy); 5086 } 5087 5088 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5089 CastKind &Kind) { 5090 assert(VectorTy->isVectorType() && "Not a vector type!"); 5091 5092 if (Ty->isVectorType() || Ty->isIntegerType()) { 5093 if (!VectorTypesMatch(*this, Ty, VectorTy)) 5094 return Diag(R.getBegin(), 5095 Ty->isVectorType() ? 5096 diag::err_invalid_conversion_between_vectors : 5097 diag::err_invalid_conversion_between_vector_and_integer) 5098 << VectorTy << Ty << R; 5099 } else 5100 return Diag(R.getBegin(), 5101 diag::err_invalid_conversion_between_vector_and_scalar) 5102 << VectorTy << Ty << R; 5103 5104 Kind = CK_BitCast; 5105 return false; 5106 } 5107 5108 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5109 Expr *CastExpr, CastKind &Kind) { 5110 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5111 5112 QualType SrcTy = CastExpr->getType(); 5113 5114 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5115 // an ExtVectorType. 5116 // In OpenCL, casts between vectors of different types are not allowed. 5117 // (See OpenCL 6.2). 5118 if (SrcTy->isVectorType()) { 5119 if (!VectorTypesMatch(*this, SrcTy, DestTy) 5120 || (getLangOpts().OpenCL && 5121 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5122 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5123 << DestTy << SrcTy << R; 5124 return ExprError(); 5125 } 5126 Kind = CK_BitCast; 5127 return Owned(CastExpr); 5128 } 5129 5130 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5131 // conversion will take place first from scalar to elt type, and then 5132 // splat from elt type to vector. 5133 if (SrcTy->isPointerType()) 5134 return Diag(R.getBegin(), 5135 diag::err_invalid_conversion_between_vector_and_scalar) 5136 << DestTy << SrcTy << R; 5137 5138 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5139 ExprResult CastExprRes = Owned(CastExpr); 5140 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5141 if (CastExprRes.isInvalid()) 5142 return ExprError(); 5143 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 5144 5145 Kind = CK_VectorSplat; 5146 return Owned(CastExpr); 5147 } 5148 5149 ExprResult 5150 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5151 Declarator &D, ParsedType &Ty, 5152 SourceLocation RParenLoc, Expr *CastExpr) { 5153 assert(!D.isInvalidType() && (CastExpr != 0) && 5154 "ActOnCastExpr(): missing type or expr"); 5155 5156 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5157 if (D.isInvalidType()) 5158 return ExprError(); 5159 5160 if (getLangOpts().CPlusPlus) { 5161 // Check that there are no default arguments (C++ only). 5162 CheckExtraCXXDefaultArguments(D); 5163 } 5164 5165 checkUnusedDeclAttributes(D); 5166 5167 QualType castType = castTInfo->getType(); 5168 Ty = CreateParsedType(castType, castTInfo); 5169 5170 bool isVectorLiteral = false; 5171 5172 // Check for an altivec or OpenCL literal, 5173 // i.e. all the elements are integer constants. 5174 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5175 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5176 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5177 && castType->isVectorType() && (PE || PLE)) { 5178 if (PLE && PLE->getNumExprs() == 0) { 5179 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5180 return ExprError(); 5181 } 5182 if (PE || PLE->getNumExprs() == 1) { 5183 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5184 if (!E->getType()->isVectorType()) 5185 isVectorLiteral = true; 5186 } 5187 else 5188 isVectorLiteral = true; 5189 } 5190 5191 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5192 // then handle it as such. 5193 if (isVectorLiteral) 5194 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5195 5196 // If the Expr being casted is a ParenListExpr, handle it specially. 5197 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5198 // sequence of BinOp comma operators. 5199 if (isa<ParenListExpr>(CastExpr)) { 5200 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5201 if (Result.isInvalid()) return ExprError(); 5202 CastExpr = Result.take(); 5203 } 5204 5205 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5206 !getSourceManager().isInSystemMacro(LParenLoc)) 5207 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5208 5209 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5210 } 5211 5212 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5213 SourceLocation RParenLoc, Expr *E, 5214 TypeSourceInfo *TInfo) { 5215 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5216 "Expected paren or paren list expression"); 5217 5218 Expr **exprs; 5219 unsigned numExprs; 5220 Expr *subExpr; 5221 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5222 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5223 LiteralLParenLoc = PE->getLParenLoc(); 5224 LiteralRParenLoc = PE->getRParenLoc(); 5225 exprs = PE->getExprs(); 5226 numExprs = PE->getNumExprs(); 5227 } else { // isa<ParenExpr> by assertion at function entrance 5228 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5229 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5230 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5231 exprs = &subExpr; 5232 numExprs = 1; 5233 } 5234 5235 QualType Ty = TInfo->getType(); 5236 assert(Ty->isVectorType() && "Expected vector type"); 5237 5238 SmallVector<Expr *, 8> initExprs; 5239 const VectorType *VTy = Ty->getAs<VectorType>(); 5240 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5241 5242 // '(...)' form of vector initialization in AltiVec: the number of 5243 // initializers must be one or must match the size of the vector. 5244 // If a single value is specified in the initializer then it will be 5245 // replicated to all the components of the vector 5246 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5247 // The number of initializers must be one or must match the size of the 5248 // vector. If a single value is specified in the initializer then it will 5249 // be replicated to all the components of the vector 5250 if (numExprs == 1) { 5251 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5252 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5253 if (Literal.isInvalid()) 5254 return ExprError(); 5255 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5256 PrepareScalarCast(Literal, ElemTy)); 5257 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5258 } 5259 else if (numExprs < numElems) { 5260 Diag(E->getExprLoc(), 5261 diag::err_incorrect_number_of_vector_initializers); 5262 return ExprError(); 5263 } 5264 else 5265 initExprs.append(exprs, exprs + numExprs); 5266 } 5267 else { 5268 // For OpenCL, when the number of initializers is a single value, 5269 // it will be replicated to all components of the vector. 5270 if (getLangOpts().OpenCL && 5271 VTy->getVectorKind() == VectorType::GenericVector && 5272 numExprs == 1) { 5273 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5274 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5275 if (Literal.isInvalid()) 5276 return ExprError(); 5277 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5278 PrepareScalarCast(Literal, ElemTy)); 5279 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5280 } 5281 5282 initExprs.append(exprs, exprs + numExprs); 5283 } 5284 // FIXME: This means that pretty-printing the final AST will produce curly 5285 // braces instead of the original commas. 5286 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5287 initExprs, LiteralRParenLoc); 5288 initE->setType(Ty); 5289 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5290 } 5291 5292 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5293 /// the ParenListExpr into a sequence of comma binary operators. 5294 ExprResult 5295 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5296 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5297 if (!E) 5298 return Owned(OrigExpr); 5299 5300 ExprResult Result(E->getExpr(0)); 5301 5302 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5303 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5304 E->getExpr(i)); 5305 5306 if (Result.isInvalid()) return ExprError(); 5307 5308 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5309 } 5310 5311 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5312 SourceLocation R, 5313 MultiExprArg Val) { 5314 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5315 return Owned(expr); 5316 } 5317 5318 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5319 /// constant and the other is not a pointer. Returns true if a diagnostic is 5320 /// emitted. 5321 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5322 SourceLocation QuestionLoc) { 5323 Expr *NullExpr = LHSExpr; 5324 Expr *NonPointerExpr = RHSExpr; 5325 Expr::NullPointerConstantKind NullKind = 5326 NullExpr->isNullPointerConstant(Context, 5327 Expr::NPC_ValueDependentIsNotNull); 5328 5329 if (NullKind == Expr::NPCK_NotNull) { 5330 NullExpr = RHSExpr; 5331 NonPointerExpr = LHSExpr; 5332 NullKind = 5333 NullExpr->isNullPointerConstant(Context, 5334 Expr::NPC_ValueDependentIsNotNull); 5335 } 5336 5337 if (NullKind == Expr::NPCK_NotNull) 5338 return false; 5339 5340 if (NullKind == Expr::NPCK_ZeroExpression) 5341 return false; 5342 5343 if (NullKind == Expr::NPCK_ZeroLiteral) { 5344 // In this case, check to make sure that we got here from a "NULL" 5345 // string in the source code. 5346 NullExpr = NullExpr->IgnoreParenImpCasts(); 5347 SourceLocation loc = NullExpr->getExprLoc(); 5348 if (!findMacroSpelling(loc, "NULL")) 5349 return false; 5350 } 5351 5352 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5353 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5354 << NonPointerExpr->getType() << DiagType 5355 << NonPointerExpr->getSourceRange(); 5356 return true; 5357 } 5358 5359 /// \brief Return false if the condition expression is valid, true otherwise. 5360 static bool checkCondition(Sema &S, Expr *Cond) { 5361 QualType CondTy = Cond->getType(); 5362 5363 // C99 6.5.15p2 5364 if (CondTy->isScalarType()) return false; 5365 5366 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5367 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5368 return false; 5369 5370 // Emit the proper error message. 5371 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5372 diag::err_typecheck_cond_expect_scalar : 5373 diag::err_typecheck_cond_expect_scalar_or_vector) 5374 << CondTy; 5375 return true; 5376 } 5377 5378 /// \brief Return false if the two expressions can be converted to a vector, 5379 /// true otherwise 5380 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5381 ExprResult &RHS, 5382 QualType CondTy) { 5383 // Both operands should be of scalar type. 5384 if (!LHS.get()->getType()->isScalarType()) { 5385 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5386 << CondTy; 5387 return true; 5388 } 5389 if (!RHS.get()->getType()->isScalarType()) { 5390 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5391 << CondTy; 5392 return true; 5393 } 5394 5395 // Implicity convert these scalars to the type of the condition. 5396 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5397 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5398 return false; 5399 } 5400 5401 /// \brief Handle when one or both operands are void type. 5402 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5403 ExprResult &RHS) { 5404 Expr *LHSExpr = LHS.get(); 5405 Expr *RHSExpr = RHS.get(); 5406 5407 if (!LHSExpr->getType()->isVoidType()) 5408 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5409 << RHSExpr->getSourceRange(); 5410 if (!RHSExpr->getType()->isVoidType()) 5411 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5412 << LHSExpr->getSourceRange(); 5413 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5414 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5415 return S.Context.VoidTy; 5416 } 5417 5418 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5419 /// true otherwise. 5420 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5421 QualType PointerTy) { 5422 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5423 !NullExpr.get()->isNullPointerConstant(S.Context, 5424 Expr::NPC_ValueDependentIsNull)) 5425 return true; 5426 5427 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5428 return false; 5429 } 5430 5431 /// \brief Checks compatibility between two pointers and return the resulting 5432 /// type. 5433 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5434 ExprResult &RHS, 5435 SourceLocation Loc) { 5436 QualType LHSTy = LHS.get()->getType(); 5437 QualType RHSTy = RHS.get()->getType(); 5438 5439 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5440 // Two identical pointers types are always compatible. 5441 return LHSTy; 5442 } 5443 5444 QualType lhptee, rhptee; 5445 5446 // Get the pointee types. 5447 bool IsBlockPointer = false; 5448 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5449 lhptee = LHSBTy->getPointeeType(); 5450 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5451 IsBlockPointer = true; 5452 } else { 5453 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5454 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5455 } 5456 5457 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5458 // differently qualified versions of compatible types, the result type is 5459 // a pointer to an appropriately qualified version of the composite 5460 // type. 5461 5462 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5463 // clause doesn't make sense for our extensions. E.g. address space 2 should 5464 // be incompatible with address space 3: they may live on different devices or 5465 // anything. 5466 Qualifiers lhQual = lhptee.getQualifiers(); 5467 Qualifiers rhQual = rhptee.getQualifiers(); 5468 5469 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5470 lhQual.removeCVRQualifiers(); 5471 rhQual.removeCVRQualifiers(); 5472 5473 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5474 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5475 5476 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5477 5478 if (CompositeTy.isNull()) { 5479 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5480 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5481 << RHS.get()->getSourceRange(); 5482 // In this situation, we assume void* type. No especially good 5483 // reason, but this is what gcc does, and we do have to pick 5484 // to get a consistent AST. 5485 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5486 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5487 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5488 return incompatTy; 5489 } 5490 5491 // The pointer types are compatible. 5492 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5493 if (IsBlockPointer) 5494 ResultTy = S.Context.getBlockPointerType(ResultTy); 5495 else 5496 ResultTy = S.Context.getPointerType(ResultTy); 5497 5498 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5499 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5500 return ResultTy; 5501 } 5502 5503 /// \brief Return the resulting type when the operands are both block pointers. 5504 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5505 ExprResult &LHS, 5506 ExprResult &RHS, 5507 SourceLocation Loc) { 5508 QualType LHSTy = LHS.get()->getType(); 5509 QualType RHSTy = RHS.get()->getType(); 5510 5511 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5512 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5513 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5514 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5515 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5516 return destType; 5517 } 5518 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5519 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5520 << RHS.get()->getSourceRange(); 5521 return QualType(); 5522 } 5523 5524 // We have 2 block pointer types. 5525 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5526 } 5527 5528 /// \brief Return the resulting type when the operands are both pointers. 5529 static QualType 5530 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5531 ExprResult &RHS, 5532 SourceLocation Loc) { 5533 // get the pointer types 5534 QualType LHSTy = LHS.get()->getType(); 5535 QualType RHSTy = RHS.get()->getType(); 5536 5537 // get the "pointed to" types 5538 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5539 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5540 5541 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5542 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5543 // Figure out necessary qualifiers (C99 6.5.15p6) 5544 QualType destPointee 5545 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5546 QualType destType = S.Context.getPointerType(destPointee); 5547 // Add qualifiers if necessary. 5548 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5549 // Promote to void*. 5550 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5551 return destType; 5552 } 5553 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5554 QualType destPointee 5555 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5556 QualType destType = S.Context.getPointerType(destPointee); 5557 // Add qualifiers if necessary. 5558 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5559 // Promote to void*. 5560 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5561 return destType; 5562 } 5563 5564 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5565 } 5566 5567 /// \brief Return false if the first expression is not an integer and the second 5568 /// expression is not a pointer, true otherwise. 5569 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5570 Expr* PointerExpr, SourceLocation Loc, 5571 bool IsIntFirstExpr) { 5572 if (!PointerExpr->getType()->isPointerType() || 5573 !Int.get()->getType()->isIntegerType()) 5574 return false; 5575 5576 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5577 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5578 5579 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5580 << Expr1->getType() << Expr2->getType() 5581 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5582 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5583 CK_IntegralToPointer); 5584 return true; 5585 } 5586 5587 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5588 /// In that case, LHS = cond. 5589 /// C99 6.5.15 5590 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5591 ExprResult &RHS, ExprValueKind &VK, 5592 ExprObjectKind &OK, 5593 SourceLocation QuestionLoc) { 5594 5595 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5596 if (!LHSResult.isUsable()) return QualType(); 5597 LHS = LHSResult; 5598 5599 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5600 if (!RHSResult.isUsable()) return QualType(); 5601 RHS = RHSResult; 5602 5603 // C++ is sufficiently different to merit its own checker. 5604 if (getLangOpts().CPlusPlus) 5605 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5606 5607 VK = VK_RValue; 5608 OK = OK_Ordinary; 5609 5610 // First, check the condition. 5611 Cond = UsualUnaryConversions(Cond.take()); 5612 if (Cond.isInvalid()) 5613 return QualType(); 5614 if (checkCondition(*this, Cond.get())) 5615 return QualType(); 5616 5617 // Now check the two expressions. 5618 if (LHS.get()->getType()->isVectorType() || 5619 RHS.get()->getType()->isVectorType()) 5620 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5621 5622 UsualArithmeticConversions(LHS, RHS); 5623 if (LHS.isInvalid() || RHS.isInvalid()) 5624 return QualType(); 5625 5626 QualType CondTy = Cond.get()->getType(); 5627 QualType LHSTy = LHS.get()->getType(); 5628 QualType RHSTy = RHS.get()->getType(); 5629 5630 // If the condition is a vector, and both operands are scalar, 5631 // attempt to implicity convert them to the vector type to act like the 5632 // built in select. (OpenCL v1.1 s6.3.i) 5633 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5634 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5635 return QualType(); 5636 5637 // If both operands have arithmetic type, do the usual arithmetic conversions 5638 // to find a common type: C99 6.5.15p3,5. 5639 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5640 return LHS.get()->getType(); 5641 5642 // If both operands are the same structure or union type, the result is that 5643 // type. 5644 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5645 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5646 if (LHSRT->getDecl() == RHSRT->getDecl()) 5647 // "If both the operands have structure or union type, the result has 5648 // that type." This implies that CV qualifiers are dropped. 5649 return LHSTy.getUnqualifiedType(); 5650 // FIXME: Type of conditional expression must be complete in C mode. 5651 } 5652 5653 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5654 // The following || allows only one side to be void (a GCC-ism). 5655 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5656 return checkConditionalVoidType(*this, LHS, RHS); 5657 } 5658 5659 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5660 // the type of the other operand." 5661 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5662 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5663 5664 // All objective-c pointer type analysis is done here. 5665 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5666 QuestionLoc); 5667 if (LHS.isInvalid() || RHS.isInvalid()) 5668 return QualType(); 5669 if (!compositeType.isNull()) 5670 return compositeType; 5671 5672 5673 // Handle block pointer types. 5674 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5675 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5676 QuestionLoc); 5677 5678 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5679 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5680 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5681 QuestionLoc); 5682 5683 // GCC compatibility: soften pointer/integer mismatch. Note that 5684 // null pointers have been filtered out by this point. 5685 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5686 /*isIntFirstExpr=*/true)) 5687 return RHSTy; 5688 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5689 /*isIntFirstExpr=*/false)) 5690 return LHSTy; 5691 5692 // Emit a better diagnostic if one of the expressions is a null pointer 5693 // constant and the other is not a pointer type. In this case, the user most 5694 // likely forgot to take the address of the other expression. 5695 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5696 return QualType(); 5697 5698 // Otherwise, the operands are not compatible. 5699 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5700 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5701 << RHS.get()->getSourceRange(); 5702 return QualType(); 5703 } 5704 5705 /// FindCompositeObjCPointerType - Helper method to find composite type of 5706 /// two objective-c pointer types of the two input expressions. 5707 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5708 SourceLocation QuestionLoc) { 5709 QualType LHSTy = LHS.get()->getType(); 5710 QualType RHSTy = RHS.get()->getType(); 5711 5712 // Handle things like Class and struct objc_class*. Here we case the result 5713 // to the pseudo-builtin, because that will be implicitly cast back to the 5714 // redefinition type if an attempt is made to access its fields. 5715 if (LHSTy->isObjCClassType() && 5716 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5717 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5718 return LHSTy; 5719 } 5720 if (RHSTy->isObjCClassType() && 5721 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5722 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5723 return RHSTy; 5724 } 5725 // And the same for struct objc_object* / id 5726 if (LHSTy->isObjCIdType() && 5727 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5728 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5729 return LHSTy; 5730 } 5731 if (RHSTy->isObjCIdType() && 5732 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5733 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5734 return RHSTy; 5735 } 5736 // And the same for struct objc_selector* / SEL 5737 if (Context.isObjCSelType(LHSTy) && 5738 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5739 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5740 return LHSTy; 5741 } 5742 if (Context.isObjCSelType(RHSTy) && 5743 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5744 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5745 return RHSTy; 5746 } 5747 // Check constraints for Objective-C object pointers types. 5748 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5749 5750 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5751 // Two identical object pointer types are always compatible. 5752 return LHSTy; 5753 } 5754 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5755 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5756 QualType compositeType = LHSTy; 5757 5758 // If both operands are interfaces and either operand can be 5759 // assigned to the other, use that type as the composite 5760 // type. This allows 5761 // xxx ? (A*) a : (B*) b 5762 // where B is a subclass of A. 5763 // 5764 // Additionally, as for assignment, if either type is 'id' 5765 // allow silent coercion. Finally, if the types are 5766 // incompatible then make sure to use 'id' as the composite 5767 // type so the result is acceptable for sending messages to. 5768 5769 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5770 // It could return the composite type. 5771 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5772 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5773 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5774 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5775 } else if ((LHSTy->isObjCQualifiedIdType() || 5776 RHSTy->isObjCQualifiedIdType()) && 5777 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5778 // Need to handle "id<xx>" explicitly. 5779 // GCC allows qualified id and any Objective-C type to devolve to 5780 // id. Currently localizing to here until clear this should be 5781 // part of ObjCQualifiedIdTypesAreCompatible. 5782 compositeType = Context.getObjCIdType(); 5783 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5784 compositeType = Context.getObjCIdType(); 5785 } else if (!(compositeType = 5786 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5787 ; 5788 else { 5789 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5790 << LHSTy << RHSTy 5791 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5792 QualType incompatTy = Context.getObjCIdType(); 5793 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5794 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5795 return incompatTy; 5796 } 5797 // The object pointer types are compatible. 5798 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5799 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5800 return compositeType; 5801 } 5802 // Check Objective-C object pointer types and 'void *' 5803 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5804 if (getLangOpts().ObjCAutoRefCount) { 5805 // ARC forbids the implicit conversion of object pointers to 'void *', 5806 // so these types are not compatible. 5807 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5808 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5809 LHS = RHS = true; 5810 return QualType(); 5811 } 5812 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5813 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5814 QualType destPointee 5815 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5816 QualType destType = Context.getPointerType(destPointee); 5817 // Add qualifiers if necessary. 5818 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5819 // Promote to void*. 5820 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5821 return destType; 5822 } 5823 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5824 if (getLangOpts().ObjCAutoRefCount) { 5825 // ARC forbids the implicit conversion of object pointers to 'void *', 5826 // so these types are not compatible. 5827 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5828 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5829 LHS = RHS = true; 5830 return QualType(); 5831 } 5832 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5833 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5834 QualType destPointee 5835 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5836 QualType destType = Context.getPointerType(destPointee); 5837 // Add qualifiers if necessary. 5838 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5839 // Promote to void*. 5840 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5841 return destType; 5842 } 5843 return QualType(); 5844 } 5845 5846 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5847 /// ParenRange in parentheses. 5848 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5849 const PartialDiagnostic &Note, 5850 SourceRange ParenRange) { 5851 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5852 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5853 EndLoc.isValid()) { 5854 Self.Diag(Loc, Note) 5855 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5856 << FixItHint::CreateInsertion(EndLoc, ")"); 5857 } else { 5858 // We can't display the parentheses, so just show the bare note. 5859 Self.Diag(Loc, Note) << ParenRange; 5860 } 5861 } 5862 5863 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5864 return Opc >= BO_Mul && Opc <= BO_Shr; 5865 } 5866 5867 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5868 /// expression, either using a built-in or overloaded operator, 5869 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5870 /// expression. 5871 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5872 Expr **RHSExprs) { 5873 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5874 E = E->IgnoreImpCasts(); 5875 E = E->IgnoreConversionOperator(); 5876 E = E->IgnoreImpCasts(); 5877 5878 // Built-in binary operator. 5879 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5880 if (IsArithmeticOp(OP->getOpcode())) { 5881 *Opcode = OP->getOpcode(); 5882 *RHSExprs = OP->getRHS(); 5883 return true; 5884 } 5885 } 5886 5887 // Overloaded operator. 5888 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5889 if (Call->getNumArgs() != 2) 5890 return false; 5891 5892 // Make sure this is really a binary operator that is safe to pass into 5893 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5894 OverloadedOperatorKind OO = Call->getOperator(); 5895 if (OO < OO_Plus || OO > OO_Arrow || 5896 OO == OO_PlusPlus || OO == OO_MinusMinus) 5897 return false; 5898 5899 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5900 if (IsArithmeticOp(OpKind)) { 5901 *Opcode = OpKind; 5902 *RHSExprs = Call->getArg(1); 5903 return true; 5904 } 5905 } 5906 5907 return false; 5908 } 5909 5910 static bool IsLogicOp(BinaryOperatorKind Opc) { 5911 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5912 } 5913 5914 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5915 /// or is a logical expression such as (x==y) which has int type, but is 5916 /// commonly interpreted as boolean. 5917 static bool ExprLooksBoolean(Expr *E) { 5918 E = E->IgnoreParenImpCasts(); 5919 5920 if (E->getType()->isBooleanType()) 5921 return true; 5922 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5923 return IsLogicOp(OP->getOpcode()); 5924 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5925 return OP->getOpcode() == UO_LNot; 5926 5927 return false; 5928 } 5929 5930 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5931 /// and binary operator are mixed in a way that suggests the programmer assumed 5932 /// the conditional operator has higher precedence, for example: 5933 /// "int x = a + someBinaryCondition ? 1 : 2". 5934 static void DiagnoseConditionalPrecedence(Sema &Self, 5935 SourceLocation OpLoc, 5936 Expr *Condition, 5937 Expr *LHSExpr, 5938 Expr *RHSExpr) { 5939 BinaryOperatorKind CondOpcode; 5940 Expr *CondRHS; 5941 5942 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5943 return; 5944 if (!ExprLooksBoolean(CondRHS)) 5945 return; 5946 5947 // The condition is an arithmetic binary expression, with a right- 5948 // hand side that looks boolean, so warn. 5949 5950 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5951 << Condition->getSourceRange() 5952 << BinaryOperator::getOpcodeStr(CondOpcode); 5953 5954 SuggestParentheses(Self, OpLoc, 5955 Self.PDiag(diag::note_precedence_silence) 5956 << BinaryOperator::getOpcodeStr(CondOpcode), 5957 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5958 5959 SuggestParentheses(Self, OpLoc, 5960 Self.PDiag(diag::note_precedence_conditional_first), 5961 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5962 } 5963 5964 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5965 /// in the case of a the GNU conditional expr extension. 5966 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5967 SourceLocation ColonLoc, 5968 Expr *CondExpr, Expr *LHSExpr, 5969 Expr *RHSExpr) { 5970 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5971 // was the condition. 5972 OpaqueValueExpr *opaqueValue = 0; 5973 Expr *commonExpr = 0; 5974 if (LHSExpr == 0) { 5975 commonExpr = CondExpr; 5976 // Lower out placeholder types first. This is important so that we don't 5977 // try to capture a placeholder. This happens in few cases in C++; such 5978 // as Objective-C++'s dictionary subscripting syntax. 5979 if (commonExpr->hasPlaceholderType()) { 5980 ExprResult result = CheckPlaceholderExpr(commonExpr); 5981 if (!result.isUsable()) return ExprError(); 5982 commonExpr = result.take(); 5983 } 5984 // We usually want to apply unary conversions *before* saving, except 5985 // in the special case of a C++ l-value conditional. 5986 if (!(getLangOpts().CPlusPlus 5987 && !commonExpr->isTypeDependent() 5988 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5989 && commonExpr->isGLValue() 5990 && commonExpr->isOrdinaryOrBitFieldObject() 5991 && RHSExpr->isOrdinaryOrBitFieldObject() 5992 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5993 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5994 if (commonRes.isInvalid()) 5995 return ExprError(); 5996 commonExpr = commonRes.take(); 5997 } 5998 5999 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6000 commonExpr->getType(), 6001 commonExpr->getValueKind(), 6002 commonExpr->getObjectKind(), 6003 commonExpr); 6004 LHSExpr = CondExpr = opaqueValue; 6005 } 6006 6007 ExprValueKind VK = VK_RValue; 6008 ExprObjectKind OK = OK_Ordinary; 6009 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 6010 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6011 VK, OK, QuestionLoc); 6012 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6013 RHS.isInvalid()) 6014 return ExprError(); 6015 6016 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6017 RHS.get()); 6018 6019 if (!commonExpr) 6020 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 6021 LHS.take(), ColonLoc, 6022 RHS.take(), result, VK, OK)); 6023 6024 return Owned(new (Context) 6025 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 6026 RHS.take(), QuestionLoc, ColonLoc, result, VK, 6027 OK)); 6028 } 6029 6030 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6031 // being closely modeled after the C99 spec:-). The odd characteristic of this 6032 // routine is it effectively iqnores the qualifiers on the top level pointee. 6033 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6034 // FIXME: add a couple examples in this comment. 6035 static Sema::AssignConvertType 6036 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6037 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6038 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6039 6040 // get the "pointed to" type (ignoring qualifiers at the top level) 6041 const Type *lhptee, *rhptee; 6042 Qualifiers lhq, rhq; 6043 std::tie(lhptee, lhq) = 6044 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6045 std::tie(rhptee, rhq) = 6046 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6047 6048 Sema::AssignConvertType ConvTy = Sema::Compatible; 6049 6050 // C99 6.5.16.1p1: This following citation is common to constraints 6051 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6052 // qualifiers of the type *pointed to* by the right; 6053 6054 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6055 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6056 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6057 // Ignore lifetime for further calculation. 6058 lhq.removeObjCLifetime(); 6059 rhq.removeObjCLifetime(); 6060 } 6061 6062 if (!lhq.compatiblyIncludes(rhq)) { 6063 // Treat address-space mismatches as fatal. TODO: address subspaces 6064 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 6065 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6066 6067 // It's okay to add or remove GC or lifetime qualifiers when converting to 6068 // and from void*. 6069 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6070 .compatiblyIncludes( 6071 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6072 && (lhptee->isVoidType() || rhptee->isVoidType())) 6073 ; // keep old 6074 6075 // Treat lifetime mismatches as fatal. 6076 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6077 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6078 6079 // For GCC compatibility, other qualifier mismatches are treated 6080 // as still compatible in C. 6081 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6082 } 6083 6084 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6085 // incomplete type and the other is a pointer to a qualified or unqualified 6086 // version of void... 6087 if (lhptee->isVoidType()) { 6088 if (rhptee->isIncompleteOrObjectType()) 6089 return ConvTy; 6090 6091 // As an extension, we allow cast to/from void* to function pointer. 6092 assert(rhptee->isFunctionType()); 6093 return Sema::FunctionVoidPointer; 6094 } 6095 6096 if (rhptee->isVoidType()) { 6097 if (lhptee->isIncompleteOrObjectType()) 6098 return ConvTy; 6099 6100 // As an extension, we allow cast to/from void* to function pointer. 6101 assert(lhptee->isFunctionType()); 6102 return Sema::FunctionVoidPointer; 6103 } 6104 6105 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6106 // unqualified versions of compatible types, ... 6107 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6108 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6109 // Check if the pointee types are compatible ignoring the sign. 6110 // We explicitly check for char so that we catch "char" vs 6111 // "unsigned char" on systems where "char" is unsigned. 6112 if (lhptee->isCharType()) 6113 ltrans = S.Context.UnsignedCharTy; 6114 else if (lhptee->hasSignedIntegerRepresentation()) 6115 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6116 6117 if (rhptee->isCharType()) 6118 rtrans = S.Context.UnsignedCharTy; 6119 else if (rhptee->hasSignedIntegerRepresentation()) 6120 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6121 6122 if (ltrans == rtrans) { 6123 // Types are compatible ignoring the sign. Qualifier incompatibility 6124 // takes priority over sign incompatibility because the sign 6125 // warning can be disabled. 6126 if (ConvTy != Sema::Compatible) 6127 return ConvTy; 6128 6129 return Sema::IncompatiblePointerSign; 6130 } 6131 6132 // If we are a multi-level pointer, it's possible that our issue is simply 6133 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6134 // the eventual target type is the same and the pointers have the same 6135 // level of indirection, this must be the issue. 6136 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6137 do { 6138 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6139 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6140 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6141 6142 if (lhptee == rhptee) 6143 return Sema::IncompatibleNestedPointerQualifiers; 6144 } 6145 6146 // General pointer incompatibility takes priority over qualifiers. 6147 return Sema::IncompatiblePointer; 6148 } 6149 if (!S.getLangOpts().CPlusPlus && 6150 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6151 return Sema::IncompatiblePointer; 6152 return ConvTy; 6153 } 6154 6155 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6156 /// block pointer types are compatible or whether a block and normal pointer 6157 /// are compatible. It is more restrict than comparing two function pointer 6158 // types. 6159 static Sema::AssignConvertType 6160 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6161 QualType RHSType) { 6162 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6163 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6164 6165 QualType lhptee, rhptee; 6166 6167 // get the "pointed to" type (ignoring qualifiers at the top level) 6168 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6169 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6170 6171 // In C++, the types have to match exactly. 6172 if (S.getLangOpts().CPlusPlus) 6173 return Sema::IncompatibleBlockPointer; 6174 6175 Sema::AssignConvertType ConvTy = Sema::Compatible; 6176 6177 // For blocks we enforce that qualifiers are identical. 6178 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6179 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6180 6181 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6182 return Sema::IncompatibleBlockPointer; 6183 6184 return ConvTy; 6185 } 6186 6187 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6188 /// for assignment compatibility. 6189 static Sema::AssignConvertType 6190 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6191 QualType RHSType) { 6192 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6193 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6194 6195 if (LHSType->isObjCBuiltinType()) { 6196 // Class is not compatible with ObjC object pointers. 6197 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6198 !RHSType->isObjCQualifiedClassType()) 6199 return Sema::IncompatiblePointer; 6200 return Sema::Compatible; 6201 } 6202 if (RHSType->isObjCBuiltinType()) { 6203 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6204 !LHSType->isObjCQualifiedClassType()) 6205 return Sema::IncompatiblePointer; 6206 return Sema::Compatible; 6207 } 6208 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6209 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6210 6211 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6212 // make an exception for id<P> 6213 !LHSType->isObjCQualifiedIdType()) 6214 return Sema::CompatiblePointerDiscardsQualifiers; 6215 6216 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6217 return Sema::Compatible; 6218 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6219 return Sema::IncompatibleObjCQualifiedId; 6220 return Sema::IncompatiblePointer; 6221 } 6222 6223 Sema::AssignConvertType 6224 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6225 QualType LHSType, QualType RHSType) { 6226 // Fake up an opaque expression. We don't actually care about what 6227 // cast operations are required, so if CheckAssignmentConstraints 6228 // adds casts to this they'll be wasted, but fortunately that doesn't 6229 // usually happen on valid code. 6230 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6231 ExprResult RHSPtr = &RHSExpr; 6232 CastKind K = CK_Invalid; 6233 6234 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6235 } 6236 6237 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6238 /// has code to accommodate several GCC extensions when type checking 6239 /// pointers. Here are some objectionable examples that GCC considers warnings: 6240 /// 6241 /// int a, *pint; 6242 /// short *pshort; 6243 /// struct foo *pfoo; 6244 /// 6245 /// pint = pshort; // warning: assignment from incompatible pointer type 6246 /// a = pint; // warning: assignment makes integer from pointer without a cast 6247 /// pint = a; // warning: assignment makes pointer from integer without a cast 6248 /// pint = pfoo; // warning: assignment from incompatible pointer type 6249 /// 6250 /// As a result, the code for dealing with pointers is more complex than the 6251 /// C99 spec dictates. 6252 /// 6253 /// Sets 'Kind' for any result kind except Incompatible. 6254 Sema::AssignConvertType 6255 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6256 CastKind &Kind) { 6257 QualType RHSType = RHS.get()->getType(); 6258 QualType OrigLHSType = LHSType; 6259 6260 // Get canonical types. We're not formatting these types, just comparing 6261 // them. 6262 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6263 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6264 6265 // Common case: no conversion required. 6266 if (LHSType == RHSType) { 6267 Kind = CK_NoOp; 6268 return Compatible; 6269 } 6270 6271 // If we have an atomic type, try a non-atomic assignment, then just add an 6272 // atomic qualification step. 6273 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6274 Sema::AssignConvertType result = 6275 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6276 if (result != Compatible) 6277 return result; 6278 if (Kind != CK_NoOp) 6279 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 6280 Kind = CK_NonAtomicToAtomic; 6281 return Compatible; 6282 } 6283 6284 // If the left-hand side is a reference type, then we are in a 6285 // (rare!) case where we've allowed the use of references in C, 6286 // e.g., as a parameter type in a built-in function. In this case, 6287 // just make sure that the type referenced is compatible with the 6288 // right-hand side type. The caller is responsible for adjusting 6289 // LHSType so that the resulting expression does not have reference 6290 // type. 6291 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6292 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6293 Kind = CK_LValueBitCast; 6294 return Compatible; 6295 } 6296 return Incompatible; 6297 } 6298 6299 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6300 // to the same ExtVector type. 6301 if (LHSType->isExtVectorType()) { 6302 if (RHSType->isExtVectorType()) 6303 return Incompatible; 6304 if (RHSType->isArithmeticType()) { 6305 // CK_VectorSplat does T -> vector T, so first cast to the 6306 // element type. 6307 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6308 if (elType != RHSType) { 6309 Kind = PrepareScalarCast(RHS, elType); 6310 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 6311 } 6312 Kind = CK_VectorSplat; 6313 return Compatible; 6314 } 6315 } 6316 6317 // Conversions to or from vector type. 6318 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6319 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6320 // Allow assignments of an AltiVec vector type to an equivalent GCC 6321 // vector type and vice versa 6322 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6323 Kind = CK_BitCast; 6324 return Compatible; 6325 } 6326 6327 // If we are allowing lax vector conversions, and LHS and RHS are both 6328 // vectors, the total size only needs to be the same. This is a bitcast; 6329 // no bits are changed but the result type is different. 6330 if (isLaxVectorConversion(RHSType, LHSType)) { 6331 Kind = CK_BitCast; 6332 return IncompatibleVectors; 6333 } 6334 } 6335 return Incompatible; 6336 } 6337 6338 // Arithmetic conversions. 6339 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6340 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6341 Kind = PrepareScalarCast(RHS, LHSType); 6342 return Compatible; 6343 } 6344 6345 // Conversions to normal pointers. 6346 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6347 // U* -> T* 6348 if (isa<PointerType>(RHSType)) { 6349 Kind = CK_BitCast; 6350 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6351 } 6352 6353 // int -> T* 6354 if (RHSType->isIntegerType()) { 6355 Kind = CK_IntegralToPointer; // FIXME: null? 6356 return IntToPointer; 6357 } 6358 6359 // C pointers are not compatible with ObjC object pointers, 6360 // with two exceptions: 6361 if (isa<ObjCObjectPointerType>(RHSType)) { 6362 // - conversions to void* 6363 if (LHSPointer->getPointeeType()->isVoidType()) { 6364 Kind = CK_BitCast; 6365 return Compatible; 6366 } 6367 6368 // - conversions from 'Class' to the redefinition type 6369 if (RHSType->isObjCClassType() && 6370 Context.hasSameType(LHSType, 6371 Context.getObjCClassRedefinitionType())) { 6372 Kind = CK_BitCast; 6373 return Compatible; 6374 } 6375 6376 Kind = CK_BitCast; 6377 return IncompatiblePointer; 6378 } 6379 6380 // U^ -> void* 6381 if (RHSType->getAs<BlockPointerType>()) { 6382 if (LHSPointer->getPointeeType()->isVoidType()) { 6383 Kind = CK_BitCast; 6384 return Compatible; 6385 } 6386 } 6387 6388 return Incompatible; 6389 } 6390 6391 // Conversions to block pointers. 6392 if (isa<BlockPointerType>(LHSType)) { 6393 // U^ -> T^ 6394 if (RHSType->isBlockPointerType()) { 6395 Kind = CK_BitCast; 6396 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6397 } 6398 6399 // int or null -> T^ 6400 if (RHSType->isIntegerType()) { 6401 Kind = CK_IntegralToPointer; // FIXME: null 6402 return IntToBlockPointer; 6403 } 6404 6405 // id -> T^ 6406 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6407 Kind = CK_AnyPointerToBlockPointerCast; 6408 return Compatible; 6409 } 6410 6411 // void* -> T^ 6412 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6413 if (RHSPT->getPointeeType()->isVoidType()) { 6414 Kind = CK_AnyPointerToBlockPointerCast; 6415 return Compatible; 6416 } 6417 6418 return Incompatible; 6419 } 6420 6421 // Conversions to Objective-C pointers. 6422 if (isa<ObjCObjectPointerType>(LHSType)) { 6423 // A* -> B* 6424 if (RHSType->isObjCObjectPointerType()) { 6425 Kind = CK_BitCast; 6426 Sema::AssignConvertType result = 6427 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6428 if (getLangOpts().ObjCAutoRefCount && 6429 result == Compatible && 6430 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6431 result = IncompatibleObjCWeakRef; 6432 return result; 6433 } 6434 6435 // int or null -> A* 6436 if (RHSType->isIntegerType()) { 6437 Kind = CK_IntegralToPointer; // FIXME: null 6438 return IntToPointer; 6439 } 6440 6441 // In general, C pointers are not compatible with ObjC object pointers, 6442 // with two exceptions: 6443 if (isa<PointerType>(RHSType)) { 6444 Kind = CK_CPointerToObjCPointerCast; 6445 6446 // - conversions from 'void*' 6447 if (RHSType->isVoidPointerType()) { 6448 return Compatible; 6449 } 6450 6451 // - conversions to 'Class' from its redefinition type 6452 if (LHSType->isObjCClassType() && 6453 Context.hasSameType(RHSType, 6454 Context.getObjCClassRedefinitionType())) { 6455 return Compatible; 6456 } 6457 6458 return IncompatiblePointer; 6459 } 6460 6461 // T^ -> A* 6462 if (RHSType->isBlockPointerType()) { 6463 maybeExtendBlockObject(*this, RHS); 6464 Kind = CK_BlockPointerToObjCPointerCast; 6465 return Compatible; 6466 } 6467 6468 return Incompatible; 6469 } 6470 6471 // Conversions from pointers that are not covered by the above. 6472 if (isa<PointerType>(RHSType)) { 6473 // T* -> _Bool 6474 if (LHSType == Context.BoolTy) { 6475 Kind = CK_PointerToBoolean; 6476 return Compatible; 6477 } 6478 6479 // T* -> int 6480 if (LHSType->isIntegerType()) { 6481 Kind = CK_PointerToIntegral; 6482 return PointerToInt; 6483 } 6484 6485 return Incompatible; 6486 } 6487 6488 // Conversions from Objective-C pointers that are not covered by the above. 6489 if (isa<ObjCObjectPointerType>(RHSType)) { 6490 // T* -> _Bool 6491 if (LHSType == Context.BoolTy) { 6492 Kind = CK_PointerToBoolean; 6493 return Compatible; 6494 } 6495 6496 // T* -> int 6497 if (LHSType->isIntegerType()) { 6498 Kind = CK_PointerToIntegral; 6499 return PointerToInt; 6500 } 6501 6502 return Incompatible; 6503 } 6504 6505 // struct A -> struct B 6506 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6507 if (Context.typesAreCompatible(LHSType, RHSType)) { 6508 Kind = CK_NoOp; 6509 return Compatible; 6510 } 6511 } 6512 6513 return Incompatible; 6514 } 6515 6516 /// \brief Constructs a transparent union from an expression that is 6517 /// used to initialize the transparent union. 6518 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6519 ExprResult &EResult, QualType UnionType, 6520 FieldDecl *Field) { 6521 // Build an initializer list that designates the appropriate member 6522 // of the transparent union. 6523 Expr *E = EResult.take(); 6524 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6525 E, SourceLocation()); 6526 Initializer->setType(UnionType); 6527 Initializer->setInitializedFieldInUnion(Field); 6528 6529 // Build a compound literal constructing a value of the transparent 6530 // union type from this initializer list. 6531 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6532 EResult = S.Owned( 6533 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6534 VK_RValue, Initializer, false)); 6535 } 6536 6537 Sema::AssignConvertType 6538 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6539 ExprResult &RHS) { 6540 QualType RHSType = RHS.get()->getType(); 6541 6542 // If the ArgType is a Union type, we want to handle a potential 6543 // transparent_union GCC extension. 6544 const RecordType *UT = ArgType->getAsUnionType(); 6545 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6546 return Incompatible; 6547 6548 // The field to initialize within the transparent union. 6549 RecordDecl *UD = UT->getDecl(); 6550 FieldDecl *InitField = 0; 6551 // It's compatible if the expression matches any of the fields. 6552 for (auto *it : UD->fields()) { 6553 if (it->getType()->isPointerType()) { 6554 // If the transparent union contains a pointer type, we allow: 6555 // 1) void pointer 6556 // 2) null pointer constant 6557 if (RHSType->isPointerType()) 6558 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6559 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6560 InitField = it; 6561 break; 6562 } 6563 6564 if (RHS.get()->isNullPointerConstant(Context, 6565 Expr::NPC_ValueDependentIsNull)) { 6566 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6567 CK_NullToPointer); 6568 InitField = it; 6569 break; 6570 } 6571 } 6572 6573 CastKind Kind = CK_Invalid; 6574 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6575 == Compatible) { 6576 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6577 InitField = it; 6578 break; 6579 } 6580 } 6581 6582 if (!InitField) 6583 return Incompatible; 6584 6585 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6586 return Compatible; 6587 } 6588 6589 Sema::AssignConvertType 6590 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6591 bool Diagnose, 6592 bool DiagnoseCFAudited) { 6593 if (getLangOpts().CPlusPlus) { 6594 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6595 // C++ 5.17p3: If the left operand is not of class type, the 6596 // expression is implicitly converted (C++ 4) to the 6597 // cv-unqualified type of the left operand. 6598 ExprResult Res; 6599 if (Diagnose) { 6600 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6601 AA_Assigning); 6602 } else { 6603 ImplicitConversionSequence ICS = 6604 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6605 /*SuppressUserConversions=*/false, 6606 /*AllowExplicit=*/false, 6607 /*InOverloadResolution=*/false, 6608 /*CStyle=*/false, 6609 /*AllowObjCWritebackConversion=*/false); 6610 if (ICS.isFailure()) 6611 return Incompatible; 6612 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6613 ICS, AA_Assigning); 6614 } 6615 if (Res.isInvalid()) 6616 return Incompatible; 6617 Sema::AssignConvertType result = Compatible; 6618 if (getLangOpts().ObjCAutoRefCount && 6619 !CheckObjCARCUnavailableWeakConversion(LHSType, 6620 RHS.get()->getType())) 6621 result = IncompatibleObjCWeakRef; 6622 RHS = Res; 6623 return result; 6624 } 6625 6626 // FIXME: Currently, we fall through and treat C++ classes like C 6627 // structures. 6628 // FIXME: We also fall through for atomics; not sure what should 6629 // happen there, though. 6630 } 6631 6632 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6633 // a null pointer constant. 6634 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 6635 LHSType->isBlockPointerType()) && 6636 RHS.get()->isNullPointerConstant(Context, 6637 Expr::NPC_ValueDependentIsNull)) { 6638 CastKind Kind; 6639 CXXCastPath Path; 6640 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 6641 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path); 6642 return Compatible; 6643 } 6644 6645 // This check seems unnatural, however it is necessary to ensure the proper 6646 // conversion of functions/arrays. If the conversion were done for all 6647 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6648 // expressions that suppress this implicit conversion (&, sizeof). 6649 // 6650 // Suppress this for references: C++ 8.5.3p5. 6651 if (!LHSType->isReferenceType()) { 6652 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6653 if (RHS.isInvalid()) 6654 return Incompatible; 6655 } 6656 6657 CastKind Kind = CK_Invalid; 6658 Sema::AssignConvertType result = 6659 CheckAssignmentConstraints(LHSType, RHS, Kind); 6660 6661 // C99 6.5.16.1p2: The value of the right operand is converted to the 6662 // type of the assignment expression. 6663 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6664 // so that we can use references in built-in functions even in C. 6665 // The getNonReferenceType() call makes sure that the resulting expression 6666 // does not have reference type. 6667 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6668 QualType Ty = LHSType.getNonLValueExprType(Context); 6669 Expr *E = RHS.take(); 6670 if (getLangOpts().ObjCAutoRefCount) 6671 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6672 DiagnoseCFAudited); 6673 if (getLangOpts().ObjC1 && 6674 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 6675 LHSType, E->getType(), E) || 6676 ConversionToObjCStringLiteralCheck(LHSType, E))) { 6677 RHS = Owned(E); 6678 return Compatible; 6679 } 6680 6681 RHS = ImpCastExprToType(E, Ty, Kind); 6682 } 6683 return result; 6684 } 6685 6686 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6687 ExprResult &RHS) { 6688 Diag(Loc, diag::err_typecheck_invalid_operands) 6689 << LHS.get()->getType() << RHS.get()->getType() 6690 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6691 return QualType(); 6692 } 6693 6694 /// Try to convert a value of non-vector type to a vector type by converting 6695 /// the type to the element type of the vector and then performing a splat. 6696 /// If the language is OpenCL, we only use conversions that promote scalar 6697 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 6698 /// for float->int. 6699 /// 6700 /// \param scalar - if non-null, actually perform the conversions 6701 /// \return true if the operation fails (but without diagnosing the failure) 6702 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 6703 QualType scalarTy, 6704 QualType vectorEltTy, 6705 QualType vectorTy) { 6706 // The conversion to apply to the scalar before splatting it, 6707 // if necessary. 6708 CastKind scalarCast = CK_Invalid; 6709 6710 if (vectorEltTy->isIntegralType(S.Context)) { 6711 if (!scalarTy->isIntegralType(S.Context)) 6712 return true; 6713 if (S.getLangOpts().OpenCL && 6714 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 6715 return true; 6716 scalarCast = CK_IntegralCast; 6717 } else if (vectorEltTy->isRealFloatingType()) { 6718 if (scalarTy->isRealFloatingType()) { 6719 if (S.getLangOpts().OpenCL && 6720 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 6721 return true; 6722 scalarCast = CK_FloatingCast; 6723 } 6724 else if (scalarTy->isIntegralType(S.Context)) 6725 scalarCast = CK_IntegralToFloating; 6726 else 6727 return true; 6728 } else { 6729 return true; 6730 } 6731 6732 // Adjust scalar if desired. 6733 if (scalar) { 6734 if (scalarCast != CK_Invalid) 6735 *scalar = S.ImpCastExprToType(scalar->take(), vectorEltTy, scalarCast); 6736 *scalar = S.ImpCastExprToType(scalar->take(), vectorTy, CK_VectorSplat); 6737 } 6738 return false; 6739 } 6740 6741 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6742 SourceLocation Loc, bool IsCompAssign) { 6743 if (!IsCompAssign) { 6744 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6745 if (LHS.isInvalid()) 6746 return QualType(); 6747 } 6748 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6749 if (RHS.isInvalid()) 6750 return QualType(); 6751 6752 // For conversion purposes, we ignore any qualifiers. 6753 // For example, "const float" and "float" are equivalent. 6754 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 6755 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 6756 6757 // If the vector types are identical, return. 6758 if (Context.hasSameType(LHSType, RHSType)) 6759 return LHSType; 6760 6761 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 6762 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 6763 assert(LHSVecType || RHSVecType); 6764 6765 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 6766 if (LHSVecType && RHSVecType && 6767 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6768 if (isa<ExtVectorType>(LHSVecType)) { 6769 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6770 return LHSType; 6771 } 6772 6773 if (!IsCompAssign) 6774 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6775 return RHSType; 6776 } 6777 6778 // If there's an ext-vector type and a scalar, try to convert the scalar to 6779 // the vector element type and splat. 6780 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 6781 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 6782 LHSVecType->getElementType(), LHSType)) 6783 return LHSType; 6784 } 6785 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 6786 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? 0 : &LHS), LHSType, 6787 RHSVecType->getElementType(), RHSType)) 6788 return RHSType; 6789 } 6790 6791 // If we're allowing lax vector conversions, only the total (data) size 6792 // needs to be the same. 6793 // FIXME: Should we really be allowing this? 6794 // FIXME: We really just pick the LHS type arbitrarily? 6795 if (isLaxVectorConversion(RHSType, LHSType)) { 6796 QualType resultType = LHSType; 6797 RHS = ImpCastExprToType(RHS.take(), resultType, CK_BitCast); 6798 return resultType; 6799 } 6800 6801 // Okay, the expression is invalid. 6802 6803 // If there's a non-vector, non-real operand, diagnose that. 6804 if ((!RHSVecType && !RHSType->isRealType()) || 6805 (!LHSVecType && !LHSType->isRealType())) { 6806 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 6807 << LHSType << RHSType 6808 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6809 return QualType(); 6810 } 6811 6812 // Otherwise, use the generic diagnostic. 6813 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6814 << LHSType << RHSType 6815 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6816 return QualType(); 6817 } 6818 6819 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6820 // expression. These are mainly cases where the null pointer is used as an 6821 // integer instead of a pointer. 6822 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6823 SourceLocation Loc, bool IsCompare) { 6824 // The canonical way to check for a GNU null is with isNullPointerConstant, 6825 // but we use a bit of a hack here for speed; this is a relatively 6826 // hot path, and isNullPointerConstant is slow. 6827 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6828 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6829 6830 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6831 6832 // Avoid analyzing cases where the result will either be invalid (and 6833 // diagnosed as such) or entirely valid and not something to warn about. 6834 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6835 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6836 return; 6837 6838 // Comparison operations would not make sense with a null pointer no matter 6839 // what the other expression is. 6840 if (!IsCompare) { 6841 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6842 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6843 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6844 return; 6845 } 6846 6847 // The rest of the operations only make sense with a null pointer 6848 // if the other expression is a pointer. 6849 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6850 NonNullType->canDecayToPointerType()) 6851 return; 6852 6853 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6854 << LHSNull /* LHS is NULL */ << NonNullType 6855 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6856 } 6857 6858 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6859 SourceLocation Loc, 6860 bool IsCompAssign, bool IsDiv) { 6861 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6862 6863 if (LHS.get()->getType()->isVectorType() || 6864 RHS.get()->getType()->isVectorType()) 6865 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6866 6867 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6868 if (LHS.isInvalid() || RHS.isInvalid()) 6869 return QualType(); 6870 6871 6872 if (compType.isNull() || !compType->isArithmeticType()) 6873 return InvalidOperands(Loc, LHS, RHS); 6874 6875 // Check for division by zero. 6876 llvm::APSInt RHSValue; 6877 if (IsDiv && !RHS.get()->isValueDependent() && 6878 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6879 DiagRuntimeBehavior(Loc, RHS.get(), 6880 PDiag(diag::warn_division_by_zero) 6881 << RHS.get()->getSourceRange()); 6882 6883 return compType; 6884 } 6885 6886 QualType Sema::CheckRemainderOperands( 6887 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6888 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6889 6890 if (LHS.get()->getType()->isVectorType() || 6891 RHS.get()->getType()->isVectorType()) { 6892 if (LHS.get()->getType()->hasIntegerRepresentation() && 6893 RHS.get()->getType()->hasIntegerRepresentation()) 6894 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6895 return InvalidOperands(Loc, LHS, RHS); 6896 } 6897 6898 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6899 if (LHS.isInvalid() || RHS.isInvalid()) 6900 return QualType(); 6901 6902 if (compType.isNull() || !compType->isIntegerType()) 6903 return InvalidOperands(Loc, LHS, RHS); 6904 6905 // Check for remainder by zero. 6906 llvm::APSInt RHSValue; 6907 if (!RHS.get()->isValueDependent() && 6908 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6909 DiagRuntimeBehavior(Loc, RHS.get(), 6910 PDiag(diag::warn_remainder_by_zero) 6911 << RHS.get()->getSourceRange()); 6912 6913 return compType; 6914 } 6915 6916 /// \brief Diagnose invalid arithmetic on two void pointers. 6917 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6918 Expr *LHSExpr, Expr *RHSExpr) { 6919 S.Diag(Loc, S.getLangOpts().CPlusPlus 6920 ? diag::err_typecheck_pointer_arith_void_type 6921 : diag::ext_gnu_void_ptr) 6922 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6923 << RHSExpr->getSourceRange(); 6924 } 6925 6926 /// \brief Diagnose invalid arithmetic on a void pointer. 6927 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6928 Expr *Pointer) { 6929 S.Diag(Loc, S.getLangOpts().CPlusPlus 6930 ? diag::err_typecheck_pointer_arith_void_type 6931 : diag::ext_gnu_void_ptr) 6932 << 0 /* one pointer */ << Pointer->getSourceRange(); 6933 } 6934 6935 /// \brief Diagnose invalid arithmetic on two function pointers. 6936 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6937 Expr *LHS, Expr *RHS) { 6938 assert(LHS->getType()->isAnyPointerType()); 6939 assert(RHS->getType()->isAnyPointerType()); 6940 S.Diag(Loc, S.getLangOpts().CPlusPlus 6941 ? diag::err_typecheck_pointer_arith_function_type 6942 : diag::ext_gnu_ptr_func_arith) 6943 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6944 // We only show the second type if it differs from the first. 6945 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6946 RHS->getType()) 6947 << RHS->getType()->getPointeeType() 6948 << LHS->getSourceRange() << RHS->getSourceRange(); 6949 } 6950 6951 /// \brief Diagnose invalid arithmetic on a function pointer. 6952 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6953 Expr *Pointer) { 6954 assert(Pointer->getType()->isAnyPointerType()); 6955 S.Diag(Loc, S.getLangOpts().CPlusPlus 6956 ? diag::err_typecheck_pointer_arith_function_type 6957 : diag::ext_gnu_ptr_func_arith) 6958 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6959 << 0 /* one pointer, so only one type */ 6960 << Pointer->getSourceRange(); 6961 } 6962 6963 /// \brief Emit error if Operand is incomplete pointer type 6964 /// 6965 /// \returns True if pointer has incomplete type 6966 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6967 Expr *Operand) { 6968 assert(Operand->getType()->isAnyPointerType() && 6969 !Operand->getType()->isDependentType()); 6970 QualType PointeeTy = Operand->getType()->getPointeeType(); 6971 return S.RequireCompleteType(Loc, PointeeTy, 6972 diag::err_typecheck_arithmetic_incomplete_type, 6973 PointeeTy, Operand->getSourceRange()); 6974 } 6975 6976 /// \brief Check the validity of an arithmetic pointer operand. 6977 /// 6978 /// If the operand has pointer type, this code will check for pointer types 6979 /// which are invalid in arithmetic operations. These will be diagnosed 6980 /// appropriately, including whether or not the use is supported as an 6981 /// extension. 6982 /// 6983 /// \returns True when the operand is valid to use (even if as an extension). 6984 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6985 Expr *Operand) { 6986 if (!Operand->getType()->isAnyPointerType()) return true; 6987 6988 QualType PointeeTy = Operand->getType()->getPointeeType(); 6989 if (PointeeTy->isVoidType()) { 6990 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6991 return !S.getLangOpts().CPlusPlus; 6992 } 6993 if (PointeeTy->isFunctionType()) { 6994 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6995 return !S.getLangOpts().CPlusPlus; 6996 } 6997 6998 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6999 7000 return true; 7001 } 7002 7003 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7004 /// operands. 7005 /// 7006 /// This routine will diagnose any invalid arithmetic on pointer operands much 7007 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7008 /// for emitting a single diagnostic even for operations where both LHS and RHS 7009 /// are (potentially problematic) pointers. 7010 /// 7011 /// \returns True when the operand is valid to use (even if as an extension). 7012 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7013 Expr *LHSExpr, Expr *RHSExpr) { 7014 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7015 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7016 if (!isLHSPointer && !isRHSPointer) return true; 7017 7018 QualType LHSPointeeTy, RHSPointeeTy; 7019 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7020 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7021 7022 // Check for arithmetic on pointers to incomplete types. 7023 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7024 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7025 if (isLHSVoidPtr || isRHSVoidPtr) { 7026 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7027 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7028 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7029 7030 return !S.getLangOpts().CPlusPlus; 7031 } 7032 7033 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7034 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7035 if (isLHSFuncPtr || isRHSFuncPtr) { 7036 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7037 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7038 RHSExpr); 7039 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7040 7041 return !S.getLangOpts().CPlusPlus; 7042 } 7043 7044 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7045 return false; 7046 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7047 return false; 7048 7049 return true; 7050 } 7051 7052 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7053 /// literal. 7054 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7055 Expr *LHSExpr, Expr *RHSExpr) { 7056 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7057 Expr* IndexExpr = RHSExpr; 7058 if (!StrExpr) { 7059 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7060 IndexExpr = LHSExpr; 7061 } 7062 7063 bool IsStringPlusInt = StrExpr && 7064 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7065 if (!IsStringPlusInt) 7066 return; 7067 7068 llvm::APSInt index; 7069 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7070 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7071 if (index.isNonNegative() && 7072 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7073 index.isUnsigned())) 7074 return; 7075 } 7076 7077 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7078 Self.Diag(OpLoc, diag::warn_string_plus_int) 7079 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7080 7081 // Only print a fixit for "str" + int, not for int + "str". 7082 if (IndexExpr == RHSExpr) { 7083 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7084 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7085 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7086 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7087 << FixItHint::CreateInsertion(EndLoc, "]"); 7088 } else 7089 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7090 } 7091 7092 /// \brief Emit a warning when adding a char literal to a string. 7093 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7094 Expr *LHSExpr, Expr *RHSExpr) { 7095 const DeclRefExpr *StringRefExpr = 7096 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts()); 7097 const CharacterLiteral *CharExpr = 7098 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7099 if (!StringRefExpr) { 7100 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts()); 7101 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7102 } 7103 7104 if (!CharExpr || !StringRefExpr) 7105 return; 7106 7107 const QualType StringType = StringRefExpr->getType(); 7108 7109 // Return if not a PointerType. 7110 if (!StringType->isAnyPointerType()) 7111 return; 7112 7113 // Return if not a CharacterType. 7114 if (!StringType->getPointeeType()->isAnyCharacterType()) 7115 return; 7116 7117 ASTContext &Ctx = Self.getASTContext(); 7118 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7119 7120 const QualType CharType = CharExpr->getType(); 7121 if (!CharType->isAnyCharacterType() && 7122 CharType->isIntegerType() && 7123 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7124 Self.Diag(OpLoc, diag::warn_string_plus_char) 7125 << DiagRange << Ctx.CharTy; 7126 } else { 7127 Self.Diag(OpLoc, diag::warn_string_plus_char) 7128 << DiagRange << CharExpr->getType(); 7129 } 7130 7131 // Only print a fixit for str + char, not for char + str. 7132 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7133 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7134 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7135 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7136 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7137 << FixItHint::CreateInsertion(EndLoc, "]"); 7138 } else { 7139 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7140 } 7141 } 7142 7143 /// \brief Emit error when two pointers are incompatible. 7144 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7145 Expr *LHSExpr, Expr *RHSExpr) { 7146 assert(LHSExpr->getType()->isAnyPointerType()); 7147 assert(RHSExpr->getType()->isAnyPointerType()); 7148 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7149 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7150 << RHSExpr->getSourceRange(); 7151 } 7152 7153 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7154 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7155 QualType* CompLHSTy) { 7156 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7157 7158 if (LHS.get()->getType()->isVectorType() || 7159 RHS.get()->getType()->isVectorType()) { 7160 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7161 if (CompLHSTy) *CompLHSTy = compType; 7162 return compType; 7163 } 7164 7165 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7166 if (LHS.isInvalid() || RHS.isInvalid()) 7167 return QualType(); 7168 7169 // Diagnose "string literal" '+' int and string '+' "char literal". 7170 if (Opc == BO_Add) { 7171 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7172 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7173 } 7174 7175 // handle the common case first (both operands are arithmetic). 7176 if (!compType.isNull() && compType->isArithmeticType()) { 7177 if (CompLHSTy) *CompLHSTy = compType; 7178 return compType; 7179 } 7180 7181 // Type-checking. Ultimately the pointer's going to be in PExp; 7182 // note that we bias towards the LHS being the pointer. 7183 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7184 7185 bool isObjCPointer; 7186 if (PExp->getType()->isPointerType()) { 7187 isObjCPointer = false; 7188 } else if (PExp->getType()->isObjCObjectPointerType()) { 7189 isObjCPointer = true; 7190 } else { 7191 std::swap(PExp, IExp); 7192 if (PExp->getType()->isPointerType()) { 7193 isObjCPointer = false; 7194 } else if (PExp->getType()->isObjCObjectPointerType()) { 7195 isObjCPointer = true; 7196 } else { 7197 return InvalidOperands(Loc, LHS, RHS); 7198 } 7199 } 7200 assert(PExp->getType()->isAnyPointerType()); 7201 7202 if (!IExp->getType()->isIntegerType()) 7203 return InvalidOperands(Loc, LHS, RHS); 7204 7205 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7206 return QualType(); 7207 7208 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7209 return QualType(); 7210 7211 // Check array bounds for pointer arithemtic 7212 CheckArrayAccess(PExp, IExp); 7213 7214 if (CompLHSTy) { 7215 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7216 if (LHSTy.isNull()) { 7217 LHSTy = LHS.get()->getType(); 7218 if (LHSTy->isPromotableIntegerType()) 7219 LHSTy = Context.getPromotedIntegerType(LHSTy); 7220 } 7221 *CompLHSTy = LHSTy; 7222 } 7223 7224 return PExp->getType(); 7225 } 7226 7227 // C99 6.5.6 7228 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7229 SourceLocation Loc, 7230 QualType* CompLHSTy) { 7231 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7232 7233 if (LHS.get()->getType()->isVectorType() || 7234 RHS.get()->getType()->isVectorType()) { 7235 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7236 if (CompLHSTy) *CompLHSTy = compType; 7237 return compType; 7238 } 7239 7240 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7241 if (LHS.isInvalid() || RHS.isInvalid()) 7242 return QualType(); 7243 7244 // Enforce type constraints: C99 6.5.6p3. 7245 7246 // Handle the common case first (both operands are arithmetic). 7247 if (!compType.isNull() && compType->isArithmeticType()) { 7248 if (CompLHSTy) *CompLHSTy = compType; 7249 return compType; 7250 } 7251 7252 // Either ptr - int or ptr - ptr. 7253 if (LHS.get()->getType()->isAnyPointerType()) { 7254 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7255 7256 // Diagnose bad cases where we step over interface counts. 7257 if (LHS.get()->getType()->isObjCObjectPointerType() && 7258 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7259 return QualType(); 7260 7261 // The result type of a pointer-int computation is the pointer type. 7262 if (RHS.get()->getType()->isIntegerType()) { 7263 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7264 return QualType(); 7265 7266 // Check array bounds for pointer arithemtic 7267 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 7268 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7269 7270 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7271 return LHS.get()->getType(); 7272 } 7273 7274 // Handle pointer-pointer subtractions. 7275 if (const PointerType *RHSPTy 7276 = RHS.get()->getType()->getAs<PointerType>()) { 7277 QualType rpointee = RHSPTy->getPointeeType(); 7278 7279 if (getLangOpts().CPlusPlus) { 7280 // Pointee types must be the same: C++ [expr.add] 7281 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7282 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7283 } 7284 } else { 7285 // Pointee types must be compatible C99 6.5.6p3 7286 if (!Context.typesAreCompatible( 7287 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7288 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7289 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7290 return QualType(); 7291 } 7292 } 7293 7294 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7295 LHS.get(), RHS.get())) 7296 return QualType(); 7297 7298 // The pointee type may have zero size. As an extension, a structure or 7299 // union may have zero size or an array may have zero length. In this 7300 // case subtraction does not make sense. 7301 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7302 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7303 if (ElementSize.isZero()) { 7304 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7305 << rpointee.getUnqualifiedType() 7306 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7307 } 7308 } 7309 7310 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7311 return Context.getPointerDiffType(); 7312 } 7313 } 7314 7315 return InvalidOperands(Loc, LHS, RHS); 7316 } 7317 7318 static bool isScopedEnumerationType(QualType T) { 7319 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7320 return ET->getDecl()->isScoped(); 7321 return false; 7322 } 7323 7324 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7325 SourceLocation Loc, unsigned Opc, 7326 QualType LHSType) { 7327 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7328 // so skip remaining warnings as we don't want to modify values within Sema. 7329 if (S.getLangOpts().OpenCL) 7330 return; 7331 7332 llvm::APSInt Right; 7333 // Check right/shifter operand 7334 if (RHS.get()->isValueDependent() || 7335 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7336 return; 7337 7338 if (Right.isNegative()) { 7339 S.DiagRuntimeBehavior(Loc, RHS.get(), 7340 S.PDiag(diag::warn_shift_negative) 7341 << RHS.get()->getSourceRange()); 7342 return; 7343 } 7344 llvm::APInt LeftBits(Right.getBitWidth(), 7345 S.Context.getTypeSize(LHS.get()->getType())); 7346 if (Right.uge(LeftBits)) { 7347 S.DiagRuntimeBehavior(Loc, RHS.get(), 7348 S.PDiag(diag::warn_shift_gt_typewidth) 7349 << RHS.get()->getSourceRange()); 7350 return; 7351 } 7352 if (Opc != BO_Shl) 7353 return; 7354 7355 // When left shifting an ICE which is signed, we can check for overflow which 7356 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7357 // integers have defined behavior modulo one more than the maximum value 7358 // representable in the result type, so never warn for those. 7359 llvm::APSInt Left; 7360 if (LHS.get()->isValueDependent() || 7361 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7362 LHSType->hasUnsignedIntegerRepresentation()) 7363 return; 7364 llvm::APInt ResultBits = 7365 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7366 if (LeftBits.uge(ResultBits)) 7367 return; 7368 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7369 Result = Result.shl(Right); 7370 7371 // Print the bit representation of the signed integer as an unsigned 7372 // hexadecimal number. 7373 SmallString<40> HexResult; 7374 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7375 7376 // If we are only missing a sign bit, this is less likely to result in actual 7377 // bugs -- if the result is cast back to an unsigned type, it will have the 7378 // expected value. Thus we place this behind a different warning that can be 7379 // turned off separately if needed. 7380 if (LeftBits == ResultBits - 1) { 7381 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7382 << HexResult.str() << LHSType 7383 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7384 return; 7385 } 7386 7387 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7388 << HexResult.str() << Result.getMinSignedBits() << LHSType 7389 << Left.getBitWidth() << LHS.get()->getSourceRange() 7390 << RHS.get()->getSourceRange(); 7391 } 7392 7393 // C99 6.5.7 7394 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7395 SourceLocation Loc, unsigned Opc, 7396 bool IsCompAssign) { 7397 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7398 7399 // Vector shifts promote their scalar inputs to vector type. 7400 if (LHS.get()->getType()->isVectorType() || 7401 RHS.get()->getType()->isVectorType()) 7402 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7403 7404 // Shifts don't perform usual arithmetic conversions, they just do integer 7405 // promotions on each operand. C99 6.5.7p3 7406 7407 // For the LHS, do usual unary conversions, but then reset them away 7408 // if this is a compound assignment. 7409 ExprResult OldLHS = LHS; 7410 LHS = UsualUnaryConversions(LHS.take()); 7411 if (LHS.isInvalid()) 7412 return QualType(); 7413 QualType LHSType = LHS.get()->getType(); 7414 if (IsCompAssign) LHS = OldLHS; 7415 7416 // The RHS is simpler. 7417 RHS = UsualUnaryConversions(RHS.take()); 7418 if (RHS.isInvalid()) 7419 return QualType(); 7420 QualType RHSType = RHS.get()->getType(); 7421 7422 // C99 6.5.7p2: Each of the operands shall have integer type. 7423 if (!LHSType->hasIntegerRepresentation() || 7424 !RHSType->hasIntegerRepresentation()) 7425 return InvalidOperands(Loc, LHS, RHS); 7426 7427 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7428 // hasIntegerRepresentation() above instead of this. 7429 if (isScopedEnumerationType(LHSType) || 7430 isScopedEnumerationType(RHSType)) { 7431 return InvalidOperands(Loc, LHS, RHS); 7432 } 7433 // Sanity-check shift operands 7434 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7435 7436 // "The type of the result is that of the promoted left operand." 7437 return LHSType; 7438 } 7439 7440 static bool IsWithinTemplateSpecialization(Decl *D) { 7441 if (DeclContext *DC = D->getDeclContext()) { 7442 if (isa<ClassTemplateSpecializationDecl>(DC)) 7443 return true; 7444 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7445 return FD->isFunctionTemplateSpecialization(); 7446 } 7447 return false; 7448 } 7449 7450 /// If two different enums are compared, raise a warning. 7451 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7452 Expr *RHS) { 7453 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7454 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7455 7456 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7457 if (!LHSEnumType) 7458 return; 7459 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7460 if (!RHSEnumType) 7461 return; 7462 7463 // Ignore anonymous enums. 7464 if (!LHSEnumType->getDecl()->getIdentifier()) 7465 return; 7466 if (!RHSEnumType->getDecl()->getIdentifier()) 7467 return; 7468 7469 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7470 return; 7471 7472 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7473 << LHSStrippedType << RHSStrippedType 7474 << LHS->getSourceRange() << RHS->getSourceRange(); 7475 } 7476 7477 /// \brief Diagnose bad pointer comparisons. 7478 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7479 ExprResult &LHS, ExprResult &RHS, 7480 bool IsError) { 7481 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7482 : diag::ext_typecheck_comparison_of_distinct_pointers) 7483 << LHS.get()->getType() << RHS.get()->getType() 7484 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7485 } 7486 7487 /// \brief Returns false if the pointers are converted to a composite type, 7488 /// true otherwise. 7489 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7490 ExprResult &LHS, ExprResult &RHS) { 7491 // C++ [expr.rel]p2: 7492 // [...] Pointer conversions (4.10) and qualification 7493 // conversions (4.4) are performed on pointer operands (or on 7494 // a pointer operand and a null pointer constant) to bring 7495 // them to their composite pointer type. [...] 7496 // 7497 // C++ [expr.eq]p1 uses the same notion for (in)equality 7498 // comparisons of pointers. 7499 7500 // C++ [expr.eq]p2: 7501 // In addition, pointers to members can be compared, or a pointer to 7502 // member and a null pointer constant. Pointer to member conversions 7503 // (4.11) and qualification conversions (4.4) are performed to bring 7504 // them to a common type. If one operand is a null pointer constant, 7505 // the common type is the type of the other operand. Otherwise, the 7506 // common type is a pointer to member type similar (4.4) to the type 7507 // of one of the operands, with a cv-qualification signature (4.4) 7508 // that is the union of the cv-qualification signatures of the operand 7509 // types. 7510 7511 QualType LHSType = LHS.get()->getType(); 7512 QualType RHSType = RHS.get()->getType(); 7513 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7514 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7515 7516 bool NonStandardCompositeType = false; 7517 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7518 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7519 if (T.isNull()) { 7520 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7521 return true; 7522 } 7523 7524 if (NonStandardCompositeType) 7525 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7526 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7527 << RHS.get()->getSourceRange(); 7528 7529 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7530 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7531 return false; 7532 } 7533 7534 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7535 ExprResult &LHS, 7536 ExprResult &RHS, 7537 bool IsError) { 7538 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7539 : diag::ext_typecheck_comparison_of_fptr_to_void) 7540 << LHS.get()->getType() << RHS.get()->getType() 7541 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7542 } 7543 7544 static bool isObjCObjectLiteral(ExprResult &E) { 7545 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7546 case Stmt::ObjCArrayLiteralClass: 7547 case Stmt::ObjCDictionaryLiteralClass: 7548 case Stmt::ObjCStringLiteralClass: 7549 case Stmt::ObjCBoxedExprClass: 7550 return true; 7551 default: 7552 // Note that ObjCBoolLiteral is NOT an object literal! 7553 return false; 7554 } 7555 } 7556 7557 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7558 const ObjCObjectPointerType *Type = 7559 LHS->getType()->getAs<ObjCObjectPointerType>(); 7560 7561 // If this is not actually an Objective-C object, bail out. 7562 if (!Type) 7563 return false; 7564 7565 // Get the LHS object's interface type. 7566 QualType InterfaceType = Type->getPointeeType(); 7567 if (const ObjCObjectType *iQFaceTy = 7568 InterfaceType->getAsObjCQualifiedInterfaceType()) 7569 InterfaceType = iQFaceTy->getBaseType(); 7570 7571 // If the RHS isn't an Objective-C object, bail out. 7572 if (!RHS->getType()->isObjCObjectPointerType()) 7573 return false; 7574 7575 // Try to find the -isEqual: method. 7576 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7577 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7578 InterfaceType, 7579 /*instance=*/true); 7580 if (!Method) { 7581 if (Type->isObjCIdType()) { 7582 // For 'id', just check the global pool. 7583 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7584 /*receiverId=*/true, 7585 /*warn=*/false); 7586 } else { 7587 // Check protocols. 7588 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7589 /*instance=*/true); 7590 } 7591 } 7592 7593 if (!Method) 7594 return false; 7595 7596 QualType T = Method->param_begin()[0]->getType(); 7597 if (!T->isObjCObjectPointerType()) 7598 return false; 7599 7600 QualType R = Method->getReturnType(); 7601 if (!R->isScalarType()) 7602 return false; 7603 7604 return true; 7605 } 7606 7607 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7608 FromE = FromE->IgnoreParenImpCasts(); 7609 switch (FromE->getStmtClass()) { 7610 default: 7611 break; 7612 case Stmt::ObjCStringLiteralClass: 7613 // "string literal" 7614 return LK_String; 7615 case Stmt::ObjCArrayLiteralClass: 7616 // "array literal" 7617 return LK_Array; 7618 case Stmt::ObjCDictionaryLiteralClass: 7619 // "dictionary literal" 7620 return LK_Dictionary; 7621 case Stmt::BlockExprClass: 7622 return LK_Block; 7623 case Stmt::ObjCBoxedExprClass: { 7624 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7625 switch (Inner->getStmtClass()) { 7626 case Stmt::IntegerLiteralClass: 7627 case Stmt::FloatingLiteralClass: 7628 case Stmt::CharacterLiteralClass: 7629 case Stmt::ObjCBoolLiteralExprClass: 7630 case Stmt::CXXBoolLiteralExprClass: 7631 // "numeric literal" 7632 return LK_Numeric; 7633 case Stmt::ImplicitCastExprClass: { 7634 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7635 // Boolean literals can be represented by implicit casts. 7636 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7637 return LK_Numeric; 7638 break; 7639 } 7640 default: 7641 break; 7642 } 7643 return LK_Boxed; 7644 } 7645 } 7646 return LK_None; 7647 } 7648 7649 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7650 ExprResult &LHS, ExprResult &RHS, 7651 BinaryOperator::Opcode Opc){ 7652 Expr *Literal; 7653 Expr *Other; 7654 if (isObjCObjectLiteral(LHS)) { 7655 Literal = LHS.get(); 7656 Other = RHS.get(); 7657 } else { 7658 Literal = RHS.get(); 7659 Other = LHS.get(); 7660 } 7661 7662 // Don't warn on comparisons against nil. 7663 Other = Other->IgnoreParenCasts(); 7664 if (Other->isNullPointerConstant(S.getASTContext(), 7665 Expr::NPC_ValueDependentIsNotNull)) 7666 return; 7667 7668 // This should be kept in sync with warn_objc_literal_comparison. 7669 // LK_String should always be after the other literals, since it has its own 7670 // warning flag. 7671 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7672 assert(LiteralKind != Sema::LK_Block); 7673 if (LiteralKind == Sema::LK_None) { 7674 llvm_unreachable("Unknown Objective-C object literal kind"); 7675 } 7676 7677 if (LiteralKind == Sema::LK_String) 7678 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7679 << Literal->getSourceRange(); 7680 else 7681 S.Diag(Loc, diag::warn_objc_literal_comparison) 7682 << LiteralKind << Literal->getSourceRange(); 7683 7684 if (BinaryOperator::isEqualityOp(Opc) && 7685 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7686 SourceLocation Start = LHS.get()->getLocStart(); 7687 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7688 CharSourceRange OpRange = 7689 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7690 7691 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7692 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7693 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7694 << FixItHint::CreateInsertion(End, "]"); 7695 } 7696 } 7697 7698 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7699 ExprResult &RHS, 7700 SourceLocation Loc, 7701 unsigned OpaqueOpc) { 7702 // This checking requires bools. 7703 if (!S.getLangOpts().Bool) return; 7704 7705 // Check that left hand side is !something. 7706 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7707 if (!UO || UO->getOpcode() != UO_LNot) return; 7708 7709 // Only check if the right hand side is non-bool arithmetic type. 7710 if (RHS.get()->getType()->isBooleanType()) return; 7711 7712 // Make sure that the something in !something is not bool. 7713 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7714 if (SubExpr->getType()->isBooleanType()) return; 7715 7716 // Emit warning. 7717 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7718 << Loc; 7719 7720 // First note suggest !(x < y) 7721 SourceLocation FirstOpen = SubExpr->getLocStart(); 7722 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7723 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7724 if (FirstClose.isInvalid()) 7725 FirstOpen = SourceLocation(); 7726 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7727 << FixItHint::CreateInsertion(FirstOpen, "(") 7728 << FixItHint::CreateInsertion(FirstClose, ")"); 7729 7730 // Second note suggests (!x) < y 7731 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7732 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7733 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7734 if (SecondClose.isInvalid()) 7735 SecondOpen = SourceLocation(); 7736 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7737 << FixItHint::CreateInsertion(SecondOpen, "(") 7738 << FixItHint::CreateInsertion(SecondClose, ")"); 7739 } 7740 7741 // Get the decl for a simple expression: a reference to a variable, 7742 // an implicit C++ field reference, or an implicit ObjC ivar reference. 7743 static ValueDecl *getCompareDecl(Expr *E) { 7744 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7745 return DR->getDecl(); 7746 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7747 if (Ivar->isFreeIvar()) 7748 return Ivar->getDecl(); 7749 } 7750 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7751 if (Mem->isImplicitAccess()) 7752 return Mem->getMemberDecl(); 7753 } 7754 return 0; 7755 } 7756 7757 // C99 6.5.8, C++ [expr.rel] 7758 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7759 SourceLocation Loc, unsigned OpaqueOpc, 7760 bool IsRelational) { 7761 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7762 7763 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7764 7765 // Handle vector comparisons separately. 7766 if (LHS.get()->getType()->isVectorType() || 7767 RHS.get()->getType()->isVectorType()) 7768 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7769 7770 QualType LHSType = LHS.get()->getType(); 7771 QualType RHSType = RHS.get()->getType(); 7772 7773 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7774 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7775 7776 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7777 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7778 7779 if (!LHSType->hasFloatingRepresentation() && 7780 !(LHSType->isBlockPointerType() && IsRelational) && 7781 !LHS.get()->getLocStart().isMacroID() && 7782 !RHS.get()->getLocStart().isMacroID() && 7783 ActiveTemplateInstantiations.empty()) { 7784 // For non-floating point types, check for self-comparisons of the form 7785 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7786 // often indicate logic errors in the program. 7787 // 7788 // NOTE: Don't warn about comparison expressions resulting from macro 7789 // expansion. Also don't warn about comparisons which are only self 7790 // comparisons within a template specialization. The warnings should catch 7791 // obvious cases in the definition of the template anyways. The idea is to 7792 // warn when the typed comparison operator will always evaluate to the same 7793 // result. 7794 ValueDecl *DL = getCompareDecl(LHSStripped); 7795 ValueDecl *DR = getCompareDecl(RHSStripped); 7796 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7797 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7798 << 0 // self- 7799 << (Opc == BO_EQ 7800 || Opc == BO_LE 7801 || Opc == BO_GE)); 7802 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7803 !DL->getType()->isReferenceType() && 7804 !DR->getType()->isReferenceType()) { 7805 // what is it always going to eval to? 7806 char always_evals_to; 7807 switch(Opc) { 7808 case BO_EQ: // e.g. array1 == array2 7809 always_evals_to = 0; // false 7810 break; 7811 case BO_NE: // e.g. array1 != array2 7812 always_evals_to = 1; // true 7813 break; 7814 default: 7815 // best we can say is 'a constant' 7816 always_evals_to = 2; // e.g. array1 <= array2 7817 break; 7818 } 7819 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7820 << 1 // array 7821 << always_evals_to); 7822 } 7823 7824 if (isa<CastExpr>(LHSStripped)) 7825 LHSStripped = LHSStripped->IgnoreParenCasts(); 7826 if (isa<CastExpr>(RHSStripped)) 7827 RHSStripped = RHSStripped->IgnoreParenCasts(); 7828 7829 // Warn about comparisons against a string constant (unless the other 7830 // operand is null), the user probably wants strcmp. 7831 Expr *literalString = 0; 7832 Expr *literalStringStripped = 0; 7833 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7834 !RHSStripped->isNullPointerConstant(Context, 7835 Expr::NPC_ValueDependentIsNull)) { 7836 literalString = LHS.get(); 7837 literalStringStripped = LHSStripped; 7838 } else if ((isa<StringLiteral>(RHSStripped) || 7839 isa<ObjCEncodeExpr>(RHSStripped)) && 7840 !LHSStripped->isNullPointerConstant(Context, 7841 Expr::NPC_ValueDependentIsNull)) { 7842 literalString = RHS.get(); 7843 literalStringStripped = RHSStripped; 7844 } 7845 7846 if (literalString) { 7847 DiagRuntimeBehavior(Loc, 0, 7848 PDiag(diag::warn_stringcompare) 7849 << isa<ObjCEncodeExpr>(literalStringStripped) 7850 << literalString->getSourceRange()); 7851 } 7852 } 7853 7854 // C99 6.5.8p3 / C99 6.5.9p4 7855 UsualArithmeticConversions(LHS, RHS); 7856 if (LHS.isInvalid() || RHS.isInvalid()) 7857 return QualType(); 7858 7859 LHSType = LHS.get()->getType(); 7860 RHSType = RHS.get()->getType(); 7861 7862 // The result of comparisons is 'bool' in C++, 'int' in C. 7863 QualType ResultTy = Context.getLogicalOperationType(); 7864 7865 if (IsRelational) { 7866 if (LHSType->isRealType() && RHSType->isRealType()) 7867 return ResultTy; 7868 } else { 7869 // Check for comparisons of floating point operands using != and ==. 7870 if (LHSType->hasFloatingRepresentation()) 7871 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7872 7873 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7874 return ResultTy; 7875 } 7876 7877 const Expr::NullPointerConstantKind LHSNullKind = 7878 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7879 const Expr::NullPointerConstantKind RHSNullKind = 7880 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7881 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 7882 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 7883 7884 if (!IsRelational && LHSIsNull != RHSIsNull) { 7885 bool IsEquality = Opc == BO_EQ; 7886 if (RHSIsNull) 7887 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 7888 RHS.get()->getSourceRange()); 7889 else 7890 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 7891 LHS.get()->getSourceRange()); 7892 } 7893 7894 // All of the following pointer-related warnings are GCC extensions, except 7895 // when handling null pointer constants. 7896 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7897 QualType LCanPointeeTy = 7898 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7899 QualType RCanPointeeTy = 7900 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7901 7902 if (getLangOpts().CPlusPlus) { 7903 if (LCanPointeeTy == RCanPointeeTy) 7904 return ResultTy; 7905 if (!IsRelational && 7906 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7907 // Valid unless comparison between non-null pointer and function pointer 7908 // This is a gcc extension compatibility comparison. 7909 // In a SFINAE context, we treat this as a hard error to maintain 7910 // conformance with the C++ standard. 7911 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7912 && !LHSIsNull && !RHSIsNull) { 7913 diagnoseFunctionPointerToVoidComparison( 7914 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7915 7916 if (isSFINAEContext()) 7917 return QualType(); 7918 7919 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7920 return ResultTy; 7921 } 7922 } 7923 7924 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7925 return QualType(); 7926 else 7927 return ResultTy; 7928 } 7929 // C99 6.5.9p2 and C99 6.5.8p2 7930 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7931 RCanPointeeTy.getUnqualifiedType())) { 7932 // Valid unless a relational comparison of function pointers 7933 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7934 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7935 << LHSType << RHSType << LHS.get()->getSourceRange() 7936 << RHS.get()->getSourceRange(); 7937 } 7938 } else if (!IsRelational && 7939 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7940 // Valid unless comparison between non-null pointer and function pointer 7941 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7942 && !LHSIsNull && !RHSIsNull) 7943 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7944 /*isError*/false); 7945 } else { 7946 // Invalid 7947 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7948 } 7949 if (LCanPointeeTy != RCanPointeeTy) { 7950 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 7951 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 7952 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 7953 : CK_BitCast; 7954 if (LHSIsNull && !RHSIsNull) 7955 LHS = ImpCastExprToType(LHS.take(), RHSType, Kind); 7956 else 7957 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind); 7958 } 7959 return ResultTy; 7960 } 7961 7962 if (getLangOpts().CPlusPlus) { 7963 // Comparison of nullptr_t with itself. 7964 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7965 return ResultTy; 7966 7967 // Comparison of pointers with null pointer constants and equality 7968 // comparisons of member pointers to null pointer constants. 7969 if (RHSIsNull && 7970 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7971 (!IsRelational && 7972 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7973 RHS = ImpCastExprToType(RHS.take(), LHSType, 7974 LHSType->isMemberPointerType() 7975 ? CK_NullToMemberPointer 7976 : CK_NullToPointer); 7977 return ResultTy; 7978 } 7979 if (LHSIsNull && 7980 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7981 (!IsRelational && 7982 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7983 LHS = ImpCastExprToType(LHS.take(), RHSType, 7984 RHSType->isMemberPointerType() 7985 ? CK_NullToMemberPointer 7986 : CK_NullToPointer); 7987 return ResultTy; 7988 } 7989 7990 // Comparison of member pointers. 7991 if (!IsRelational && 7992 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7993 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7994 return QualType(); 7995 else 7996 return ResultTy; 7997 } 7998 7999 // Handle scoped enumeration types specifically, since they don't promote 8000 // to integers. 8001 if (LHS.get()->getType()->isEnumeralType() && 8002 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8003 RHS.get()->getType())) 8004 return ResultTy; 8005 } 8006 8007 // Handle block pointer types. 8008 if (!IsRelational && LHSType->isBlockPointerType() && 8009 RHSType->isBlockPointerType()) { 8010 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8011 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8012 8013 if (!LHSIsNull && !RHSIsNull && 8014 !Context.typesAreCompatible(lpointee, rpointee)) { 8015 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8016 << LHSType << RHSType << LHS.get()->getSourceRange() 8017 << RHS.get()->getSourceRange(); 8018 } 8019 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 8020 return ResultTy; 8021 } 8022 8023 // Allow block pointers to be compared with null pointer constants. 8024 if (!IsRelational 8025 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8026 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8027 if (!LHSIsNull && !RHSIsNull) { 8028 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8029 ->getPointeeType()->isVoidType()) 8030 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8031 ->getPointeeType()->isVoidType()))) 8032 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8033 << LHSType << RHSType << LHS.get()->getSourceRange() 8034 << RHS.get()->getSourceRange(); 8035 } 8036 if (LHSIsNull && !RHSIsNull) 8037 LHS = ImpCastExprToType(LHS.take(), RHSType, 8038 RHSType->isPointerType() ? CK_BitCast 8039 : CK_AnyPointerToBlockPointerCast); 8040 else 8041 RHS = ImpCastExprToType(RHS.take(), LHSType, 8042 LHSType->isPointerType() ? CK_BitCast 8043 : CK_AnyPointerToBlockPointerCast); 8044 return ResultTy; 8045 } 8046 8047 if (LHSType->isObjCObjectPointerType() || 8048 RHSType->isObjCObjectPointerType()) { 8049 const PointerType *LPT = LHSType->getAs<PointerType>(); 8050 const PointerType *RPT = RHSType->getAs<PointerType>(); 8051 if (LPT || RPT) { 8052 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8053 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8054 8055 if (!LPtrToVoid && !RPtrToVoid && 8056 !Context.typesAreCompatible(LHSType, RHSType)) { 8057 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8058 /*isError*/false); 8059 } 8060 if (LHSIsNull && !RHSIsNull) { 8061 Expr *E = LHS.take(); 8062 if (getLangOpts().ObjCAutoRefCount) 8063 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8064 LHS = ImpCastExprToType(E, RHSType, 8065 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8066 } 8067 else { 8068 Expr *E = RHS.take(); 8069 if (getLangOpts().ObjCAutoRefCount) 8070 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion); 8071 RHS = ImpCastExprToType(E, LHSType, 8072 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8073 } 8074 return ResultTy; 8075 } 8076 if (LHSType->isObjCObjectPointerType() && 8077 RHSType->isObjCObjectPointerType()) { 8078 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8079 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8080 /*isError*/false); 8081 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8082 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8083 8084 if (LHSIsNull && !RHSIsNull) 8085 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 8086 else 8087 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 8088 return ResultTy; 8089 } 8090 } 8091 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8092 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8093 unsigned DiagID = 0; 8094 bool isError = false; 8095 if (LangOpts.DebuggerSupport) { 8096 // Under a debugger, allow the comparison of pointers to integers, 8097 // since users tend to want to compare addresses. 8098 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8099 (RHSIsNull && RHSType->isIntegerType())) { 8100 if (IsRelational && !getLangOpts().CPlusPlus) 8101 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8102 } else if (IsRelational && !getLangOpts().CPlusPlus) 8103 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8104 else if (getLangOpts().CPlusPlus) { 8105 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8106 isError = true; 8107 } else 8108 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8109 8110 if (DiagID) { 8111 Diag(Loc, DiagID) 8112 << LHSType << RHSType << LHS.get()->getSourceRange() 8113 << RHS.get()->getSourceRange(); 8114 if (isError) 8115 return QualType(); 8116 } 8117 8118 if (LHSType->isIntegerType()) 8119 LHS = ImpCastExprToType(LHS.take(), RHSType, 8120 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8121 else 8122 RHS = ImpCastExprToType(RHS.take(), LHSType, 8123 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8124 return ResultTy; 8125 } 8126 8127 // Handle block pointers. 8128 if (!IsRelational && RHSIsNull 8129 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8130 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 8131 return ResultTy; 8132 } 8133 if (!IsRelational && LHSIsNull 8134 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8135 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 8136 return ResultTy; 8137 } 8138 8139 return InvalidOperands(Loc, LHS, RHS); 8140 } 8141 8142 8143 // Return a signed type that is of identical size and number of elements. 8144 // For floating point vectors, return an integer type of identical size 8145 // and number of elements. 8146 QualType Sema::GetSignedVectorType(QualType V) { 8147 const VectorType *VTy = V->getAs<VectorType>(); 8148 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8149 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8150 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8151 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8152 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8153 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8154 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8155 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8156 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8157 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8158 "Unhandled vector element size in vector compare"); 8159 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8160 } 8161 8162 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 8163 /// operates on extended vector types. Instead of producing an IntTy result, 8164 /// like a scalar comparison, a vector comparison produces a vector of integer 8165 /// types. 8166 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8167 SourceLocation Loc, 8168 bool IsRelational) { 8169 // Check to make sure we're operating on vectors of the same type and width, 8170 // Allowing one side to be a scalar of element type. 8171 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8172 if (vType.isNull()) 8173 return vType; 8174 8175 QualType LHSType = LHS.get()->getType(); 8176 8177 // If AltiVec, the comparison results in a numeric type, i.e. 8178 // bool for C++, int for C 8179 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8180 return Context.getLogicalOperationType(); 8181 8182 // For non-floating point types, check for self-comparisons of the form 8183 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8184 // often indicate logic errors in the program. 8185 if (!LHSType->hasFloatingRepresentation() && 8186 ActiveTemplateInstantiations.empty()) { 8187 if (DeclRefExpr* DRL 8188 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8189 if (DeclRefExpr* DRR 8190 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8191 if (DRL->getDecl() == DRR->getDecl()) 8192 DiagRuntimeBehavior(Loc, 0, 8193 PDiag(diag::warn_comparison_always) 8194 << 0 // self- 8195 << 2 // "a constant" 8196 ); 8197 } 8198 8199 // Check for comparisons of floating point operands using != and ==. 8200 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8201 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8202 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8203 } 8204 8205 // Return a signed type for the vector. 8206 return GetSignedVectorType(LHSType); 8207 } 8208 8209 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8210 SourceLocation Loc) { 8211 // Ensure that either both operands are of the same vector type, or 8212 // one operand is of a vector type and the other is of its element type. 8213 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8214 if (vType.isNull()) 8215 return InvalidOperands(Loc, LHS, RHS); 8216 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8217 vType->hasFloatingRepresentation()) 8218 return InvalidOperands(Loc, LHS, RHS); 8219 8220 return GetSignedVectorType(LHS.get()->getType()); 8221 } 8222 8223 inline QualType Sema::CheckBitwiseOperands( 8224 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8225 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8226 8227 if (LHS.get()->getType()->isVectorType() || 8228 RHS.get()->getType()->isVectorType()) { 8229 if (LHS.get()->getType()->hasIntegerRepresentation() && 8230 RHS.get()->getType()->hasIntegerRepresentation()) 8231 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8232 8233 return InvalidOperands(Loc, LHS, RHS); 8234 } 8235 8236 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 8237 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8238 IsCompAssign); 8239 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8240 return QualType(); 8241 LHS = LHSResult.take(); 8242 RHS = RHSResult.take(); 8243 8244 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8245 return compType; 8246 return InvalidOperands(Loc, LHS, RHS); 8247 } 8248 8249 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8250 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8251 8252 // Check vector operands differently. 8253 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8254 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8255 8256 // Diagnose cases where the user write a logical and/or but probably meant a 8257 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8258 // is a constant. 8259 if (LHS.get()->getType()->isIntegerType() && 8260 !LHS.get()->getType()->isBooleanType() && 8261 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8262 // Don't warn in macros or template instantiations. 8263 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8264 // If the RHS can be constant folded, and if it constant folds to something 8265 // that isn't 0 or 1 (which indicate a potential logical operation that 8266 // happened to fold to true/false) then warn. 8267 // Parens on the RHS are ignored. 8268 llvm::APSInt Result; 8269 if (RHS.get()->EvaluateAsInt(Result, Context)) 8270 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 8271 (Result != 0 && Result != 1)) { 8272 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8273 << RHS.get()->getSourceRange() 8274 << (Opc == BO_LAnd ? "&&" : "||"); 8275 // Suggest replacing the logical operator with the bitwise version 8276 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8277 << (Opc == BO_LAnd ? "&" : "|") 8278 << FixItHint::CreateReplacement(SourceRange( 8279 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8280 getLangOpts())), 8281 Opc == BO_LAnd ? "&" : "|"); 8282 if (Opc == BO_LAnd) 8283 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8284 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8285 << FixItHint::CreateRemoval( 8286 SourceRange( 8287 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8288 0, getSourceManager(), 8289 getLangOpts()), 8290 RHS.get()->getLocEnd())); 8291 } 8292 } 8293 8294 if (!Context.getLangOpts().CPlusPlus) { 8295 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8296 // not operate on the built-in scalar and vector float types. 8297 if (Context.getLangOpts().OpenCL && 8298 Context.getLangOpts().OpenCLVersion < 120) { 8299 if (LHS.get()->getType()->isFloatingType() || 8300 RHS.get()->getType()->isFloatingType()) 8301 return InvalidOperands(Loc, LHS, RHS); 8302 } 8303 8304 LHS = UsualUnaryConversions(LHS.take()); 8305 if (LHS.isInvalid()) 8306 return QualType(); 8307 8308 RHS = UsualUnaryConversions(RHS.take()); 8309 if (RHS.isInvalid()) 8310 return QualType(); 8311 8312 if (!LHS.get()->getType()->isScalarType() || 8313 !RHS.get()->getType()->isScalarType()) 8314 return InvalidOperands(Loc, LHS, RHS); 8315 8316 return Context.IntTy; 8317 } 8318 8319 // The following is safe because we only use this method for 8320 // non-overloadable operands. 8321 8322 // C++ [expr.log.and]p1 8323 // C++ [expr.log.or]p1 8324 // The operands are both contextually converted to type bool. 8325 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8326 if (LHSRes.isInvalid()) 8327 return InvalidOperands(Loc, LHS, RHS); 8328 LHS = LHSRes; 8329 8330 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8331 if (RHSRes.isInvalid()) 8332 return InvalidOperands(Loc, LHS, RHS); 8333 RHS = RHSRes; 8334 8335 // C++ [expr.log.and]p2 8336 // C++ [expr.log.or]p2 8337 // The result is a bool. 8338 return Context.BoolTy; 8339 } 8340 8341 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8342 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8343 if (!ME) return false; 8344 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8345 ObjCMessageExpr *Base = 8346 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8347 if (!Base) return false; 8348 return Base->getMethodDecl() != 0; 8349 } 8350 8351 /// Is the given expression (which must be 'const') a reference to a 8352 /// variable which was originally non-const, but which has become 8353 /// 'const' due to being captured within a block? 8354 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8355 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8356 assert(E->isLValue() && E->getType().isConstQualified()); 8357 E = E->IgnoreParens(); 8358 8359 // Must be a reference to a declaration from an enclosing scope. 8360 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8361 if (!DRE) return NCCK_None; 8362 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8363 8364 // The declaration must be a variable which is not declared 'const'. 8365 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8366 if (!var) return NCCK_None; 8367 if (var->getType().isConstQualified()) return NCCK_None; 8368 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8369 8370 // Decide whether the first capture was for a block or a lambda. 8371 DeclContext *DC = S.CurContext, *Prev = 0; 8372 while (DC != var->getDeclContext()) { 8373 Prev = DC; 8374 DC = DC->getParent(); 8375 } 8376 // Unless we have an init-capture, we've gone one step too far. 8377 if (!var->isInitCapture()) 8378 DC = Prev; 8379 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8380 } 8381 8382 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8383 /// emit an error and return true. If so, return false. 8384 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8385 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8386 SourceLocation OrigLoc = Loc; 8387 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8388 &Loc); 8389 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8390 IsLV = Expr::MLV_InvalidMessageExpression; 8391 if (IsLV == Expr::MLV_Valid) 8392 return false; 8393 8394 unsigned Diag = 0; 8395 bool NeedType = false; 8396 switch (IsLV) { // C99 6.5.16p2 8397 case Expr::MLV_ConstQualified: 8398 Diag = diag::err_typecheck_assign_const; 8399 8400 // Use a specialized diagnostic when we're assigning to an object 8401 // from an enclosing function or block. 8402 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8403 if (NCCK == NCCK_Block) 8404 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8405 else 8406 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8407 break; 8408 } 8409 8410 // In ARC, use some specialized diagnostics for occasions where we 8411 // infer 'const'. These are always pseudo-strong variables. 8412 if (S.getLangOpts().ObjCAutoRefCount) { 8413 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8414 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8415 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8416 8417 // Use the normal diagnostic if it's pseudo-__strong but the 8418 // user actually wrote 'const'. 8419 if (var->isARCPseudoStrong() && 8420 (!var->getTypeSourceInfo() || 8421 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8422 // There are two pseudo-strong cases: 8423 // - self 8424 ObjCMethodDecl *method = S.getCurMethodDecl(); 8425 if (method && var == method->getSelfDecl()) 8426 Diag = method->isClassMethod() 8427 ? diag::err_typecheck_arc_assign_self_class_method 8428 : diag::err_typecheck_arc_assign_self; 8429 8430 // - fast enumeration variables 8431 else 8432 Diag = diag::err_typecheck_arr_assign_enumeration; 8433 8434 SourceRange Assign; 8435 if (Loc != OrigLoc) 8436 Assign = SourceRange(OrigLoc, OrigLoc); 8437 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8438 // We need to preserve the AST regardless, so migration tool 8439 // can do its job. 8440 return false; 8441 } 8442 } 8443 } 8444 8445 break; 8446 case Expr::MLV_ArrayType: 8447 case Expr::MLV_ArrayTemporary: 8448 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8449 NeedType = true; 8450 break; 8451 case Expr::MLV_NotObjectType: 8452 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8453 NeedType = true; 8454 break; 8455 case Expr::MLV_LValueCast: 8456 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8457 break; 8458 case Expr::MLV_Valid: 8459 llvm_unreachable("did not take early return for MLV_Valid"); 8460 case Expr::MLV_InvalidExpression: 8461 case Expr::MLV_MemberFunction: 8462 case Expr::MLV_ClassTemporary: 8463 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8464 break; 8465 case Expr::MLV_IncompleteType: 8466 case Expr::MLV_IncompleteVoidType: 8467 return S.RequireCompleteType(Loc, E->getType(), 8468 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8469 case Expr::MLV_DuplicateVectorComponents: 8470 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8471 break; 8472 case Expr::MLV_NoSetterProperty: 8473 llvm_unreachable("readonly properties should be processed differently"); 8474 case Expr::MLV_InvalidMessageExpression: 8475 Diag = diag::error_readonly_message_assignment; 8476 break; 8477 case Expr::MLV_SubObjCPropertySetting: 8478 Diag = diag::error_no_subobject_property_setting; 8479 break; 8480 } 8481 8482 SourceRange Assign; 8483 if (Loc != OrigLoc) 8484 Assign = SourceRange(OrigLoc, OrigLoc); 8485 if (NeedType) 8486 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8487 else 8488 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8489 return true; 8490 } 8491 8492 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8493 SourceLocation Loc, 8494 Sema &Sema) { 8495 // C / C++ fields 8496 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8497 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8498 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8499 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8500 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8501 } 8502 8503 // Objective-C instance variables 8504 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8505 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8506 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8507 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8508 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8509 if (RL && RR && RL->getDecl() == RR->getDecl()) 8510 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8511 } 8512 } 8513 8514 // C99 6.5.16.1 8515 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8516 SourceLocation Loc, 8517 QualType CompoundType) { 8518 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8519 8520 // Verify that LHS is a modifiable lvalue, and emit error if not. 8521 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8522 return QualType(); 8523 8524 QualType LHSType = LHSExpr->getType(); 8525 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8526 CompoundType; 8527 AssignConvertType ConvTy; 8528 if (CompoundType.isNull()) { 8529 Expr *RHSCheck = RHS.get(); 8530 8531 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8532 8533 QualType LHSTy(LHSType); 8534 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8535 if (RHS.isInvalid()) 8536 return QualType(); 8537 // Special case of NSObject attributes on c-style pointer types. 8538 if (ConvTy == IncompatiblePointer && 8539 ((Context.isObjCNSObjectType(LHSType) && 8540 RHSType->isObjCObjectPointerType()) || 8541 (Context.isObjCNSObjectType(RHSType) && 8542 LHSType->isObjCObjectPointerType()))) 8543 ConvTy = Compatible; 8544 8545 if (ConvTy == Compatible && 8546 LHSType->isObjCObjectType()) 8547 Diag(Loc, diag::err_objc_object_assignment) 8548 << LHSType; 8549 8550 // If the RHS is a unary plus or minus, check to see if they = and + are 8551 // right next to each other. If so, the user may have typo'd "x =+ 4" 8552 // instead of "x += 4". 8553 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8554 RHSCheck = ICE->getSubExpr(); 8555 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8556 if ((UO->getOpcode() == UO_Plus || 8557 UO->getOpcode() == UO_Minus) && 8558 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8559 // Only if the two operators are exactly adjacent. 8560 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8561 // And there is a space or other character before the subexpr of the 8562 // unary +/-. We don't want to warn on "x=-1". 8563 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8564 UO->getSubExpr()->getLocStart().isFileID()) { 8565 Diag(Loc, diag::warn_not_compound_assign) 8566 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8567 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8568 } 8569 } 8570 8571 if (ConvTy == Compatible) { 8572 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8573 // Warn about retain cycles where a block captures the LHS, but 8574 // not if the LHS is a simple variable into which the block is 8575 // being stored...unless that variable can be captured by reference! 8576 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8577 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8578 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8579 checkRetainCycles(LHSExpr, RHS.get()); 8580 8581 // It is safe to assign a weak reference into a strong variable. 8582 // Although this code can still have problems: 8583 // id x = self.weakProp; 8584 // id y = self.weakProp; 8585 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8586 // paths through the function. This should be revisited if 8587 // -Wrepeated-use-of-weak is made flow-sensitive. 8588 DiagnosticsEngine::Level Level = 8589 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8590 RHS.get()->getLocStart()); 8591 if (Level != DiagnosticsEngine::Ignored) 8592 getCurFunction()->markSafeWeakUse(RHS.get()); 8593 8594 } else if (getLangOpts().ObjCAutoRefCount) { 8595 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8596 } 8597 } 8598 } else { 8599 // Compound assignment "x += y" 8600 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8601 } 8602 8603 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8604 RHS.get(), AA_Assigning)) 8605 return QualType(); 8606 8607 CheckForNullPointerDereference(*this, LHSExpr); 8608 8609 // C99 6.5.16p3: The type of an assignment expression is the type of the 8610 // left operand unless the left operand has qualified type, in which case 8611 // it is the unqualified version of the type of the left operand. 8612 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8613 // is converted to the type of the assignment expression (above). 8614 // C++ 5.17p1: the type of the assignment expression is that of its left 8615 // operand. 8616 return (getLangOpts().CPlusPlus 8617 ? LHSType : LHSType.getUnqualifiedType()); 8618 } 8619 8620 // C99 6.5.17 8621 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8622 SourceLocation Loc) { 8623 LHS = S.CheckPlaceholderExpr(LHS.take()); 8624 RHS = S.CheckPlaceholderExpr(RHS.take()); 8625 if (LHS.isInvalid() || RHS.isInvalid()) 8626 return QualType(); 8627 8628 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8629 // operands, but not unary promotions. 8630 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8631 8632 // So we treat the LHS as a ignored value, and in C++ we allow the 8633 // containing site to determine what should be done with the RHS. 8634 LHS = S.IgnoredValueConversions(LHS.take()); 8635 if (LHS.isInvalid()) 8636 return QualType(); 8637 8638 S.DiagnoseUnusedExprResult(LHS.get()); 8639 8640 if (!S.getLangOpts().CPlusPlus) { 8641 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8642 if (RHS.isInvalid()) 8643 return QualType(); 8644 if (!RHS.get()->getType()->isVoidType()) 8645 S.RequireCompleteType(Loc, RHS.get()->getType(), 8646 diag::err_incomplete_type); 8647 } 8648 8649 return RHS.get()->getType(); 8650 } 8651 8652 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8653 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8654 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8655 ExprValueKind &VK, 8656 SourceLocation OpLoc, 8657 bool IsInc, bool IsPrefix) { 8658 if (Op->isTypeDependent()) 8659 return S.Context.DependentTy; 8660 8661 QualType ResType = Op->getType(); 8662 // Atomic types can be used for increment / decrement where the non-atomic 8663 // versions can, so ignore the _Atomic() specifier for the purpose of 8664 // checking. 8665 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8666 ResType = ResAtomicType->getValueType(); 8667 8668 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8669 8670 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8671 // Decrement of bool is not allowed. 8672 if (!IsInc) { 8673 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8674 return QualType(); 8675 } 8676 // Increment of bool sets it to true, but is deprecated. 8677 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8678 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8679 // Error on enum increments and decrements in C++ mode 8680 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8681 return QualType(); 8682 } else if (ResType->isRealType()) { 8683 // OK! 8684 } else if (ResType->isPointerType()) { 8685 // C99 6.5.2.4p2, 6.5.6p2 8686 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8687 return QualType(); 8688 } else if (ResType->isObjCObjectPointerType()) { 8689 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8690 // Otherwise, we just need a complete type. 8691 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8692 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8693 return QualType(); 8694 } else if (ResType->isAnyComplexType()) { 8695 // C99 does not support ++/-- on complex types, we allow as an extension. 8696 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8697 << ResType << Op->getSourceRange(); 8698 } else if (ResType->isPlaceholderType()) { 8699 ExprResult PR = S.CheckPlaceholderExpr(Op); 8700 if (PR.isInvalid()) return QualType(); 8701 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8702 IsInc, IsPrefix); 8703 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8704 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8705 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8706 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8707 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8708 } else { 8709 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8710 << ResType << int(IsInc) << Op->getSourceRange(); 8711 return QualType(); 8712 } 8713 // At this point, we know we have a real, complex or pointer type. 8714 // Now make sure the operand is a modifiable lvalue. 8715 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8716 return QualType(); 8717 // In C++, a prefix increment is the same type as the operand. Otherwise 8718 // (in C or with postfix), the increment is the unqualified type of the 8719 // operand. 8720 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8721 VK = VK_LValue; 8722 return ResType; 8723 } else { 8724 VK = VK_RValue; 8725 return ResType.getUnqualifiedType(); 8726 } 8727 } 8728 8729 8730 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8731 /// This routine allows us to typecheck complex/recursive expressions 8732 /// where the declaration is needed for type checking. We only need to 8733 /// handle cases when the expression references a function designator 8734 /// or is an lvalue. Here are some examples: 8735 /// - &(x) => x 8736 /// - &*****f => f for f a function designator. 8737 /// - &s.xx => s 8738 /// - &s.zz[1].yy -> s, if zz is an array 8739 /// - *(x + 1) -> x, if x is an array 8740 /// - &"123"[2] -> 0 8741 /// - & __real__ x -> x 8742 static ValueDecl *getPrimaryDecl(Expr *E) { 8743 switch (E->getStmtClass()) { 8744 case Stmt::DeclRefExprClass: 8745 return cast<DeclRefExpr>(E)->getDecl(); 8746 case Stmt::MemberExprClass: 8747 // If this is an arrow operator, the address is an offset from 8748 // the base's value, so the object the base refers to is 8749 // irrelevant. 8750 if (cast<MemberExpr>(E)->isArrow()) 8751 return 0; 8752 // Otherwise, the expression refers to a part of the base 8753 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8754 case Stmt::ArraySubscriptExprClass: { 8755 // FIXME: This code shouldn't be necessary! We should catch the implicit 8756 // promotion of register arrays earlier. 8757 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8758 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8759 if (ICE->getSubExpr()->getType()->isArrayType()) 8760 return getPrimaryDecl(ICE->getSubExpr()); 8761 } 8762 return 0; 8763 } 8764 case Stmt::UnaryOperatorClass: { 8765 UnaryOperator *UO = cast<UnaryOperator>(E); 8766 8767 switch(UO->getOpcode()) { 8768 case UO_Real: 8769 case UO_Imag: 8770 case UO_Extension: 8771 return getPrimaryDecl(UO->getSubExpr()); 8772 default: 8773 return 0; 8774 } 8775 } 8776 case Stmt::ParenExprClass: 8777 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8778 case Stmt::ImplicitCastExprClass: 8779 // If the result of an implicit cast is an l-value, we care about 8780 // the sub-expression; otherwise, the result here doesn't matter. 8781 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8782 default: 8783 return 0; 8784 } 8785 } 8786 8787 namespace { 8788 enum { 8789 AO_Bit_Field = 0, 8790 AO_Vector_Element = 1, 8791 AO_Property_Expansion = 2, 8792 AO_Register_Variable = 3, 8793 AO_No_Error = 4 8794 }; 8795 } 8796 /// \brief Diagnose invalid operand for address of operations. 8797 /// 8798 /// \param Type The type of operand which cannot have its address taken. 8799 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8800 Expr *E, unsigned Type) { 8801 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8802 } 8803 8804 /// CheckAddressOfOperand - The operand of & must be either a function 8805 /// designator or an lvalue designating an object. If it is an lvalue, the 8806 /// object cannot be declared with storage class register or be a bit field. 8807 /// Note: The usual conversions are *not* applied to the operand of the & 8808 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8809 /// In C++, the operand might be an overloaded function name, in which case 8810 /// we allow the '&' but retain the overloaded-function type. 8811 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8812 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8813 if (PTy->getKind() == BuiltinType::Overload) { 8814 Expr *E = OrigOp.get()->IgnoreParens(); 8815 if (!isa<OverloadExpr>(E)) { 8816 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8817 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8818 << OrigOp.get()->getSourceRange(); 8819 return QualType(); 8820 } 8821 8822 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8823 if (isa<UnresolvedMemberExpr>(Ovl)) 8824 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8825 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8826 << OrigOp.get()->getSourceRange(); 8827 return QualType(); 8828 } 8829 8830 return Context.OverloadTy; 8831 } 8832 8833 if (PTy->getKind() == BuiltinType::UnknownAny) 8834 return Context.UnknownAnyTy; 8835 8836 if (PTy->getKind() == BuiltinType::BoundMember) { 8837 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8838 << OrigOp.get()->getSourceRange(); 8839 return QualType(); 8840 } 8841 8842 OrigOp = CheckPlaceholderExpr(OrigOp.take()); 8843 if (OrigOp.isInvalid()) return QualType(); 8844 } 8845 8846 if (OrigOp.get()->isTypeDependent()) 8847 return Context.DependentTy; 8848 8849 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8850 8851 // Make sure to ignore parentheses in subsequent checks 8852 Expr *op = OrigOp.get()->IgnoreParens(); 8853 8854 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 8855 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 8856 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 8857 return QualType(); 8858 } 8859 8860 if (getLangOpts().C99) { 8861 // Implement C99-only parts of addressof rules. 8862 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8863 if (uOp->getOpcode() == UO_Deref) 8864 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8865 // (assuming the deref expression is valid). 8866 return uOp->getSubExpr()->getType(); 8867 } 8868 // Technically, there should be a check for array subscript 8869 // expressions here, but the result of one is always an lvalue anyway. 8870 } 8871 ValueDecl *dcl = getPrimaryDecl(op); 8872 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8873 unsigned AddressOfError = AO_No_Error; 8874 8875 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8876 bool sfinae = (bool)isSFINAEContext(); 8877 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8878 : diag::ext_typecheck_addrof_temporary) 8879 << op->getType() << op->getSourceRange(); 8880 if (sfinae) 8881 return QualType(); 8882 // Materialize the temporary as an lvalue so that we can take its address. 8883 OrigOp = op = new (Context) 8884 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8885 } else if (isa<ObjCSelectorExpr>(op)) { 8886 return Context.getPointerType(op->getType()); 8887 } else if (lval == Expr::LV_MemberFunction) { 8888 // If it's an instance method, make a member pointer. 8889 // The expression must have exactly the form &A::foo. 8890 8891 // If the underlying expression isn't a decl ref, give up. 8892 if (!isa<DeclRefExpr>(op)) { 8893 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8894 << OrigOp.get()->getSourceRange(); 8895 return QualType(); 8896 } 8897 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8898 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8899 8900 // The id-expression was parenthesized. 8901 if (OrigOp.get() != DRE) { 8902 Diag(OpLoc, diag::err_parens_pointer_member_function) 8903 << OrigOp.get()->getSourceRange(); 8904 8905 // The method was named without a qualifier. 8906 } else if (!DRE->getQualifier()) { 8907 if (MD->getParent()->getName().empty()) 8908 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8909 << op->getSourceRange(); 8910 else { 8911 SmallString<32> Str; 8912 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8913 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8914 << op->getSourceRange() 8915 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8916 } 8917 } 8918 8919 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 8920 if (isa<CXXDestructorDecl>(MD)) 8921 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 8922 8923 QualType MPTy = Context.getMemberPointerType( 8924 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8925 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8926 RequireCompleteType(OpLoc, MPTy, 0); 8927 return MPTy; 8928 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8929 // C99 6.5.3.2p1 8930 // The operand must be either an l-value or a function designator 8931 if (!op->getType()->isFunctionType()) { 8932 // Use a special diagnostic for loads from property references. 8933 if (isa<PseudoObjectExpr>(op)) { 8934 AddressOfError = AO_Property_Expansion; 8935 } else { 8936 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8937 << op->getType() << op->getSourceRange(); 8938 return QualType(); 8939 } 8940 } 8941 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8942 // The operand cannot be a bit-field 8943 AddressOfError = AO_Bit_Field; 8944 } else if (op->getObjectKind() == OK_VectorComponent) { 8945 // The operand cannot be an element of a vector 8946 AddressOfError = AO_Vector_Element; 8947 } else if (dcl) { // C99 6.5.3.2p1 8948 // We have an lvalue with a decl. Make sure the decl is not declared 8949 // with the register storage-class specifier. 8950 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8951 // in C++ it is not error to take address of a register 8952 // variable (c++03 7.1.1P3) 8953 if (vd->getStorageClass() == SC_Register && 8954 !getLangOpts().CPlusPlus) { 8955 AddressOfError = AO_Register_Variable; 8956 } 8957 } else if (isa<FunctionTemplateDecl>(dcl)) { 8958 return Context.OverloadTy; 8959 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8960 // Okay: we can take the address of a field. 8961 // Could be a pointer to member, though, if there is an explicit 8962 // scope qualifier for the class. 8963 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8964 DeclContext *Ctx = dcl->getDeclContext(); 8965 if (Ctx && Ctx->isRecord()) { 8966 if (dcl->getType()->isReferenceType()) { 8967 Diag(OpLoc, 8968 diag::err_cannot_form_pointer_to_member_of_reference_type) 8969 << dcl->getDeclName() << dcl->getType(); 8970 return QualType(); 8971 } 8972 8973 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8974 Ctx = Ctx->getParent(); 8975 8976 QualType MPTy = Context.getMemberPointerType( 8977 op->getType(), 8978 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8979 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8980 RequireCompleteType(OpLoc, MPTy, 0); 8981 return MPTy; 8982 } 8983 } 8984 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8985 llvm_unreachable("Unknown/unexpected decl type"); 8986 } 8987 8988 if (AddressOfError != AO_No_Error) { 8989 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 8990 return QualType(); 8991 } 8992 8993 if (lval == Expr::LV_IncompleteVoidType) { 8994 // Taking the address of a void variable is technically illegal, but we 8995 // allow it in cases which are otherwise valid. 8996 // Example: "extern void x; void* y = &x;". 8997 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8998 } 8999 9000 // If the operand has type "type", the result has type "pointer to type". 9001 if (op->getType()->isObjCObjectType()) 9002 return Context.getObjCObjectPointerType(op->getType()); 9003 return Context.getPointerType(op->getType()); 9004 } 9005 9006 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 9007 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 9008 SourceLocation OpLoc) { 9009 if (Op->isTypeDependent()) 9010 return S.Context.DependentTy; 9011 9012 ExprResult ConvResult = S.UsualUnaryConversions(Op); 9013 if (ConvResult.isInvalid()) 9014 return QualType(); 9015 Op = ConvResult.take(); 9016 QualType OpTy = Op->getType(); 9017 QualType Result; 9018 9019 if (isa<CXXReinterpretCastExpr>(Op)) { 9020 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 9021 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 9022 Op->getSourceRange()); 9023 } 9024 9025 // Note that per both C89 and C99, indirection is always legal, even if OpTy 9026 // is an incomplete type or void. It would be possible to warn about 9027 // dereferencing a void pointer, but it's completely well-defined, and such a 9028 // warning is unlikely to catch any mistakes. 9029 if (const PointerType *PT = OpTy->getAs<PointerType>()) 9030 Result = PT->getPointeeType(); 9031 else if (const ObjCObjectPointerType *OPT = 9032 OpTy->getAs<ObjCObjectPointerType>()) 9033 Result = OPT->getPointeeType(); 9034 else { 9035 ExprResult PR = S.CheckPlaceholderExpr(Op); 9036 if (PR.isInvalid()) return QualType(); 9037 if (PR.take() != Op) 9038 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 9039 } 9040 9041 if (Result.isNull()) { 9042 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 9043 << OpTy << Op->getSourceRange(); 9044 return QualType(); 9045 } 9046 9047 // Dereferences are usually l-values... 9048 VK = VK_LValue; 9049 9050 // ...except that certain expressions are never l-values in C. 9051 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 9052 VK = VK_RValue; 9053 9054 return Result; 9055 } 9056 9057 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 9058 tok::TokenKind Kind) { 9059 BinaryOperatorKind Opc; 9060 switch (Kind) { 9061 default: llvm_unreachable("Unknown binop!"); 9062 case tok::periodstar: Opc = BO_PtrMemD; break; 9063 case tok::arrowstar: Opc = BO_PtrMemI; break; 9064 case tok::star: Opc = BO_Mul; break; 9065 case tok::slash: Opc = BO_Div; break; 9066 case tok::percent: Opc = BO_Rem; break; 9067 case tok::plus: Opc = BO_Add; break; 9068 case tok::minus: Opc = BO_Sub; break; 9069 case tok::lessless: Opc = BO_Shl; break; 9070 case tok::greatergreater: Opc = BO_Shr; break; 9071 case tok::lessequal: Opc = BO_LE; break; 9072 case tok::less: Opc = BO_LT; break; 9073 case tok::greaterequal: Opc = BO_GE; break; 9074 case tok::greater: Opc = BO_GT; break; 9075 case tok::exclaimequal: Opc = BO_NE; break; 9076 case tok::equalequal: Opc = BO_EQ; break; 9077 case tok::amp: Opc = BO_And; break; 9078 case tok::caret: Opc = BO_Xor; break; 9079 case tok::pipe: Opc = BO_Or; break; 9080 case tok::ampamp: Opc = BO_LAnd; break; 9081 case tok::pipepipe: Opc = BO_LOr; break; 9082 case tok::equal: Opc = BO_Assign; break; 9083 case tok::starequal: Opc = BO_MulAssign; break; 9084 case tok::slashequal: Opc = BO_DivAssign; break; 9085 case tok::percentequal: Opc = BO_RemAssign; break; 9086 case tok::plusequal: Opc = BO_AddAssign; break; 9087 case tok::minusequal: Opc = BO_SubAssign; break; 9088 case tok::lesslessequal: Opc = BO_ShlAssign; break; 9089 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 9090 case tok::ampequal: Opc = BO_AndAssign; break; 9091 case tok::caretequal: Opc = BO_XorAssign; break; 9092 case tok::pipeequal: Opc = BO_OrAssign; break; 9093 case tok::comma: Opc = BO_Comma; break; 9094 } 9095 return Opc; 9096 } 9097 9098 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 9099 tok::TokenKind Kind) { 9100 UnaryOperatorKind Opc; 9101 switch (Kind) { 9102 default: llvm_unreachable("Unknown unary op!"); 9103 case tok::plusplus: Opc = UO_PreInc; break; 9104 case tok::minusminus: Opc = UO_PreDec; break; 9105 case tok::amp: Opc = UO_AddrOf; break; 9106 case tok::star: Opc = UO_Deref; break; 9107 case tok::plus: Opc = UO_Plus; break; 9108 case tok::minus: Opc = UO_Minus; break; 9109 case tok::tilde: Opc = UO_Not; break; 9110 case tok::exclaim: Opc = UO_LNot; break; 9111 case tok::kw___real: Opc = UO_Real; break; 9112 case tok::kw___imag: Opc = UO_Imag; break; 9113 case tok::kw___extension__: Opc = UO_Extension; break; 9114 } 9115 return Opc; 9116 } 9117 9118 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 9119 /// This warning is only emitted for builtin assignment operations. It is also 9120 /// suppressed in the event of macro expansions. 9121 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 9122 SourceLocation OpLoc) { 9123 if (!S.ActiveTemplateInstantiations.empty()) 9124 return; 9125 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 9126 return; 9127 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 9128 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 9129 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 9130 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 9131 if (!LHSDeclRef || !RHSDeclRef || 9132 LHSDeclRef->getLocation().isMacroID() || 9133 RHSDeclRef->getLocation().isMacroID()) 9134 return; 9135 const ValueDecl *LHSDecl = 9136 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 9137 const ValueDecl *RHSDecl = 9138 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 9139 if (LHSDecl != RHSDecl) 9140 return; 9141 if (LHSDecl->getType().isVolatileQualified()) 9142 return; 9143 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9144 if (RefTy->getPointeeType().isVolatileQualified()) 9145 return; 9146 9147 S.Diag(OpLoc, diag::warn_self_assignment) 9148 << LHSDeclRef->getType() 9149 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9150 } 9151 9152 /// Check if a bitwise-& is performed on an Objective-C pointer. This 9153 /// is usually indicative of introspection within the Objective-C pointer. 9154 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9155 SourceLocation OpLoc) { 9156 if (!S.getLangOpts().ObjC1) 9157 return; 9158 9159 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 9160 const Expr *LHS = L.get(); 9161 const Expr *RHS = R.get(); 9162 9163 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9164 ObjCPointerExpr = LHS; 9165 OtherExpr = RHS; 9166 } 9167 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9168 ObjCPointerExpr = RHS; 9169 OtherExpr = LHS; 9170 } 9171 9172 // This warning is deliberately made very specific to reduce false 9173 // positives with logic that uses '&' for hashing. This logic mainly 9174 // looks for code trying to introspect into tagged pointers, which 9175 // code should generally never do. 9176 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9177 unsigned Diag = diag::warn_objc_pointer_masking; 9178 // Determine if we are introspecting the result of performSelectorXXX. 9179 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9180 // Special case messages to -performSelector and friends, which 9181 // can return non-pointer values boxed in a pointer value. 9182 // Some clients may wish to silence warnings in this subcase. 9183 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9184 Selector S = ME->getSelector(); 9185 StringRef SelArg0 = S.getNameForSlot(0); 9186 if (SelArg0.startswith("performSelector")) 9187 Diag = diag::warn_objc_pointer_masking_performSelector; 9188 } 9189 9190 S.Diag(OpLoc, Diag) 9191 << ObjCPointerExpr->getSourceRange(); 9192 } 9193 } 9194 9195 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 9196 /// operator @p Opc at location @c TokLoc. This routine only supports 9197 /// built-in operations; ActOnBinOp handles overloaded operators. 9198 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9199 BinaryOperatorKind Opc, 9200 Expr *LHSExpr, Expr *RHSExpr) { 9201 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 9202 // The syntax only allows initializer lists on the RHS of assignment, 9203 // so we don't need to worry about accepting invalid code for 9204 // non-assignment operators. 9205 // C++11 5.17p9: 9206 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 9207 // of x = {} is x = T(). 9208 InitializationKind Kind = 9209 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 9210 InitializedEntity Entity = 9211 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 9212 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 9213 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 9214 if (Init.isInvalid()) 9215 return Init; 9216 RHSExpr = Init.take(); 9217 } 9218 9219 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 9220 QualType ResultTy; // Result type of the binary operator. 9221 // The following two variables are used for compound assignment operators 9222 QualType CompLHSTy; // Type of LHS after promotions for computation 9223 QualType CompResultTy; // Type of computation result 9224 ExprValueKind VK = VK_RValue; 9225 ExprObjectKind OK = OK_Ordinary; 9226 9227 switch (Opc) { 9228 case BO_Assign: 9229 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9230 if (getLangOpts().CPlusPlus && 9231 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9232 VK = LHS.get()->getValueKind(); 9233 OK = LHS.get()->getObjectKind(); 9234 } 9235 if (!ResultTy.isNull()) 9236 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9237 break; 9238 case BO_PtrMemD: 9239 case BO_PtrMemI: 9240 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9241 Opc == BO_PtrMemI); 9242 break; 9243 case BO_Mul: 9244 case BO_Div: 9245 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9246 Opc == BO_Div); 9247 break; 9248 case BO_Rem: 9249 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9250 break; 9251 case BO_Add: 9252 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9253 break; 9254 case BO_Sub: 9255 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9256 break; 9257 case BO_Shl: 9258 case BO_Shr: 9259 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9260 break; 9261 case BO_LE: 9262 case BO_LT: 9263 case BO_GE: 9264 case BO_GT: 9265 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9266 break; 9267 case BO_EQ: 9268 case BO_NE: 9269 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9270 break; 9271 case BO_And: 9272 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9273 case BO_Xor: 9274 case BO_Or: 9275 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9276 break; 9277 case BO_LAnd: 9278 case BO_LOr: 9279 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9280 break; 9281 case BO_MulAssign: 9282 case BO_DivAssign: 9283 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9284 Opc == BO_DivAssign); 9285 CompLHSTy = CompResultTy; 9286 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9287 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9288 break; 9289 case BO_RemAssign: 9290 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9291 CompLHSTy = CompResultTy; 9292 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9293 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9294 break; 9295 case BO_AddAssign: 9296 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9297 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9298 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9299 break; 9300 case BO_SubAssign: 9301 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9302 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9303 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9304 break; 9305 case BO_ShlAssign: 9306 case BO_ShrAssign: 9307 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9308 CompLHSTy = CompResultTy; 9309 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9310 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9311 break; 9312 case BO_AndAssign: 9313 case BO_XorAssign: 9314 case BO_OrAssign: 9315 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9316 CompLHSTy = CompResultTy; 9317 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9318 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9319 break; 9320 case BO_Comma: 9321 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9322 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9323 VK = RHS.get()->getValueKind(); 9324 OK = RHS.get()->getObjectKind(); 9325 } 9326 break; 9327 } 9328 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9329 return ExprError(); 9330 9331 // Check for array bounds violations for both sides of the BinaryOperator 9332 CheckArrayAccess(LHS.get()); 9333 CheckArrayAccess(RHS.get()); 9334 9335 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9336 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9337 &Context.Idents.get("object_setClass"), 9338 SourceLocation(), LookupOrdinaryName); 9339 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9340 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9341 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9342 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9343 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9344 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9345 } 9346 else 9347 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9348 } 9349 else if (const ObjCIvarRefExpr *OIRE = 9350 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9351 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9352 9353 if (CompResultTy.isNull()) 9354 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 9355 ResultTy, VK, OK, OpLoc, 9356 FPFeatures.fp_contract)); 9357 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9358 OK_ObjCProperty) { 9359 VK = VK_LValue; 9360 OK = LHS.get()->getObjectKind(); 9361 } 9362 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 9363 ResultTy, VK, OK, CompLHSTy, 9364 CompResultTy, OpLoc, 9365 FPFeatures.fp_contract)); 9366 } 9367 9368 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9369 /// operators are mixed in a way that suggests that the programmer forgot that 9370 /// comparison operators have higher precedence. The most typical example of 9371 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9372 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9373 SourceLocation OpLoc, Expr *LHSExpr, 9374 Expr *RHSExpr) { 9375 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9376 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9377 9378 // Check that one of the sides is a comparison operator. 9379 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9380 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9381 if (!isLeftComp && !isRightComp) 9382 return; 9383 9384 // Bitwise operations are sometimes used as eager logical ops. 9385 // Don't diagnose this. 9386 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9387 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9388 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9389 return; 9390 9391 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9392 OpLoc) 9393 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9394 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9395 SourceRange ParensRange = isLeftComp ? 9396 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9397 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9398 9399 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9400 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9401 SuggestParentheses(Self, OpLoc, 9402 Self.PDiag(diag::note_precedence_silence) << OpStr, 9403 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9404 SuggestParentheses(Self, OpLoc, 9405 Self.PDiag(diag::note_precedence_bitwise_first) 9406 << BinaryOperator::getOpcodeStr(Opc), 9407 ParensRange); 9408 } 9409 9410 /// \brief It accepts a '&' expr that is inside a '|' one. 9411 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9412 /// in parentheses. 9413 static void 9414 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9415 BinaryOperator *Bop) { 9416 assert(Bop->getOpcode() == BO_And); 9417 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9418 << Bop->getSourceRange() << OpLoc; 9419 SuggestParentheses(Self, Bop->getOperatorLoc(), 9420 Self.PDiag(diag::note_precedence_silence) 9421 << Bop->getOpcodeStr(), 9422 Bop->getSourceRange()); 9423 } 9424 9425 /// \brief It accepts a '&&' expr that is inside a '||' one. 9426 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9427 /// in parentheses. 9428 static void 9429 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9430 BinaryOperator *Bop) { 9431 assert(Bop->getOpcode() == BO_LAnd); 9432 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9433 << Bop->getSourceRange() << OpLoc; 9434 SuggestParentheses(Self, Bop->getOperatorLoc(), 9435 Self.PDiag(diag::note_precedence_silence) 9436 << Bop->getOpcodeStr(), 9437 Bop->getSourceRange()); 9438 } 9439 9440 /// \brief Returns true if the given expression can be evaluated as a constant 9441 /// 'true'. 9442 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9443 bool Res; 9444 return !E->isValueDependent() && 9445 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9446 } 9447 9448 /// \brief Returns true if the given expression can be evaluated as a constant 9449 /// 'false'. 9450 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9451 bool Res; 9452 return !E->isValueDependent() && 9453 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9454 } 9455 9456 /// \brief Look for '&&' in the left hand of a '||' expr. 9457 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9458 Expr *LHSExpr, Expr *RHSExpr) { 9459 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9460 if (Bop->getOpcode() == BO_LAnd) { 9461 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9462 if (EvaluatesAsFalse(S, RHSExpr)) 9463 return; 9464 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9465 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9466 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9467 } else if (Bop->getOpcode() == BO_LOr) { 9468 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9469 // If it's "a || b && 1 || c" we didn't warn earlier for 9470 // "a || b && 1", but warn now. 9471 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9472 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9473 } 9474 } 9475 } 9476 } 9477 9478 /// \brief Look for '&&' in the right hand of a '||' expr. 9479 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9480 Expr *LHSExpr, Expr *RHSExpr) { 9481 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9482 if (Bop->getOpcode() == BO_LAnd) { 9483 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9484 if (EvaluatesAsFalse(S, LHSExpr)) 9485 return; 9486 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9487 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9488 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9489 } 9490 } 9491 } 9492 9493 /// \brief Look for '&' in the left or right hand of a '|' expr. 9494 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9495 Expr *OrArg) { 9496 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9497 if (Bop->getOpcode() == BO_And) 9498 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9499 } 9500 } 9501 9502 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9503 Expr *SubExpr, StringRef Shift) { 9504 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9505 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9506 StringRef Op = Bop->getOpcodeStr(); 9507 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9508 << Bop->getSourceRange() << OpLoc << Shift << Op; 9509 SuggestParentheses(S, Bop->getOperatorLoc(), 9510 S.PDiag(diag::note_precedence_silence) << Op, 9511 Bop->getSourceRange()); 9512 } 9513 } 9514 } 9515 9516 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9517 Expr *LHSExpr, Expr *RHSExpr) { 9518 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9519 if (!OCE) 9520 return; 9521 9522 FunctionDecl *FD = OCE->getDirectCallee(); 9523 if (!FD || !FD->isOverloadedOperator()) 9524 return; 9525 9526 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9527 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9528 return; 9529 9530 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9531 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9532 << (Kind == OO_LessLess); 9533 SuggestParentheses(S, OCE->getOperatorLoc(), 9534 S.PDiag(diag::note_precedence_silence) 9535 << (Kind == OO_LessLess ? "<<" : ">>"), 9536 OCE->getSourceRange()); 9537 SuggestParentheses(S, OpLoc, 9538 S.PDiag(diag::note_evaluate_comparison_first), 9539 SourceRange(OCE->getArg(1)->getLocStart(), 9540 RHSExpr->getLocEnd())); 9541 } 9542 9543 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9544 /// precedence. 9545 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9546 SourceLocation OpLoc, Expr *LHSExpr, 9547 Expr *RHSExpr){ 9548 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9549 if (BinaryOperator::isBitwiseOp(Opc)) 9550 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9551 9552 // Diagnose "arg1 & arg2 | arg3" 9553 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9554 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9555 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9556 } 9557 9558 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9559 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9560 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9561 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9562 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9563 } 9564 9565 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9566 || Opc == BO_Shr) { 9567 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9568 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9569 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9570 } 9571 9572 // Warn on overloaded shift operators and comparisons, such as: 9573 // cout << 5 == 4; 9574 if (BinaryOperator::isComparisonOp(Opc)) 9575 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9576 } 9577 9578 // Binary Operators. 'Tok' is the token for the operator. 9579 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9580 tok::TokenKind Kind, 9581 Expr *LHSExpr, Expr *RHSExpr) { 9582 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9583 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9584 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9585 9586 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9587 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9588 9589 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9590 } 9591 9592 /// Build an overloaded binary operator expression in the given scope. 9593 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9594 BinaryOperatorKind Opc, 9595 Expr *LHS, Expr *RHS) { 9596 // Find all of the overloaded operators visible from this 9597 // point. We perform both an operator-name lookup from the local 9598 // scope and an argument-dependent lookup based on the types of 9599 // the arguments. 9600 UnresolvedSet<16> Functions; 9601 OverloadedOperatorKind OverOp 9602 = BinaryOperator::getOverloadedOperator(Opc); 9603 if (Sc && OverOp != OO_None) 9604 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9605 RHS->getType(), Functions); 9606 9607 // Build the (potentially-overloaded, potentially-dependent) 9608 // binary operation. 9609 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9610 } 9611 9612 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9613 BinaryOperatorKind Opc, 9614 Expr *LHSExpr, Expr *RHSExpr) { 9615 // We want to end up calling one of checkPseudoObjectAssignment 9616 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9617 // both expressions are overloadable or either is type-dependent), 9618 // or CreateBuiltinBinOp (in any other case). We also want to get 9619 // any placeholder types out of the way. 9620 9621 // Handle pseudo-objects in the LHS. 9622 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9623 // Assignments with a pseudo-object l-value need special analysis. 9624 if (pty->getKind() == BuiltinType::PseudoObject && 9625 BinaryOperator::isAssignmentOp(Opc)) 9626 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9627 9628 // Don't resolve overloads if the other type is overloadable. 9629 if (pty->getKind() == BuiltinType::Overload) { 9630 // We can't actually test that if we still have a placeholder, 9631 // though. Fortunately, none of the exceptions we see in that 9632 // code below are valid when the LHS is an overload set. Note 9633 // that an overload set can be dependently-typed, but it never 9634 // instantiates to having an overloadable type. 9635 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9636 if (resolvedRHS.isInvalid()) return ExprError(); 9637 RHSExpr = resolvedRHS.take(); 9638 9639 if (RHSExpr->isTypeDependent() || 9640 RHSExpr->getType()->isOverloadableType()) 9641 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9642 } 9643 9644 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9645 if (LHS.isInvalid()) return ExprError(); 9646 LHSExpr = LHS.take(); 9647 } 9648 9649 // Handle pseudo-objects in the RHS. 9650 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9651 // An overload in the RHS can potentially be resolved by the type 9652 // being assigned to. 9653 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9654 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9655 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9656 9657 if (LHSExpr->getType()->isOverloadableType()) 9658 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9659 9660 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9661 } 9662 9663 // Don't resolve overloads if the other type is overloadable. 9664 if (pty->getKind() == BuiltinType::Overload && 9665 LHSExpr->getType()->isOverloadableType()) 9666 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9667 9668 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9669 if (!resolvedRHS.isUsable()) return ExprError(); 9670 RHSExpr = resolvedRHS.take(); 9671 } 9672 9673 if (getLangOpts().CPlusPlus) { 9674 // If either expression is type-dependent, always build an 9675 // overloaded op. 9676 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9677 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9678 9679 // Otherwise, build an overloaded op if either expression has an 9680 // overloadable type. 9681 if (LHSExpr->getType()->isOverloadableType() || 9682 RHSExpr->getType()->isOverloadableType()) 9683 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9684 } 9685 9686 // Build a built-in binary operation. 9687 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9688 } 9689 9690 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9691 UnaryOperatorKind Opc, 9692 Expr *InputExpr) { 9693 ExprResult Input = Owned(InputExpr); 9694 ExprValueKind VK = VK_RValue; 9695 ExprObjectKind OK = OK_Ordinary; 9696 QualType resultType; 9697 switch (Opc) { 9698 case UO_PreInc: 9699 case UO_PreDec: 9700 case UO_PostInc: 9701 case UO_PostDec: 9702 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9703 Opc == UO_PreInc || 9704 Opc == UO_PostInc, 9705 Opc == UO_PreInc || 9706 Opc == UO_PreDec); 9707 break; 9708 case UO_AddrOf: 9709 resultType = CheckAddressOfOperand(Input, OpLoc); 9710 break; 9711 case UO_Deref: { 9712 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9713 if (Input.isInvalid()) return ExprError(); 9714 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9715 break; 9716 } 9717 case UO_Plus: 9718 case UO_Minus: 9719 Input = UsualUnaryConversions(Input.take()); 9720 if (Input.isInvalid()) return ExprError(); 9721 resultType = Input.get()->getType(); 9722 if (resultType->isDependentType()) 9723 break; 9724 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9725 resultType->isVectorType()) 9726 break; 9727 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9728 Opc == UO_Plus && 9729 resultType->isPointerType()) 9730 break; 9731 9732 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9733 << resultType << Input.get()->getSourceRange()); 9734 9735 case UO_Not: // bitwise complement 9736 Input = UsualUnaryConversions(Input.take()); 9737 if (Input.isInvalid()) 9738 return ExprError(); 9739 resultType = Input.get()->getType(); 9740 if (resultType->isDependentType()) 9741 break; 9742 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9743 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9744 // C99 does not support '~' for complex conjugation. 9745 Diag(OpLoc, diag::ext_integer_complement_complex) 9746 << resultType << Input.get()->getSourceRange(); 9747 else if (resultType->hasIntegerRepresentation()) 9748 break; 9749 else if (resultType->isExtVectorType()) { 9750 if (Context.getLangOpts().OpenCL) { 9751 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9752 // on vector float types. 9753 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9754 if (!T->isIntegerType()) 9755 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9756 << resultType << Input.get()->getSourceRange()); 9757 } 9758 break; 9759 } else { 9760 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9761 << resultType << Input.get()->getSourceRange()); 9762 } 9763 break; 9764 9765 case UO_LNot: // logical negation 9766 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9767 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9768 if (Input.isInvalid()) return ExprError(); 9769 resultType = Input.get()->getType(); 9770 9771 // Though we still have to promote half FP to float... 9772 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9773 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9774 resultType = Context.FloatTy; 9775 } 9776 9777 if (resultType->isDependentType()) 9778 break; 9779 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 9780 // C99 6.5.3.3p1: ok, fallthrough; 9781 if (Context.getLangOpts().CPlusPlus) { 9782 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9783 // operand contextually converted to bool. 9784 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9785 ScalarTypeToBooleanCastKind(resultType)); 9786 } else if (Context.getLangOpts().OpenCL && 9787 Context.getLangOpts().OpenCLVersion < 120) { 9788 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9789 // operate on scalar float types. 9790 if (!resultType->isIntegerType()) 9791 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9792 << resultType << Input.get()->getSourceRange()); 9793 } 9794 } else if (resultType->isExtVectorType()) { 9795 if (Context.getLangOpts().OpenCL && 9796 Context.getLangOpts().OpenCLVersion < 120) { 9797 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9798 // operate on vector float types. 9799 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9800 if (!T->isIntegerType()) 9801 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9802 << resultType << Input.get()->getSourceRange()); 9803 } 9804 // Vector logical not returns the signed variant of the operand type. 9805 resultType = GetSignedVectorType(resultType); 9806 break; 9807 } else { 9808 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9809 << resultType << Input.get()->getSourceRange()); 9810 } 9811 9812 // LNot always has type int. C99 6.5.3.3p5. 9813 // In C++, it's bool. C++ 5.3.1p8 9814 resultType = Context.getLogicalOperationType(); 9815 break; 9816 case UO_Real: 9817 case UO_Imag: 9818 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9819 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9820 // complex l-values to ordinary l-values and all other values to r-values. 9821 if (Input.isInvalid()) return ExprError(); 9822 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9823 if (Input.get()->getValueKind() != VK_RValue && 9824 Input.get()->getObjectKind() == OK_Ordinary) 9825 VK = Input.get()->getValueKind(); 9826 } else if (!getLangOpts().CPlusPlus) { 9827 // In C, a volatile scalar is read by __imag. In C++, it is not. 9828 Input = DefaultLvalueConversion(Input.take()); 9829 } 9830 break; 9831 case UO_Extension: 9832 resultType = Input.get()->getType(); 9833 VK = Input.get()->getValueKind(); 9834 OK = Input.get()->getObjectKind(); 9835 break; 9836 } 9837 if (resultType.isNull() || Input.isInvalid()) 9838 return ExprError(); 9839 9840 // Check for array bounds violations in the operand of the UnaryOperator, 9841 // except for the '*' and '&' operators that have to be handled specially 9842 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9843 // that are explicitly defined as valid by the standard). 9844 if (Opc != UO_AddrOf && Opc != UO_Deref) 9845 CheckArrayAccess(Input.get()); 9846 9847 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9848 VK, OK, OpLoc)); 9849 } 9850 9851 /// \brief Determine whether the given expression is a qualified member 9852 /// access expression, of a form that could be turned into a pointer to member 9853 /// with the address-of operator. 9854 static bool isQualifiedMemberAccess(Expr *E) { 9855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9856 if (!DRE->getQualifier()) 9857 return false; 9858 9859 ValueDecl *VD = DRE->getDecl(); 9860 if (!VD->isCXXClassMember()) 9861 return false; 9862 9863 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9864 return true; 9865 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9866 return Method->isInstance(); 9867 9868 return false; 9869 } 9870 9871 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9872 if (!ULE->getQualifier()) 9873 return false; 9874 9875 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9876 DEnd = ULE->decls_end(); 9877 D != DEnd; ++D) { 9878 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9879 if (Method->isInstance()) 9880 return true; 9881 } else { 9882 // Overload set does not contain methods. 9883 break; 9884 } 9885 } 9886 9887 return false; 9888 } 9889 9890 return false; 9891 } 9892 9893 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9894 UnaryOperatorKind Opc, Expr *Input) { 9895 // First things first: handle placeholders so that the 9896 // overloaded-operator check considers the right type. 9897 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9898 // Increment and decrement of pseudo-object references. 9899 if (pty->getKind() == BuiltinType::PseudoObject && 9900 UnaryOperator::isIncrementDecrementOp(Opc)) 9901 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9902 9903 // extension is always a builtin operator. 9904 if (Opc == UO_Extension) 9905 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9906 9907 // & gets special logic for several kinds of placeholder. 9908 // The builtin code knows what to do. 9909 if (Opc == UO_AddrOf && 9910 (pty->getKind() == BuiltinType::Overload || 9911 pty->getKind() == BuiltinType::UnknownAny || 9912 pty->getKind() == BuiltinType::BoundMember)) 9913 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9914 9915 // Anything else needs to be handled now. 9916 ExprResult Result = CheckPlaceholderExpr(Input); 9917 if (Result.isInvalid()) return ExprError(); 9918 Input = Result.take(); 9919 } 9920 9921 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9922 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9923 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9924 // Find all of the overloaded operators visible from this 9925 // point. We perform both an operator-name lookup from the local 9926 // scope and an argument-dependent lookup based on the types of 9927 // the arguments. 9928 UnresolvedSet<16> Functions; 9929 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9930 if (S && OverOp != OO_None) 9931 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9932 Functions); 9933 9934 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9935 } 9936 9937 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9938 } 9939 9940 // Unary Operators. 'Tok' is the token for the operator. 9941 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9942 tok::TokenKind Op, Expr *Input) { 9943 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9944 } 9945 9946 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9947 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9948 LabelDecl *TheDecl) { 9949 TheDecl->markUsed(Context); 9950 // Create the AST node. The address of a label always has type 'void*'. 9951 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9952 Context.getPointerType(Context.VoidTy))); 9953 } 9954 9955 /// Given the last statement in a statement-expression, check whether 9956 /// the result is a producing expression (like a call to an 9957 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9958 /// release out of the full-expression. Otherwise, return null. 9959 /// Cannot fail. 9960 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9961 // Should always be wrapped with one of these. 9962 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9963 if (!cleanups) return 0; 9964 9965 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9966 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9967 return 0; 9968 9969 // Splice out the cast. This shouldn't modify any interesting 9970 // features of the statement. 9971 Expr *producer = cast->getSubExpr(); 9972 assert(producer->getType() == cast->getType()); 9973 assert(producer->getValueKind() == cast->getValueKind()); 9974 cleanups->setSubExpr(producer); 9975 return cleanups; 9976 } 9977 9978 void Sema::ActOnStartStmtExpr() { 9979 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9980 } 9981 9982 void Sema::ActOnStmtExprError() { 9983 // Note that function is also called by TreeTransform when leaving a 9984 // StmtExpr scope without rebuilding anything. 9985 9986 DiscardCleanupsInEvaluationContext(); 9987 PopExpressionEvaluationContext(); 9988 } 9989 9990 ExprResult 9991 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9992 SourceLocation RPLoc) { // "({..})" 9993 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9994 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9995 9996 if (hasAnyUnrecoverableErrorsInThisFunction()) 9997 DiscardCleanupsInEvaluationContext(); 9998 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9999 PopExpressionEvaluationContext(); 10000 10001 bool isFileScope 10002 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 10003 if (isFileScope) 10004 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 10005 10006 // FIXME: there are a variety of strange constraints to enforce here, for 10007 // example, it is not possible to goto into a stmt expression apparently. 10008 // More semantic analysis is needed. 10009 10010 // If there are sub-stmts in the compound stmt, take the type of the last one 10011 // as the type of the stmtexpr. 10012 QualType Ty = Context.VoidTy; 10013 bool StmtExprMayBindToTemp = false; 10014 if (!Compound->body_empty()) { 10015 Stmt *LastStmt = Compound->body_back(); 10016 LabelStmt *LastLabelStmt = 0; 10017 // If LastStmt is a label, skip down through into the body. 10018 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 10019 LastLabelStmt = Label; 10020 LastStmt = Label->getSubStmt(); 10021 } 10022 10023 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 10024 // Do function/array conversion on the last expression, but not 10025 // lvalue-to-rvalue. However, initialize an unqualified type. 10026 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 10027 if (LastExpr.isInvalid()) 10028 return ExprError(); 10029 Ty = LastExpr.get()->getType().getUnqualifiedType(); 10030 10031 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 10032 // In ARC, if the final expression ends in a consume, splice 10033 // the consume out and bind it later. In the alternate case 10034 // (when dealing with a retainable type), the result 10035 // initialization will create a produce. In both cases the 10036 // result will be +1, and we'll need to balance that out with 10037 // a bind. 10038 if (Expr *rebuiltLastStmt 10039 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 10040 LastExpr = rebuiltLastStmt; 10041 } else { 10042 LastExpr = PerformCopyInitialization( 10043 InitializedEntity::InitializeResult(LPLoc, 10044 Ty, 10045 false), 10046 SourceLocation(), 10047 LastExpr); 10048 } 10049 10050 if (LastExpr.isInvalid()) 10051 return ExprError(); 10052 if (LastExpr.get() != 0) { 10053 if (!LastLabelStmt) 10054 Compound->setLastStmt(LastExpr.take()); 10055 else 10056 LastLabelStmt->setSubStmt(LastExpr.take()); 10057 StmtExprMayBindToTemp = true; 10058 } 10059 } 10060 } 10061 } 10062 10063 // FIXME: Check that expression type is complete/non-abstract; statement 10064 // expressions are not lvalues. 10065 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 10066 if (StmtExprMayBindToTemp) 10067 return MaybeBindToTemporary(ResStmtExpr); 10068 return Owned(ResStmtExpr); 10069 } 10070 10071 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 10072 TypeSourceInfo *TInfo, 10073 OffsetOfComponent *CompPtr, 10074 unsigned NumComponents, 10075 SourceLocation RParenLoc) { 10076 QualType ArgTy = TInfo->getType(); 10077 bool Dependent = ArgTy->isDependentType(); 10078 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 10079 10080 // We must have at least one component that refers to the type, and the first 10081 // one is known to be a field designator. Verify that the ArgTy represents 10082 // a struct/union/class. 10083 if (!Dependent && !ArgTy->isRecordType()) 10084 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 10085 << ArgTy << TypeRange); 10086 10087 // Type must be complete per C99 7.17p3 because a declaring a variable 10088 // with an incomplete type would be ill-formed. 10089 if (!Dependent 10090 && RequireCompleteType(BuiltinLoc, ArgTy, 10091 diag::err_offsetof_incomplete_type, TypeRange)) 10092 return ExprError(); 10093 10094 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 10095 // GCC extension, diagnose them. 10096 // FIXME: This diagnostic isn't actually visible because the location is in 10097 // a system header! 10098 if (NumComponents != 1) 10099 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 10100 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 10101 10102 bool DidWarnAboutNonPOD = false; 10103 QualType CurrentType = ArgTy; 10104 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 10105 SmallVector<OffsetOfNode, 4> Comps; 10106 SmallVector<Expr*, 4> Exprs; 10107 for (unsigned i = 0; i != NumComponents; ++i) { 10108 const OffsetOfComponent &OC = CompPtr[i]; 10109 if (OC.isBrackets) { 10110 // Offset of an array sub-field. TODO: Should we allow vector elements? 10111 if (!CurrentType->isDependentType()) { 10112 const ArrayType *AT = Context.getAsArrayType(CurrentType); 10113 if(!AT) 10114 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 10115 << CurrentType); 10116 CurrentType = AT->getElementType(); 10117 } else 10118 CurrentType = Context.DependentTy; 10119 10120 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 10121 if (IdxRval.isInvalid()) 10122 return ExprError(); 10123 Expr *Idx = IdxRval.take(); 10124 10125 // The expression must be an integral expression. 10126 // FIXME: An integral constant expression? 10127 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 10128 !Idx->getType()->isIntegerType()) 10129 return ExprError(Diag(Idx->getLocStart(), 10130 diag::err_typecheck_subscript_not_integer) 10131 << Idx->getSourceRange()); 10132 10133 // Record this array index. 10134 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 10135 Exprs.push_back(Idx); 10136 continue; 10137 } 10138 10139 // Offset of a field. 10140 if (CurrentType->isDependentType()) { 10141 // We have the offset of a field, but we can't look into the dependent 10142 // type. Just record the identifier of the field. 10143 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10144 CurrentType = Context.DependentTy; 10145 continue; 10146 } 10147 10148 // We need to have a complete type to look into. 10149 if (RequireCompleteType(OC.LocStart, CurrentType, 10150 diag::err_offsetof_incomplete_type)) 10151 return ExprError(); 10152 10153 // Look for the designated field. 10154 const RecordType *RC = CurrentType->getAs<RecordType>(); 10155 if (!RC) 10156 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10157 << CurrentType); 10158 RecordDecl *RD = RC->getDecl(); 10159 10160 // C++ [lib.support.types]p5: 10161 // The macro offsetof accepts a restricted set of type arguments in this 10162 // International Standard. type shall be a POD structure or a POD union 10163 // (clause 9). 10164 // C++11 [support.types]p4: 10165 // If type is not a standard-layout class (Clause 9), the results are 10166 // undefined. 10167 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10168 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10169 unsigned DiagID = 10170 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 10171 : diag::warn_offsetof_non_pod_type; 10172 10173 if (!IsSafe && !DidWarnAboutNonPOD && 10174 DiagRuntimeBehavior(BuiltinLoc, 0, 10175 PDiag(DiagID) 10176 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10177 << CurrentType)) 10178 DidWarnAboutNonPOD = true; 10179 } 10180 10181 // Look for the field. 10182 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10183 LookupQualifiedName(R, RD); 10184 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 10185 IndirectFieldDecl *IndirectMemberDecl = 0; 10186 if (!MemberDecl) { 10187 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 10188 MemberDecl = IndirectMemberDecl->getAnonField(); 10189 } 10190 10191 if (!MemberDecl) 10192 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 10193 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 10194 OC.LocEnd)); 10195 10196 // C99 7.17p3: 10197 // (If the specified member is a bit-field, the behavior is undefined.) 10198 // 10199 // We diagnose this as an error. 10200 if (MemberDecl->isBitField()) { 10201 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 10202 << MemberDecl->getDeclName() 10203 << SourceRange(BuiltinLoc, RParenLoc); 10204 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 10205 return ExprError(); 10206 } 10207 10208 RecordDecl *Parent = MemberDecl->getParent(); 10209 if (IndirectMemberDecl) 10210 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 10211 10212 // If the member was found in a base class, introduce OffsetOfNodes for 10213 // the base class indirections. 10214 CXXBasePaths Paths; 10215 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 10216 if (Paths.getDetectedVirtual()) { 10217 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 10218 << MemberDecl->getDeclName() 10219 << SourceRange(BuiltinLoc, RParenLoc); 10220 return ExprError(); 10221 } 10222 10223 CXXBasePath &Path = Paths.front(); 10224 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10225 B != BEnd; ++B) 10226 Comps.push_back(OffsetOfNode(B->Base)); 10227 } 10228 10229 if (IndirectMemberDecl) { 10230 for (auto *FI : IndirectMemberDecl->chain()) { 10231 assert(isa<FieldDecl>(FI)); 10232 Comps.push_back(OffsetOfNode(OC.LocStart, 10233 cast<FieldDecl>(FI), OC.LocEnd)); 10234 } 10235 } else 10236 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10237 10238 CurrentType = MemberDecl->getType().getNonReferenceType(); 10239 } 10240 10241 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 10242 TInfo, Comps, Exprs, RParenLoc)); 10243 } 10244 10245 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10246 SourceLocation BuiltinLoc, 10247 SourceLocation TypeLoc, 10248 ParsedType ParsedArgTy, 10249 OffsetOfComponent *CompPtr, 10250 unsigned NumComponents, 10251 SourceLocation RParenLoc) { 10252 10253 TypeSourceInfo *ArgTInfo; 10254 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10255 if (ArgTy.isNull()) 10256 return ExprError(); 10257 10258 if (!ArgTInfo) 10259 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10260 10261 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10262 RParenLoc); 10263 } 10264 10265 10266 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10267 Expr *CondExpr, 10268 Expr *LHSExpr, Expr *RHSExpr, 10269 SourceLocation RPLoc) { 10270 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10271 10272 ExprValueKind VK = VK_RValue; 10273 ExprObjectKind OK = OK_Ordinary; 10274 QualType resType; 10275 bool ValueDependent = false; 10276 bool CondIsTrue = false; 10277 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10278 resType = Context.DependentTy; 10279 ValueDependent = true; 10280 } else { 10281 // The conditional expression is required to be a constant expression. 10282 llvm::APSInt condEval(32); 10283 ExprResult CondICE 10284 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10285 diag::err_typecheck_choose_expr_requires_constant, false); 10286 if (CondICE.isInvalid()) 10287 return ExprError(); 10288 CondExpr = CondICE.take(); 10289 CondIsTrue = condEval.getZExtValue(); 10290 10291 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10292 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10293 10294 resType = ActiveExpr->getType(); 10295 ValueDependent = ActiveExpr->isValueDependent(); 10296 VK = ActiveExpr->getValueKind(); 10297 OK = ActiveExpr->getObjectKind(); 10298 } 10299 10300 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 10301 resType, VK, OK, RPLoc, CondIsTrue, 10302 resType->isDependentType(), 10303 ValueDependent)); 10304 } 10305 10306 //===----------------------------------------------------------------------===// 10307 // Clang Extensions. 10308 //===----------------------------------------------------------------------===// 10309 10310 /// ActOnBlockStart - This callback is invoked when a block literal is started. 10311 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10312 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10313 10314 if (LangOpts.CPlusPlus) { 10315 Decl *ManglingContextDecl; 10316 if (MangleNumberingContext *MCtx = 10317 getCurrentMangleNumberContext(Block->getDeclContext(), 10318 ManglingContextDecl)) { 10319 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10320 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10321 } 10322 } 10323 10324 PushBlockScope(CurScope, Block); 10325 CurContext->addDecl(Block); 10326 if (CurScope) 10327 PushDeclContext(CurScope, Block); 10328 else 10329 CurContext = Block; 10330 10331 getCurBlock()->HasImplicitReturnType = true; 10332 10333 // Enter a new evaluation context to insulate the block from any 10334 // cleanups from the enclosing full-expression. 10335 PushExpressionEvaluationContext(PotentiallyEvaluated); 10336 } 10337 10338 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10339 Scope *CurScope) { 10340 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 10341 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10342 BlockScopeInfo *CurBlock = getCurBlock(); 10343 10344 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10345 QualType T = Sig->getType(); 10346 10347 // FIXME: We should allow unexpanded parameter packs here, but that would, 10348 // in turn, make the block expression contain unexpanded parameter packs. 10349 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10350 // Drop the parameters. 10351 FunctionProtoType::ExtProtoInfo EPI; 10352 EPI.HasTrailingReturn = false; 10353 EPI.TypeQuals |= DeclSpec::TQ_const; 10354 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10355 Sig = Context.getTrivialTypeSourceInfo(T); 10356 } 10357 10358 // GetTypeForDeclarator always produces a function type for a block 10359 // literal signature. Furthermore, it is always a FunctionProtoType 10360 // unless the function was written with a typedef. 10361 assert(T->isFunctionType() && 10362 "GetTypeForDeclarator made a non-function block signature"); 10363 10364 // Look for an explicit signature in that function type. 10365 FunctionProtoTypeLoc ExplicitSignature; 10366 10367 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10368 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10369 10370 // Check whether that explicit signature was synthesized by 10371 // GetTypeForDeclarator. If so, don't save that as part of the 10372 // written signature. 10373 if (ExplicitSignature.getLocalRangeBegin() == 10374 ExplicitSignature.getLocalRangeEnd()) { 10375 // This would be much cheaper if we stored TypeLocs instead of 10376 // TypeSourceInfos. 10377 TypeLoc Result = ExplicitSignature.getReturnLoc(); 10378 unsigned Size = Result.getFullDataSize(); 10379 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10380 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10381 10382 ExplicitSignature = FunctionProtoTypeLoc(); 10383 } 10384 } 10385 10386 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10387 CurBlock->FunctionType = T; 10388 10389 const FunctionType *Fn = T->getAs<FunctionType>(); 10390 QualType RetTy = Fn->getReturnType(); 10391 bool isVariadic = 10392 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10393 10394 CurBlock->TheDecl->setIsVariadic(isVariadic); 10395 10396 // Context.DependentTy is used as a placeholder for a missing block 10397 // return type. TODO: what should we do with declarators like: 10398 // ^ * { ... } 10399 // If the answer is "apply template argument deduction".... 10400 if (RetTy != Context.DependentTy) { 10401 CurBlock->ReturnType = RetTy; 10402 CurBlock->TheDecl->setBlockMissingReturnType(false); 10403 CurBlock->HasImplicitReturnType = false; 10404 } 10405 10406 // Push block parameters from the declarator if we had them. 10407 SmallVector<ParmVarDecl*, 8> Params; 10408 if (ExplicitSignature) { 10409 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 10410 ParmVarDecl *Param = ExplicitSignature.getParam(I); 10411 if (Param->getIdentifier() == 0 && 10412 !Param->isImplicit() && 10413 !Param->isInvalidDecl() && 10414 !getLangOpts().CPlusPlus) 10415 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10416 Params.push_back(Param); 10417 } 10418 10419 // Fake up parameter variables if we have a typedef, like 10420 // ^ fntype { ... } 10421 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10422 for (const auto &I : Fn->param_types()) { 10423 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 10424 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 10425 Params.push_back(Param); 10426 } 10427 } 10428 10429 // Set the parameters on the block decl. 10430 if (!Params.empty()) { 10431 CurBlock->TheDecl->setParams(Params); 10432 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10433 CurBlock->TheDecl->param_end(), 10434 /*CheckParameterNames=*/false); 10435 } 10436 10437 // Finally we can process decl attributes. 10438 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10439 10440 // Put the parameter variables in scope. 10441 for (auto AI : CurBlock->TheDecl->params()) { 10442 AI->setOwningFunction(CurBlock->TheDecl); 10443 10444 // If this has an identifier, add it to the scope stack. 10445 if (AI->getIdentifier()) { 10446 CheckShadow(CurBlock->TheScope, AI); 10447 10448 PushOnScopeChains(AI, CurBlock->TheScope); 10449 } 10450 } 10451 } 10452 10453 /// ActOnBlockError - If there is an error parsing a block, this callback 10454 /// is invoked to pop the information about the block from the action impl. 10455 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10456 // Leave the expression-evaluation context. 10457 DiscardCleanupsInEvaluationContext(); 10458 PopExpressionEvaluationContext(); 10459 10460 // Pop off CurBlock, handle nested blocks. 10461 PopDeclContext(); 10462 PopFunctionScopeInfo(); 10463 } 10464 10465 /// ActOnBlockStmtExpr - This is called when the body of a block statement 10466 /// literal was successfully completed. ^(int x){...} 10467 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10468 Stmt *Body, Scope *CurScope) { 10469 // If blocks are disabled, emit an error. 10470 if (!LangOpts.Blocks) 10471 Diag(CaretLoc, diag::err_blocks_disable); 10472 10473 // Leave the expression-evaluation context. 10474 if (hasAnyUnrecoverableErrorsInThisFunction()) 10475 DiscardCleanupsInEvaluationContext(); 10476 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10477 PopExpressionEvaluationContext(); 10478 10479 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10480 10481 if (BSI->HasImplicitReturnType) 10482 deduceClosureReturnType(*BSI); 10483 10484 PopDeclContext(); 10485 10486 QualType RetTy = Context.VoidTy; 10487 if (!BSI->ReturnType.isNull()) 10488 RetTy = BSI->ReturnType; 10489 10490 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 10491 QualType BlockTy; 10492 10493 // Set the captured variables on the block. 10494 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10495 SmallVector<BlockDecl::Capture, 4> Captures; 10496 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10497 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10498 if (Cap.isThisCapture()) 10499 continue; 10500 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10501 Cap.isNested(), Cap.getInitExpr()); 10502 Captures.push_back(NewCap); 10503 } 10504 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10505 BSI->CXXThisCaptureIndex != 0); 10506 10507 // If the user wrote a function type in some form, try to use that. 10508 if (!BSI->FunctionType.isNull()) { 10509 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10510 10511 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10512 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10513 10514 // Turn protoless block types into nullary block types. 10515 if (isa<FunctionNoProtoType>(FTy)) { 10516 FunctionProtoType::ExtProtoInfo EPI; 10517 EPI.ExtInfo = Ext; 10518 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10519 10520 // Otherwise, if we don't need to change anything about the function type, 10521 // preserve its sugar structure. 10522 } else if (FTy->getReturnType() == RetTy && 10523 (!NoReturn || FTy->getNoReturnAttr())) { 10524 BlockTy = BSI->FunctionType; 10525 10526 // Otherwise, make the minimal modifications to the function type. 10527 } else { 10528 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10529 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10530 EPI.TypeQuals = 0; // FIXME: silently? 10531 EPI.ExtInfo = Ext; 10532 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 10533 } 10534 10535 // If we don't have a function type, just build one from nothing. 10536 } else { 10537 FunctionProtoType::ExtProtoInfo EPI; 10538 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10539 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10540 } 10541 10542 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10543 BSI->TheDecl->param_end()); 10544 BlockTy = Context.getBlockPointerType(BlockTy); 10545 10546 // If needed, diagnose invalid gotos and switches in the block. 10547 if (getCurFunction()->NeedsScopeChecking() && 10548 !hasAnyUnrecoverableErrorsInThisFunction() && 10549 !PP.isCodeCompletionEnabled()) 10550 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10551 10552 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10553 10554 // Try to apply the named return value optimization. We have to check again 10555 // if we can do this, though, because blocks keep return statements around 10556 // to deduce an implicit return type. 10557 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10558 !BSI->TheDecl->isDependentContext()) 10559 computeNRVO(Body, getCurBlock()); 10560 10561 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10562 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10563 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10564 10565 // If the block isn't obviously global, i.e. it captures anything at 10566 // all, then we need to do a few things in the surrounding context: 10567 if (Result->getBlockDecl()->hasCaptures()) { 10568 // First, this expression has a new cleanup object. 10569 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10570 ExprNeedsCleanups = true; 10571 10572 // It also gets a branch-protected scope if any of the captured 10573 // variables needs destruction. 10574 for (const auto &CI : Result->getBlockDecl()->captures()) { 10575 const VarDecl *var = CI.getVariable(); 10576 if (var->getType().isDestructedType() != QualType::DK_none) { 10577 getCurFunction()->setHasBranchProtectedScope(); 10578 break; 10579 } 10580 } 10581 } 10582 10583 return Owned(Result); 10584 } 10585 10586 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10587 Expr *E, ParsedType Ty, 10588 SourceLocation RPLoc) { 10589 TypeSourceInfo *TInfo; 10590 GetTypeFromParser(Ty, &TInfo); 10591 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10592 } 10593 10594 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10595 Expr *E, TypeSourceInfo *TInfo, 10596 SourceLocation RPLoc) { 10597 Expr *OrigExpr = E; 10598 10599 // Get the va_list type 10600 QualType VaListType = Context.getBuiltinVaListType(); 10601 if (VaListType->isArrayType()) { 10602 // Deal with implicit array decay; for example, on x86-64, 10603 // va_list is an array, but it's supposed to decay to 10604 // a pointer for va_arg. 10605 VaListType = Context.getArrayDecayedType(VaListType); 10606 // Make sure the input expression also decays appropriately. 10607 ExprResult Result = UsualUnaryConversions(E); 10608 if (Result.isInvalid()) 10609 return ExprError(); 10610 E = Result.take(); 10611 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10612 // If va_list is a record type and we are compiling in C++ mode, 10613 // check the argument using reference binding. 10614 InitializedEntity Entity 10615 = InitializedEntity::InitializeParameter(Context, 10616 Context.getLValueReferenceType(VaListType), false); 10617 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10618 if (Init.isInvalid()) 10619 return ExprError(); 10620 E = Init.takeAs<Expr>(); 10621 } else { 10622 // Otherwise, the va_list argument must be an l-value because 10623 // it is modified by va_arg. 10624 if (!E->isTypeDependent() && 10625 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10626 return ExprError(); 10627 } 10628 10629 if (!E->isTypeDependent() && 10630 !Context.hasSameType(VaListType, E->getType())) { 10631 return ExprError(Diag(E->getLocStart(), 10632 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10633 << OrigExpr->getType() << E->getSourceRange()); 10634 } 10635 10636 if (!TInfo->getType()->isDependentType()) { 10637 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10638 diag::err_second_parameter_to_va_arg_incomplete, 10639 TInfo->getTypeLoc())) 10640 return ExprError(); 10641 10642 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10643 TInfo->getType(), 10644 diag::err_second_parameter_to_va_arg_abstract, 10645 TInfo->getTypeLoc())) 10646 return ExprError(); 10647 10648 if (!TInfo->getType().isPODType(Context)) { 10649 Diag(TInfo->getTypeLoc().getBeginLoc(), 10650 TInfo->getType()->isObjCLifetimeType() 10651 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10652 : diag::warn_second_parameter_to_va_arg_not_pod) 10653 << TInfo->getType() 10654 << TInfo->getTypeLoc().getSourceRange(); 10655 } 10656 10657 // Check for va_arg where arguments of the given type will be promoted 10658 // (i.e. this va_arg is guaranteed to have undefined behavior). 10659 QualType PromoteType; 10660 if (TInfo->getType()->isPromotableIntegerType()) { 10661 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10662 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10663 PromoteType = QualType(); 10664 } 10665 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10666 PromoteType = Context.DoubleTy; 10667 if (!PromoteType.isNull()) 10668 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10669 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10670 << TInfo->getType() 10671 << PromoteType 10672 << TInfo->getTypeLoc().getSourceRange()); 10673 } 10674 10675 QualType T = TInfo->getType().getNonLValueExprType(Context); 10676 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10677 } 10678 10679 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10680 // The type of __null will be int or long, depending on the size of 10681 // pointers on the target. 10682 QualType Ty; 10683 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10684 if (pw == Context.getTargetInfo().getIntWidth()) 10685 Ty = Context.IntTy; 10686 else if (pw == Context.getTargetInfo().getLongWidth()) 10687 Ty = Context.LongTy; 10688 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10689 Ty = Context.LongLongTy; 10690 else { 10691 llvm_unreachable("I don't know size of pointer!"); 10692 } 10693 10694 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10695 } 10696 10697 bool 10698 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 10699 if (!getLangOpts().ObjC1) 10700 return false; 10701 10702 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10703 if (!PT) 10704 return false; 10705 10706 if (!PT->isObjCIdType()) { 10707 // Check if the destination is the 'NSString' interface. 10708 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10709 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10710 return false; 10711 } 10712 10713 // Ignore any parens, implicit casts (should only be 10714 // array-to-pointer decays), and not-so-opaque values. The last is 10715 // important for making this trigger for property assignments. 10716 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 10717 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10718 if (OV->getSourceExpr()) 10719 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10720 10721 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10722 if (!SL || !SL->isAscii()) 10723 return false; 10724 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 10725 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10726 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).take(); 10727 return true; 10728 } 10729 10730 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10731 SourceLocation Loc, 10732 QualType DstType, QualType SrcType, 10733 Expr *SrcExpr, AssignmentAction Action, 10734 bool *Complained) { 10735 if (Complained) 10736 *Complained = false; 10737 10738 // Decode the result (notice that AST's are still created for extensions). 10739 bool CheckInferredResultType = false; 10740 bool isInvalid = false; 10741 unsigned DiagKind = 0; 10742 FixItHint Hint; 10743 ConversionFixItGenerator ConvHints; 10744 bool MayHaveConvFixit = false; 10745 bool MayHaveFunctionDiff = false; 10746 10747 switch (ConvTy) { 10748 case Compatible: 10749 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10750 return false; 10751 10752 case PointerToInt: 10753 DiagKind = diag::ext_typecheck_convert_pointer_int; 10754 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10755 MayHaveConvFixit = true; 10756 break; 10757 case IntToPointer: 10758 DiagKind = diag::ext_typecheck_convert_int_pointer; 10759 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10760 MayHaveConvFixit = true; 10761 break; 10762 case IncompatiblePointer: 10763 DiagKind = 10764 (Action == AA_Passing_CFAudited ? 10765 diag::err_arc_typecheck_convert_incompatible_pointer : 10766 diag::ext_typecheck_convert_incompatible_pointer); 10767 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10768 SrcType->isObjCObjectPointerType(); 10769 if (Hint.isNull() && !CheckInferredResultType) { 10770 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10771 } 10772 else if (CheckInferredResultType) { 10773 SrcType = SrcType.getUnqualifiedType(); 10774 DstType = DstType.getUnqualifiedType(); 10775 } 10776 MayHaveConvFixit = true; 10777 break; 10778 case IncompatiblePointerSign: 10779 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10780 break; 10781 case FunctionVoidPointer: 10782 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10783 break; 10784 case IncompatiblePointerDiscardsQualifiers: { 10785 // Perform array-to-pointer decay if necessary. 10786 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10787 10788 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10789 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10790 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10791 DiagKind = diag::err_typecheck_incompatible_address_space; 10792 break; 10793 10794 10795 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10796 DiagKind = diag::err_typecheck_incompatible_ownership; 10797 break; 10798 } 10799 10800 llvm_unreachable("unknown error case for discarding qualifiers!"); 10801 // fallthrough 10802 } 10803 case CompatiblePointerDiscardsQualifiers: 10804 // If the qualifiers lost were because we were applying the 10805 // (deprecated) C++ conversion from a string literal to a char* 10806 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10807 // Ideally, this check would be performed in 10808 // checkPointerTypesForAssignment. However, that would require a 10809 // bit of refactoring (so that the second argument is an 10810 // expression, rather than a type), which should be done as part 10811 // of a larger effort to fix checkPointerTypesForAssignment for 10812 // C++ semantics. 10813 if (getLangOpts().CPlusPlus && 10814 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10815 return false; 10816 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10817 break; 10818 case IncompatibleNestedPointerQualifiers: 10819 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10820 break; 10821 case IntToBlockPointer: 10822 DiagKind = diag::err_int_to_block_pointer; 10823 break; 10824 case IncompatibleBlockPointer: 10825 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10826 break; 10827 case IncompatibleObjCQualifiedId: 10828 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10829 // it can give a more specific diagnostic. 10830 DiagKind = diag::warn_incompatible_qualified_id; 10831 break; 10832 case IncompatibleVectors: 10833 DiagKind = diag::warn_incompatible_vectors; 10834 break; 10835 case IncompatibleObjCWeakRef: 10836 DiagKind = diag::err_arc_weak_unavailable_assign; 10837 break; 10838 case Incompatible: 10839 DiagKind = diag::err_typecheck_convert_incompatible; 10840 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10841 MayHaveConvFixit = true; 10842 isInvalid = true; 10843 MayHaveFunctionDiff = true; 10844 break; 10845 } 10846 10847 QualType FirstType, SecondType; 10848 switch (Action) { 10849 case AA_Assigning: 10850 case AA_Initializing: 10851 // The destination type comes first. 10852 FirstType = DstType; 10853 SecondType = SrcType; 10854 break; 10855 10856 case AA_Returning: 10857 case AA_Passing: 10858 case AA_Passing_CFAudited: 10859 case AA_Converting: 10860 case AA_Sending: 10861 case AA_Casting: 10862 // The source type comes first. 10863 FirstType = SrcType; 10864 SecondType = DstType; 10865 break; 10866 } 10867 10868 PartialDiagnostic FDiag = PDiag(DiagKind); 10869 if (Action == AA_Passing_CFAudited) 10870 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 10871 else 10872 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10873 10874 // If we can fix the conversion, suggest the FixIts. 10875 assert(ConvHints.isNull() || Hint.isNull()); 10876 if (!ConvHints.isNull()) { 10877 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10878 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10879 FDiag << *HI; 10880 } else { 10881 FDiag << Hint; 10882 } 10883 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10884 10885 if (MayHaveFunctionDiff) 10886 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10887 10888 Diag(Loc, FDiag); 10889 10890 if (SecondType == Context.OverloadTy) 10891 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10892 FirstType); 10893 10894 if (CheckInferredResultType) 10895 EmitRelatedResultTypeNote(SrcExpr); 10896 10897 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10898 EmitRelatedResultTypeNoteForReturn(DstType); 10899 10900 if (Complained) 10901 *Complained = true; 10902 return isInvalid; 10903 } 10904 10905 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10906 llvm::APSInt *Result) { 10907 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10908 public: 10909 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 10910 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10911 } 10912 } Diagnoser; 10913 10914 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10915 } 10916 10917 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10918 llvm::APSInt *Result, 10919 unsigned DiagID, 10920 bool AllowFold) { 10921 class IDDiagnoser : public VerifyICEDiagnoser { 10922 unsigned DiagID; 10923 10924 public: 10925 IDDiagnoser(unsigned DiagID) 10926 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10927 10928 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 10929 S.Diag(Loc, DiagID) << SR; 10930 } 10931 } Diagnoser(DiagID); 10932 10933 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10934 } 10935 10936 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10937 SourceRange SR) { 10938 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10939 } 10940 10941 ExprResult 10942 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10943 VerifyICEDiagnoser &Diagnoser, 10944 bool AllowFold) { 10945 SourceLocation DiagLoc = E->getLocStart(); 10946 10947 if (getLangOpts().CPlusPlus11) { 10948 // C++11 [expr.const]p5: 10949 // If an expression of literal class type is used in a context where an 10950 // integral constant expression is required, then that class type shall 10951 // have a single non-explicit conversion function to an integral or 10952 // unscoped enumeration type 10953 ExprResult Converted; 10954 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10955 public: 10956 CXX11ConvertDiagnoser(bool Silent) 10957 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10958 Silent, true) {} 10959 10960 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10961 QualType T) override { 10962 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10963 } 10964 10965 SemaDiagnosticBuilder diagnoseIncomplete( 10966 Sema &S, SourceLocation Loc, QualType T) override { 10967 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10968 } 10969 10970 SemaDiagnosticBuilder diagnoseExplicitConv( 10971 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 10972 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10973 } 10974 10975 SemaDiagnosticBuilder noteExplicitConv( 10976 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 10977 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10978 << ConvTy->isEnumeralType() << ConvTy; 10979 } 10980 10981 SemaDiagnosticBuilder diagnoseAmbiguous( 10982 Sema &S, SourceLocation Loc, QualType T) override { 10983 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10984 } 10985 10986 SemaDiagnosticBuilder noteAmbiguous( 10987 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 10988 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10989 << ConvTy->isEnumeralType() << ConvTy; 10990 } 10991 10992 SemaDiagnosticBuilder diagnoseConversion( 10993 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 10994 llvm_unreachable("conversion functions are permitted"); 10995 } 10996 } ConvertDiagnoser(Diagnoser.Suppress); 10997 10998 Converted = PerformContextualImplicitConversion(DiagLoc, E, 10999 ConvertDiagnoser); 11000 if (Converted.isInvalid()) 11001 return Converted; 11002 E = Converted.take(); 11003 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 11004 return ExprError(); 11005 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11006 // An ICE must be of integral or unscoped enumeration type. 11007 if (!Diagnoser.Suppress) 11008 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11009 return ExprError(); 11010 } 11011 11012 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 11013 // in the non-ICE case. 11014 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 11015 if (Result) 11016 *Result = E->EvaluateKnownConstInt(Context); 11017 return Owned(E); 11018 } 11019 11020 Expr::EvalResult EvalResult; 11021 SmallVector<PartialDiagnosticAt, 8> Notes; 11022 EvalResult.Diag = &Notes; 11023 11024 // Try to evaluate the expression, and produce diagnostics explaining why it's 11025 // not a constant expression as a side-effect. 11026 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 11027 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 11028 11029 // In C++11, we can rely on diagnostics being produced for any expression 11030 // which is not a constant expression. If no diagnostics were produced, then 11031 // this is a constant expression. 11032 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 11033 if (Result) 11034 *Result = EvalResult.Val.getInt(); 11035 return Owned(E); 11036 } 11037 11038 // If our only note is the usual "invalid subexpression" note, just point 11039 // the caret at its location rather than producing an essentially 11040 // redundant note. 11041 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11042 diag::note_invalid_subexpr_in_const_expr) { 11043 DiagLoc = Notes[0].first; 11044 Notes.clear(); 11045 } 11046 11047 if (!Folded || !AllowFold) { 11048 if (!Diagnoser.Suppress) { 11049 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11050 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11051 Diag(Notes[I].first, Notes[I].second); 11052 } 11053 11054 return ExprError(); 11055 } 11056 11057 Diagnoser.diagnoseFold(*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 if (Result) 11062 *Result = EvalResult.Val.getInt(); 11063 return Owned(E); 11064 } 11065 11066 namespace { 11067 // Handle the case where we conclude a expression which we speculatively 11068 // considered to be unevaluated is actually evaluated. 11069 class TransformToPE : public TreeTransform<TransformToPE> { 11070 typedef TreeTransform<TransformToPE> BaseTransform; 11071 11072 public: 11073 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 11074 11075 // Make sure we redo semantic analysis 11076 bool AlwaysRebuild() { return true; } 11077 11078 // Make sure we handle LabelStmts correctly. 11079 // FIXME: This does the right thing, but maybe we need a more general 11080 // fix to TreeTransform? 11081 StmtResult TransformLabelStmt(LabelStmt *S) { 11082 S->getDecl()->setStmt(0); 11083 return BaseTransform::TransformLabelStmt(S); 11084 } 11085 11086 // We need to special-case DeclRefExprs referring to FieldDecls which 11087 // are not part of a member pointer formation; normal TreeTransforming 11088 // doesn't catch this case because of the way we represent them in the AST. 11089 // FIXME: This is a bit ugly; is it really the best way to handle this 11090 // case? 11091 // 11092 // Error on DeclRefExprs referring to FieldDecls. 11093 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 11094 if (isa<FieldDecl>(E->getDecl()) && 11095 !SemaRef.isUnevaluatedContext()) 11096 return SemaRef.Diag(E->getLocation(), 11097 diag::err_invalid_non_static_member_use) 11098 << E->getDecl() << E->getSourceRange(); 11099 11100 return BaseTransform::TransformDeclRefExpr(E); 11101 } 11102 11103 // Exception: filter out member pointer formation 11104 ExprResult TransformUnaryOperator(UnaryOperator *E) { 11105 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 11106 return E; 11107 11108 return BaseTransform::TransformUnaryOperator(E); 11109 } 11110 11111 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11112 // Lambdas never need to be transformed. 11113 return E; 11114 } 11115 }; 11116 } 11117 11118 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 11119 assert(isUnevaluatedContext() && 11120 "Should only transform unevaluated expressions"); 11121 ExprEvalContexts.back().Context = 11122 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 11123 if (isUnevaluatedContext()) 11124 return E; 11125 return TransformToPE(*this).TransformExpr(E); 11126 } 11127 11128 void 11129 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11130 Decl *LambdaContextDecl, 11131 bool IsDecltype) { 11132 ExprEvalContexts.push_back( 11133 ExpressionEvaluationContextRecord(NewContext, 11134 ExprCleanupObjects.size(), 11135 ExprNeedsCleanups, 11136 LambdaContextDecl, 11137 IsDecltype)); 11138 ExprNeedsCleanups = false; 11139 if (!MaybeODRUseExprs.empty()) 11140 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11141 } 11142 11143 void 11144 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11145 ReuseLambdaContextDecl_t, 11146 bool IsDecltype) { 11147 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11148 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11149 } 11150 11151 void Sema::PopExpressionEvaluationContext() { 11152 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11153 11154 if (!Rec.Lambdas.empty()) { 11155 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11156 unsigned D; 11157 if (Rec.isUnevaluated()) { 11158 // C++11 [expr.prim.lambda]p2: 11159 // A lambda-expression shall not appear in an unevaluated operand 11160 // (Clause 5). 11161 D = diag::err_lambda_unevaluated_operand; 11162 } else { 11163 // C++1y [expr.const]p2: 11164 // A conditional-expression e is a core constant expression unless the 11165 // evaluation of e, following the rules of the abstract machine, would 11166 // evaluate [...] a lambda-expression. 11167 D = diag::err_lambda_in_constant_expression; 11168 } 11169 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 11170 Diag(Rec.Lambdas[I]->getLocStart(), D); 11171 } else { 11172 // Mark the capture expressions odr-used. This was deferred 11173 // during lambda expression creation. 11174 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 11175 LambdaExpr *Lambda = Rec.Lambdas[I]; 11176 for (LambdaExpr::capture_init_iterator 11177 C = Lambda->capture_init_begin(), 11178 CEnd = Lambda->capture_init_end(); 11179 C != CEnd; ++C) { 11180 MarkDeclarationsReferencedInExpr(*C); 11181 } 11182 } 11183 } 11184 } 11185 11186 // When are coming out of an unevaluated context, clear out any 11187 // temporaries that we may have created as part of the evaluation of 11188 // the expression in that context: they aren't relevant because they 11189 // will never be constructed. 11190 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11191 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 11192 ExprCleanupObjects.end()); 11193 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 11194 CleanupVarDeclMarking(); 11195 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 11196 // Otherwise, merge the contexts together. 11197 } else { 11198 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 11199 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 11200 Rec.SavedMaybeODRUseExprs.end()); 11201 } 11202 11203 // Pop the current expression evaluation context off the stack. 11204 ExprEvalContexts.pop_back(); 11205 } 11206 11207 void Sema::DiscardCleanupsInEvaluationContext() { 11208 ExprCleanupObjects.erase( 11209 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 11210 ExprCleanupObjects.end()); 11211 ExprNeedsCleanups = false; 11212 MaybeODRUseExprs.clear(); 11213 } 11214 11215 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 11216 if (!E->getType()->isVariablyModifiedType()) 11217 return E; 11218 return TransformToPotentiallyEvaluated(E); 11219 } 11220 11221 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11222 // Do not mark anything as "used" within a dependent context; wait for 11223 // an instantiation. 11224 if (SemaRef.CurContext->isDependentContext()) 11225 return false; 11226 11227 switch (SemaRef.ExprEvalContexts.back().Context) { 11228 case Sema::Unevaluated: 11229 case Sema::UnevaluatedAbstract: 11230 // We are in an expression that is not potentially evaluated; do nothing. 11231 // (Depending on how you read the standard, we actually do need to do 11232 // something here for null pointer constants, but the standard's 11233 // definition of a null pointer constant is completely crazy.) 11234 return false; 11235 11236 case Sema::ConstantEvaluated: 11237 case Sema::PotentiallyEvaluated: 11238 // We are in a potentially evaluated expression (or a constant-expression 11239 // in C++03); we need to do implicit template instantiation, implicitly 11240 // define class members, and mark most declarations as used. 11241 return true; 11242 11243 case Sema::PotentiallyEvaluatedIfUsed: 11244 // Referenced declarations will only be used if the construct in the 11245 // containing expression is used. 11246 return false; 11247 } 11248 llvm_unreachable("Invalid context"); 11249 } 11250 11251 /// \brief Mark a function referenced, and check whether it is odr-used 11252 /// (C++ [basic.def.odr]p2, C99 6.9p3) 11253 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 11254 assert(Func && "No function?"); 11255 11256 Func->setReferenced(); 11257 11258 // C++11 [basic.def.odr]p3: 11259 // A function whose name appears as a potentially-evaluated expression is 11260 // odr-used if it is the unique lookup result or the selected member of a 11261 // set of overloaded functions [...]. 11262 // 11263 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11264 // can just check that here. Skip the rest of this function if we've already 11265 // marked the function as used. 11266 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11267 // C++11 [temp.inst]p3: 11268 // Unless a function template specialization has been explicitly 11269 // instantiated or explicitly specialized, the function template 11270 // specialization is implicitly instantiated when the specialization is 11271 // referenced in a context that requires a function definition to exist. 11272 // 11273 // We consider constexpr function templates to be referenced in a context 11274 // that requires a definition to exist whenever they are referenced. 11275 // 11276 // FIXME: This instantiates constexpr functions too frequently. If this is 11277 // really an unevaluated context (and we're not just in the definition of a 11278 // function template or overload resolution or other cases which we 11279 // incorrectly consider to be unevaluated contexts), and we're not in a 11280 // subexpression which we actually need to evaluate (for instance, a 11281 // template argument, array bound or an expression in a braced-init-list), 11282 // we are not permitted to instantiate this constexpr function definition. 11283 // 11284 // FIXME: This also implicitly defines special members too frequently. They 11285 // are only supposed to be implicitly defined if they are odr-used, but they 11286 // are not odr-used from constant expressions in unevaluated contexts. 11287 // However, they cannot be referenced if they are deleted, and they are 11288 // deleted whenever the implicit definition of the special member would 11289 // fail. 11290 if (!Func->isConstexpr() || Func->getBody()) 11291 return; 11292 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11293 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11294 return; 11295 } 11296 11297 // Note that this declaration has been used. 11298 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11299 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 11300 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11301 if (Constructor->isDefaultConstructor()) { 11302 if (Constructor->isTrivial()) 11303 return; 11304 DefineImplicitDefaultConstructor(Loc, Constructor); 11305 } else if (Constructor->isCopyConstructor()) { 11306 DefineImplicitCopyConstructor(Loc, Constructor); 11307 } else if (Constructor->isMoveConstructor()) { 11308 DefineImplicitMoveConstructor(Loc, Constructor); 11309 } 11310 } else if (Constructor->getInheritedConstructor()) { 11311 DefineInheritingConstructor(Loc, Constructor); 11312 } 11313 11314 MarkVTableUsed(Loc, Constructor->getParent()); 11315 } else if (CXXDestructorDecl *Destructor = 11316 dyn_cast<CXXDestructorDecl>(Func)) { 11317 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 11318 if (Destructor->isDefaulted() && !Destructor->isDeleted()) 11319 DefineImplicitDestructor(Loc, Destructor); 11320 if (Destructor->isVirtual()) 11321 MarkVTableUsed(Loc, Destructor->getParent()); 11322 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11323 if (MethodDecl->isOverloadedOperator() && 11324 MethodDecl->getOverloadedOperator() == OO_Equal) { 11325 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 11326 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 11327 if (MethodDecl->isCopyAssignmentOperator()) 11328 DefineImplicitCopyAssignment(Loc, MethodDecl); 11329 else 11330 DefineImplicitMoveAssignment(Loc, MethodDecl); 11331 } 11332 } else if (isa<CXXConversionDecl>(MethodDecl) && 11333 MethodDecl->getParent()->isLambda()) { 11334 CXXConversionDecl *Conversion = 11335 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 11336 if (Conversion->isLambdaToBlockPointerConversion()) 11337 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11338 else 11339 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11340 } else if (MethodDecl->isVirtual()) 11341 MarkVTableUsed(Loc, MethodDecl->getParent()); 11342 } 11343 11344 // Recursive functions should be marked when used from another function. 11345 // FIXME: Is this really right? 11346 if (CurContext == Func) return; 11347 11348 // Resolve the exception specification for any function which is 11349 // used: CodeGen will need it. 11350 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11351 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11352 ResolveExceptionSpec(Loc, FPT); 11353 11354 // Implicit instantiation of function templates and member functions of 11355 // class templates. 11356 if (Func->isImplicitlyInstantiable()) { 11357 bool AlreadyInstantiated = false; 11358 SourceLocation PointOfInstantiation = Loc; 11359 if (FunctionTemplateSpecializationInfo *SpecInfo 11360 = Func->getTemplateSpecializationInfo()) { 11361 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11362 SpecInfo->setPointOfInstantiation(Loc); 11363 else if (SpecInfo->getTemplateSpecializationKind() 11364 == TSK_ImplicitInstantiation) { 11365 AlreadyInstantiated = true; 11366 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11367 } 11368 } else if (MemberSpecializationInfo *MSInfo 11369 = Func->getMemberSpecializationInfo()) { 11370 if (MSInfo->getPointOfInstantiation().isInvalid()) 11371 MSInfo->setPointOfInstantiation(Loc); 11372 else if (MSInfo->getTemplateSpecializationKind() 11373 == TSK_ImplicitInstantiation) { 11374 AlreadyInstantiated = true; 11375 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11376 } 11377 } 11378 11379 if (!AlreadyInstantiated || Func->isConstexpr()) { 11380 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11381 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11382 ActiveTemplateInstantiations.size()) 11383 PendingLocalImplicitInstantiations.push_back( 11384 std::make_pair(Func, PointOfInstantiation)); 11385 else if (Func->isConstexpr()) 11386 // Do not defer instantiations of constexpr functions, to avoid the 11387 // expression evaluator needing to call back into Sema if it sees a 11388 // call to such a function. 11389 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11390 else { 11391 PendingInstantiations.push_back(std::make_pair(Func, 11392 PointOfInstantiation)); 11393 // Notify the consumer that a function was implicitly instantiated. 11394 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11395 } 11396 } 11397 } else { 11398 // Walk redefinitions, as some of them may be instantiable. 11399 for (auto i : Func->redecls()) { 11400 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11401 MarkFunctionReferenced(Loc, i); 11402 } 11403 } 11404 11405 // Keep track of used but undefined functions. 11406 if (!Func->isDefined()) { 11407 if (mightHaveNonExternalLinkage(Func)) 11408 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11409 else if (Func->getMostRecentDecl()->isInlined() && 11410 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11411 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11412 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11413 } 11414 11415 // Normally the most current decl is marked used while processing the use and 11416 // any subsequent decls are marked used by decl merging. This fails with 11417 // template instantiation since marking can happen at the end of the file 11418 // and, because of the two phase lookup, this function is called with at 11419 // decl in the middle of a decl chain. We loop to maintain the invariant 11420 // that once a decl is used, all decls after it are also used. 11421 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11422 F->markUsed(Context); 11423 if (F == Func) 11424 break; 11425 } 11426 } 11427 11428 static void 11429 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11430 VarDecl *var, DeclContext *DC) { 11431 DeclContext *VarDC = var->getDeclContext(); 11432 11433 // If the parameter still belongs to the translation unit, then 11434 // we're actually just using one parameter in the declaration of 11435 // the next. 11436 if (isa<ParmVarDecl>(var) && 11437 isa<TranslationUnitDecl>(VarDC)) 11438 return; 11439 11440 // For C code, don't diagnose about capture if we're not actually in code 11441 // right now; it's impossible to write a non-constant expression outside of 11442 // function context, so we'll get other (more useful) diagnostics later. 11443 // 11444 // For C++, things get a bit more nasty... it would be nice to suppress this 11445 // diagnostic for certain cases like using a local variable in an array bound 11446 // for a member of a local class, but the correct predicate is not obvious. 11447 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11448 return; 11449 11450 if (isa<CXXMethodDecl>(VarDC) && 11451 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11452 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11453 << var->getIdentifier(); 11454 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11455 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11456 << var->getIdentifier() << fn->getDeclName(); 11457 } else if (isa<BlockDecl>(VarDC)) { 11458 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11459 << var->getIdentifier(); 11460 } else { 11461 // FIXME: Is there any other context where a local variable can be 11462 // declared? 11463 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11464 << var->getIdentifier(); 11465 } 11466 11467 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 11468 << var->getIdentifier(); 11469 11470 // FIXME: Add additional diagnostic info about class etc. which prevents 11471 // capture. 11472 } 11473 11474 11475 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11476 bool &SubCapturesAreNested, 11477 QualType &CaptureType, 11478 QualType &DeclRefType) { 11479 // Check whether we've already captured it. 11480 if (CSI->CaptureMap.count(Var)) { 11481 // If we found a capture, any subcaptures are nested. 11482 SubCapturesAreNested = true; 11483 11484 // Retrieve the capture type for this variable. 11485 CaptureType = CSI->getCapture(Var).getCaptureType(); 11486 11487 // Compute the type of an expression that refers to this variable. 11488 DeclRefType = CaptureType.getNonReferenceType(); 11489 11490 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11491 if (Cap.isCopyCapture() && 11492 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11493 DeclRefType.addConst(); 11494 return true; 11495 } 11496 return false; 11497 } 11498 11499 // Only block literals, captured statements, and lambda expressions can 11500 // capture; other scopes don't work. 11501 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11502 SourceLocation Loc, 11503 const bool Diagnose, Sema &S) { 11504 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 11505 return getLambdaAwareParentOfDeclContext(DC); 11506 else { 11507 if (Diagnose) 11508 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11509 } 11510 return 0; 11511 } 11512 11513 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11514 // certain types of variables (unnamed, variably modified types etc.) 11515 // so check for eligibility. 11516 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11517 SourceLocation Loc, 11518 const bool Diagnose, Sema &S) { 11519 11520 bool IsBlock = isa<BlockScopeInfo>(CSI); 11521 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11522 11523 // Lambdas are not allowed to capture unnamed variables 11524 // (e.g. anonymous unions). 11525 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11526 // assuming that's the intent. 11527 if (IsLambda && !Var->getDeclName()) { 11528 if (Diagnose) { 11529 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11530 S.Diag(Var->getLocation(), diag::note_declared_at); 11531 } 11532 return false; 11533 } 11534 11535 // Prohibit variably-modified types; they're difficult to deal with. 11536 if (Var->getType()->isVariablyModifiedType()) { 11537 if (Diagnose) { 11538 if (IsBlock) 11539 S.Diag(Loc, diag::err_ref_vm_type); 11540 else 11541 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11542 S.Diag(Var->getLocation(), diag::note_previous_decl) 11543 << Var->getDeclName(); 11544 } 11545 return false; 11546 } 11547 // Prohibit structs with flexible array members too. 11548 // We cannot capture what is in the tail end of the struct. 11549 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11550 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11551 if (Diagnose) { 11552 if (IsBlock) 11553 S.Diag(Loc, diag::err_ref_flexarray_type); 11554 else 11555 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11556 << Var->getDeclName(); 11557 S.Diag(Var->getLocation(), diag::note_previous_decl) 11558 << Var->getDeclName(); 11559 } 11560 return false; 11561 } 11562 } 11563 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11564 // Lambdas and captured statements are not allowed to capture __block 11565 // variables; they don't support the expected semantics. 11566 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11567 if (Diagnose) { 11568 S.Diag(Loc, diag::err_capture_block_variable) 11569 << Var->getDeclName() << !IsLambda; 11570 S.Diag(Var->getLocation(), diag::note_previous_decl) 11571 << Var->getDeclName(); 11572 } 11573 return false; 11574 } 11575 11576 return true; 11577 } 11578 11579 // Returns true if the capture by block was successful. 11580 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11581 SourceLocation Loc, 11582 const bool BuildAndDiagnose, 11583 QualType &CaptureType, 11584 QualType &DeclRefType, 11585 const bool Nested, 11586 Sema &S) { 11587 Expr *CopyExpr = 0; 11588 bool ByRef = false; 11589 11590 // Blocks are not allowed to capture arrays. 11591 if (CaptureType->isArrayType()) { 11592 if (BuildAndDiagnose) { 11593 S.Diag(Loc, diag::err_ref_array_type); 11594 S.Diag(Var->getLocation(), diag::note_previous_decl) 11595 << Var->getDeclName(); 11596 } 11597 return false; 11598 } 11599 11600 // Forbid the block-capture of autoreleasing variables. 11601 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11602 if (BuildAndDiagnose) { 11603 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11604 << /*block*/ 0; 11605 S.Diag(Var->getLocation(), diag::note_previous_decl) 11606 << Var->getDeclName(); 11607 } 11608 return false; 11609 } 11610 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11611 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11612 // Block capture by reference does not change the capture or 11613 // declaration reference types. 11614 ByRef = true; 11615 } else { 11616 // Block capture by copy introduces 'const'. 11617 CaptureType = CaptureType.getNonReferenceType().withConst(); 11618 DeclRefType = CaptureType; 11619 11620 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11621 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11622 // The capture logic needs the destructor, so make sure we mark it. 11623 // Usually this is unnecessary because most local variables have 11624 // their destructors marked at declaration time, but parameters are 11625 // an exception because it's technically only the call site that 11626 // actually requires the destructor. 11627 if (isa<ParmVarDecl>(Var)) 11628 S.FinalizeVarWithDestructor(Var, Record); 11629 11630 // Enter a new evaluation context to insulate the copy 11631 // full-expression. 11632 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11633 11634 // According to the blocks spec, the capture of a variable from 11635 // the stack requires a const copy constructor. This is not true 11636 // of the copy/move done to move a __block variable to the heap. 11637 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11638 DeclRefType.withConst(), 11639 VK_LValue, Loc); 11640 11641 ExprResult Result 11642 = S.PerformCopyInitialization( 11643 InitializedEntity::InitializeBlock(Var->getLocation(), 11644 CaptureType, false), 11645 Loc, S.Owned(DeclRef)); 11646 11647 // Build a full-expression copy expression if initialization 11648 // succeeded and used a non-trivial constructor. Recover from 11649 // errors by pretending that the copy isn't necessary. 11650 if (!Result.isInvalid() && 11651 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11652 ->isTrivial()) { 11653 Result = S.MaybeCreateExprWithCleanups(Result); 11654 CopyExpr = Result.take(); 11655 } 11656 } 11657 } 11658 } 11659 11660 // Actually capture the variable. 11661 if (BuildAndDiagnose) 11662 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11663 SourceLocation(), CaptureType, CopyExpr); 11664 11665 return true; 11666 11667 } 11668 11669 11670 /// \brief Capture the given variable in the captured region. 11671 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11672 VarDecl *Var, 11673 SourceLocation Loc, 11674 const bool BuildAndDiagnose, 11675 QualType &CaptureType, 11676 QualType &DeclRefType, 11677 const bool RefersToEnclosingLocal, 11678 Sema &S) { 11679 11680 // By default, capture variables by reference. 11681 bool ByRef = true; 11682 // Using an LValue reference type is consistent with Lambdas (see below). 11683 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11684 Expr *CopyExpr = 0; 11685 if (BuildAndDiagnose) { 11686 // The current implementation assumes that all variables are captured 11687 // by references. Since there is no capture by copy, no expression evaluation 11688 // will be needed. 11689 // 11690 RecordDecl *RD = RSI->TheRecordDecl; 11691 11692 FieldDecl *Field 11693 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType, 11694 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11695 0, false, ICIS_NoInit); 11696 Field->setImplicit(true); 11697 Field->setAccess(AS_private); 11698 RD->addDecl(Field); 11699 11700 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11701 DeclRefType, VK_LValue, Loc); 11702 Var->setReferenced(true); 11703 Var->markUsed(S.Context); 11704 } 11705 11706 // Actually capture the variable. 11707 if (BuildAndDiagnose) 11708 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11709 SourceLocation(), CaptureType, CopyExpr); 11710 11711 11712 return true; 11713 } 11714 11715 /// \brief Create a field within the lambda class for the variable 11716 /// being captured. Handle Array captures. 11717 static ExprResult addAsFieldToClosureType(Sema &S, 11718 LambdaScopeInfo *LSI, 11719 VarDecl *Var, QualType FieldType, 11720 QualType DeclRefType, 11721 SourceLocation Loc, 11722 bool RefersToEnclosingLocal) { 11723 CXXRecordDecl *Lambda = LSI->Lambda; 11724 11725 // Build the non-static data member. 11726 FieldDecl *Field 11727 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11728 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11729 0, false, ICIS_NoInit); 11730 Field->setImplicit(true); 11731 Field->setAccess(AS_private); 11732 Lambda->addDecl(Field); 11733 11734 // C++11 [expr.prim.lambda]p21: 11735 // When the lambda-expression is evaluated, the entities that 11736 // are captured by copy are used to direct-initialize each 11737 // corresponding non-static data member of the resulting closure 11738 // object. (For array members, the array elements are 11739 // direct-initialized in increasing subscript order.) These 11740 // initializations are performed in the (unspecified) order in 11741 // which the non-static data members are declared. 11742 11743 // Introduce a new evaluation context for the initialization, so 11744 // that temporaries introduced as part of the capture are retained 11745 // to be re-"exported" from the lambda expression itself. 11746 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11747 11748 // C++ [expr.prim.labda]p12: 11749 // An entity captured by a lambda-expression is odr-used (3.2) in 11750 // the scope containing the lambda-expression. 11751 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11752 DeclRefType, VK_LValue, Loc); 11753 Var->setReferenced(true); 11754 Var->markUsed(S.Context); 11755 11756 // When the field has array type, create index variables for each 11757 // dimension of the array. We use these index variables to subscript 11758 // the source array, and other clients (e.g., CodeGen) will perform 11759 // the necessary iteration with these index variables. 11760 SmallVector<VarDecl *, 4> IndexVariables; 11761 QualType BaseType = FieldType; 11762 QualType SizeType = S.Context.getSizeType(); 11763 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11764 while (const ConstantArrayType *Array 11765 = S.Context.getAsConstantArrayType(BaseType)) { 11766 // Create the iteration variable for this array index. 11767 IdentifierInfo *IterationVarName = 0; 11768 { 11769 SmallString<8> Str; 11770 llvm::raw_svector_ostream OS(Str); 11771 OS << "__i" << IndexVariables.size(); 11772 IterationVarName = &S.Context.Idents.get(OS.str()); 11773 } 11774 VarDecl *IterationVar 11775 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11776 IterationVarName, SizeType, 11777 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11778 SC_None); 11779 IndexVariables.push_back(IterationVar); 11780 LSI->ArrayIndexVars.push_back(IterationVar); 11781 11782 // Create a reference to the iteration variable. 11783 ExprResult IterationVarRef 11784 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11785 assert(!IterationVarRef.isInvalid() && 11786 "Reference to invented variable cannot fail!"); 11787 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11788 assert(!IterationVarRef.isInvalid() && 11789 "Conversion of invented variable cannot fail!"); 11790 11791 // Subscript the array with this iteration variable. 11792 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11793 Ref, Loc, IterationVarRef.take(), Loc); 11794 if (Subscript.isInvalid()) { 11795 S.CleanupVarDeclMarking(); 11796 S.DiscardCleanupsInEvaluationContext(); 11797 return ExprError(); 11798 } 11799 11800 Ref = Subscript.take(); 11801 BaseType = Array->getElementType(); 11802 } 11803 11804 // Construct the entity that we will be initializing. For an array, this 11805 // will be first element in the array, which may require several levels 11806 // of array-subscript entities. 11807 SmallVector<InitializedEntity, 4> Entities; 11808 Entities.reserve(1 + IndexVariables.size()); 11809 Entities.push_back( 11810 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(), 11811 Field->getType(), Loc)); 11812 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11813 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11814 0, 11815 Entities.back())); 11816 11817 InitializationKind InitKind 11818 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11819 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11820 ExprResult Result(true); 11821 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11822 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11823 11824 // If this initialization requires any cleanups (e.g., due to a 11825 // default argument to a copy constructor), note that for the 11826 // lambda. 11827 if (S.ExprNeedsCleanups) 11828 LSI->ExprNeedsCleanups = true; 11829 11830 // Exit the expression evaluation context used for the capture. 11831 S.CleanupVarDeclMarking(); 11832 S.DiscardCleanupsInEvaluationContext(); 11833 return Result; 11834 } 11835 11836 11837 11838 /// \brief Capture the given variable in the lambda. 11839 static bool captureInLambda(LambdaScopeInfo *LSI, 11840 VarDecl *Var, 11841 SourceLocation Loc, 11842 const bool BuildAndDiagnose, 11843 QualType &CaptureType, 11844 QualType &DeclRefType, 11845 const bool RefersToEnclosingLocal, 11846 const Sema::TryCaptureKind Kind, 11847 SourceLocation EllipsisLoc, 11848 const bool IsTopScope, 11849 Sema &S) { 11850 11851 // Determine whether we are capturing by reference or by value. 11852 bool ByRef = false; 11853 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11854 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11855 } else { 11856 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11857 } 11858 11859 // Compute the type of the field that will capture this variable. 11860 if (ByRef) { 11861 // C++11 [expr.prim.lambda]p15: 11862 // An entity is captured by reference if it is implicitly or 11863 // explicitly captured but not captured by copy. It is 11864 // unspecified whether additional unnamed non-static data 11865 // members are declared in the closure type for entities 11866 // captured by reference. 11867 // 11868 // FIXME: It is not clear whether we want to build an lvalue reference 11869 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11870 // to do the former, while EDG does the latter. Core issue 1249 will 11871 // clarify, but for now we follow GCC because it's a more permissive and 11872 // easily defensible position. 11873 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11874 } else { 11875 // C++11 [expr.prim.lambda]p14: 11876 // For each entity captured by copy, an unnamed non-static 11877 // data member is declared in the closure type. The 11878 // declaration order of these members is unspecified. The type 11879 // of such a data member is the type of the corresponding 11880 // captured entity if the entity is not a reference to an 11881 // object, or the referenced type otherwise. [Note: If the 11882 // captured entity is a reference to a function, the 11883 // corresponding data member is also a reference to a 11884 // function. - end note ] 11885 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11886 if (!RefType->getPointeeType()->isFunctionType()) 11887 CaptureType = RefType->getPointeeType(); 11888 } 11889 11890 // Forbid the lambda copy-capture of autoreleasing variables. 11891 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11892 if (BuildAndDiagnose) { 11893 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11894 S.Diag(Var->getLocation(), diag::note_previous_decl) 11895 << Var->getDeclName(); 11896 } 11897 return false; 11898 } 11899 11900 // Make sure that by-copy captures are of a complete and non-abstract type. 11901 if (BuildAndDiagnose) { 11902 if (!CaptureType->isDependentType() && 11903 S.RequireCompleteType(Loc, CaptureType, 11904 diag::err_capture_of_incomplete_type, 11905 Var->getDeclName())) 11906 return false; 11907 11908 if (S.RequireNonAbstractType(Loc, CaptureType, 11909 diag::err_capture_of_abstract_type)) 11910 return false; 11911 } 11912 } 11913 11914 // Capture this variable in the lambda. 11915 Expr *CopyExpr = 0; 11916 if (BuildAndDiagnose) { 11917 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 11918 CaptureType, DeclRefType, Loc, 11919 RefersToEnclosingLocal); 11920 if (!Result.isInvalid()) 11921 CopyExpr = Result.take(); 11922 } 11923 11924 // Compute the type of a reference to this captured variable. 11925 if (ByRef) 11926 DeclRefType = CaptureType.getNonReferenceType(); 11927 else { 11928 // C++ [expr.prim.lambda]p5: 11929 // The closure type for a lambda-expression has a public inline 11930 // function call operator [...]. This function call operator is 11931 // declared const (9.3.1) if and only if the lambda-expression’s 11932 // parameter-declaration-clause is not followed by mutable. 11933 DeclRefType = CaptureType.getNonReferenceType(); 11934 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11935 DeclRefType.addConst(); 11936 } 11937 11938 // Add the capture. 11939 if (BuildAndDiagnose) 11940 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 11941 Loc, EllipsisLoc, CaptureType, CopyExpr); 11942 11943 return true; 11944 } 11945 11946 11947 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 11948 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11949 bool BuildAndDiagnose, 11950 QualType &CaptureType, 11951 QualType &DeclRefType, 11952 const unsigned *const FunctionScopeIndexToStopAt) { 11953 bool Nested = false; 11954 11955 DeclContext *DC = CurContext; 11956 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 11957 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 11958 // We need to sync up the Declaration Context with the 11959 // FunctionScopeIndexToStopAt 11960 if (FunctionScopeIndexToStopAt) { 11961 unsigned FSIndex = FunctionScopes.size() - 1; 11962 while (FSIndex != MaxFunctionScopesIndex) { 11963 DC = getLambdaAwareParentOfDeclContext(DC); 11964 --FSIndex; 11965 } 11966 } 11967 11968 11969 // If the variable is declared in the current context (and is not an 11970 // init-capture), there is no need to capture it. 11971 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 11972 if (!Var->hasLocalStorage()) return true; 11973 11974 // Walk up the stack to determine whether we can capture the variable, 11975 // performing the "simple" checks that don't depend on type. We stop when 11976 // we've either hit the declared scope of the variable or find an existing 11977 // capture of that variable. We start from the innermost capturing-entity 11978 // (the DC) and ensure that all intervening capturing-entities 11979 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 11980 // declcontext can either capture the variable or have already captured 11981 // the variable. 11982 CaptureType = Var->getType(); 11983 DeclRefType = CaptureType.getNonReferenceType(); 11984 bool Explicit = (Kind != TryCapture_Implicit); 11985 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 11986 do { 11987 // Only block literals, captured statements, and lambda expressions can 11988 // capture; other scopes don't work. 11989 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 11990 ExprLoc, 11991 BuildAndDiagnose, 11992 *this); 11993 if (!ParentDC) return true; 11994 11995 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 11996 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 11997 11998 11999 // Check whether we've already captured it. 12000 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 12001 DeclRefType)) 12002 break; 12003 // If we are instantiating a generic lambda call operator body, 12004 // we do not want to capture new variables. What was captured 12005 // during either a lambdas transformation or initial parsing 12006 // should be used. 12007 if (isGenericLambdaCallOperatorSpecialization(DC)) { 12008 if (BuildAndDiagnose) { 12009 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12010 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 12011 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12012 Diag(Var->getLocation(), diag::note_previous_decl) 12013 << Var->getDeclName(); 12014 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 12015 } else 12016 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 12017 } 12018 return true; 12019 } 12020 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12021 // certain types of variables (unnamed, variably modified types etc.) 12022 // so check for eligibility. 12023 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 12024 return true; 12025 12026 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 12027 // No capture-default, and this is not an explicit capture 12028 // so cannot capture this variable. 12029 if (BuildAndDiagnose) { 12030 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12031 Diag(Var->getLocation(), diag::note_previous_decl) 12032 << Var->getDeclName(); 12033 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 12034 diag::note_lambda_decl); 12035 // FIXME: If we error out because an outer lambda can not implicitly 12036 // capture a variable that an inner lambda explicitly captures, we 12037 // should have the inner lambda do the explicit capture - because 12038 // it makes for cleaner diagnostics later. This would purely be done 12039 // so that the diagnostic does not misleadingly claim that a variable 12040 // can not be captured by a lambda implicitly even though it is captured 12041 // explicitly. Suggestion: 12042 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 12043 // at the function head 12044 // - cache the StartingDeclContext - this must be a lambda 12045 // - captureInLambda in the innermost lambda the variable. 12046 } 12047 return true; 12048 } 12049 12050 FunctionScopesIndex--; 12051 DC = ParentDC; 12052 Explicit = false; 12053 } while (!Var->getDeclContext()->Equals(DC)); 12054 12055 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 12056 // computing the type of the capture at each step, checking type-specific 12057 // requirements, and adding captures if requested. 12058 // If the variable had already been captured previously, we start capturing 12059 // at the lambda nested within that one. 12060 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 12061 ++I) { 12062 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 12063 12064 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 12065 if (!captureInBlock(BSI, Var, ExprLoc, 12066 BuildAndDiagnose, CaptureType, 12067 DeclRefType, Nested, *this)) 12068 return true; 12069 Nested = true; 12070 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 12071 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 12072 BuildAndDiagnose, CaptureType, 12073 DeclRefType, Nested, *this)) 12074 return true; 12075 Nested = true; 12076 } else { 12077 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12078 if (!captureInLambda(LSI, Var, ExprLoc, 12079 BuildAndDiagnose, CaptureType, 12080 DeclRefType, Nested, Kind, EllipsisLoc, 12081 /*IsTopScope*/I == N - 1, *this)) 12082 return true; 12083 Nested = true; 12084 } 12085 } 12086 return false; 12087 } 12088 12089 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 12090 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 12091 QualType CaptureType; 12092 QualType DeclRefType; 12093 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 12094 /*BuildAndDiagnose=*/true, CaptureType, 12095 DeclRefType, 0); 12096 } 12097 12098 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 12099 QualType CaptureType; 12100 QualType DeclRefType; 12101 12102 // Determine whether we can capture this variable. 12103 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 12104 /*BuildAndDiagnose=*/false, CaptureType, 12105 DeclRefType, 0)) 12106 return QualType(); 12107 12108 return DeclRefType; 12109 } 12110 12111 12112 12113 // If either the type of the variable or the initializer is dependent, 12114 // return false. Otherwise, determine whether the variable is a constant 12115 // expression. Use this if you need to know if a variable that might or 12116 // might not be dependent is truly a constant expression. 12117 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 12118 ASTContext &Context) { 12119 12120 if (Var->getType()->isDependentType()) 12121 return false; 12122 const VarDecl *DefVD = 0; 12123 Var->getAnyInitializer(DefVD); 12124 if (!DefVD) 12125 return false; 12126 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 12127 Expr *Init = cast<Expr>(Eval->Value); 12128 if (Init->isValueDependent()) 12129 return false; 12130 return IsVariableAConstantExpression(Var, Context); 12131 } 12132 12133 12134 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 12135 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 12136 // an object that satisfies the requirements for appearing in a 12137 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 12138 // is immediately applied." This function handles the lvalue-to-rvalue 12139 // conversion part. 12140 MaybeODRUseExprs.erase(E->IgnoreParens()); 12141 12142 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 12143 // to a variable that is a constant expression, and if so, identify it as 12144 // a reference to a variable that does not involve an odr-use of that 12145 // variable. 12146 if (LambdaScopeInfo *LSI = getCurLambda()) { 12147 Expr *SansParensExpr = E->IgnoreParens(); 12148 VarDecl *Var = 0; 12149 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 12150 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 12151 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 12152 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 12153 12154 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 12155 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 12156 } 12157 } 12158 12159 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 12160 if (!Res.isUsable()) 12161 return Res; 12162 12163 // If a constant-expression is a reference to a variable where we delay 12164 // deciding whether it is an odr-use, just assume we will apply the 12165 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 12166 // (a non-type template argument), we have special handling anyway. 12167 UpdateMarkingForLValueToRValue(Res.get()); 12168 return Res; 12169 } 12170 12171 void Sema::CleanupVarDeclMarking() { 12172 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 12173 e = MaybeODRUseExprs.end(); 12174 i != e; ++i) { 12175 VarDecl *Var; 12176 SourceLocation Loc; 12177 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 12178 Var = cast<VarDecl>(DRE->getDecl()); 12179 Loc = DRE->getLocation(); 12180 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 12181 Var = cast<VarDecl>(ME->getMemberDecl()); 12182 Loc = ME->getMemberLoc(); 12183 } else { 12184 llvm_unreachable("Unexpcted expression"); 12185 } 12186 12187 MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0); 12188 } 12189 12190 MaybeODRUseExprs.clear(); 12191 } 12192 12193 12194 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 12195 VarDecl *Var, Expr *E) { 12196 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 12197 "Invalid Expr argument to DoMarkVarDeclReferenced"); 12198 Var->setReferenced(); 12199 12200 // If the context is not potentially evaluated, this is not an odr-use and 12201 // does not trigger instantiation. 12202 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 12203 if (SemaRef.isUnevaluatedContext()) 12204 return; 12205 12206 // If we don't yet know whether this context is going to end up being an 12207 // evaluated context, and we're referencing a variable from an enclosing 12208 // scope, add a potential capture. 12209 // 12210 // FIXME: Is this necessary? These contexts are only used for default 12211 // arguments, where local variables can't be used. 12212 const bool RefersToEnclosingScope = 12213 (SemaRef.CurContext != Var->getDeclContext() && 12214 Var->getDeclContext()->isFunctionOrMethod() && 12215 Var->hasLocalStorage()); 12216 if (!RefersToEnclosingScope) 12217 return; 12218 12219 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 12220 // If a variable could potentially be odr-used, defer marking it so 12221 // until we finish analyzing the full expression for any lvalue-to-rvalue 12222 // or discarded value conversions that would obviate odr-use. 12223 // Add it to the list of potential captures that will be analyzed 12224 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 12225 // unless the variable is a reference that was initialized by a constant 12226 // expression (this will never need to be captured or odr-used). 12227 assert(E && "Capture variable should be used in an expression."); 12228 if (!Var->getType()->isReferenceType() || 12229 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 12230 LSI->addPotentialCapture(E->IgnoreParens()); 12231 } 12232 return; 12233 } 12234 12235 VarTemplateSpecializationDecl *VarSpec = 12236 dyn_cast<VarTemplateSpecializationDecl>(Var); 12237 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 12238 "Can't instantiate a partial template specialization."); 12239 12240 // Perform implicit instantiation of static data members, static data member 12241 // templates of class templates, and variable template specializations. Delay 12242 // instantiations of variable templates, except for those that could be used 12243 // in a constant expression. 12244 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 12245 if (isTemplateInstantiation(TSK)) { 12246 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 12247 12248 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 12249 if (Var->getPointOfInstantiation().isInvalid()) { 12250 // This is a modification of an existing AST node. Notify listeners. 12251 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 12252 L->StaticDataMemberInstantiated(Var); 12253 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 12254 // Don't bother trying to instantiate it again, unless we might need 12255 // its initializer before we get to the end of the TU. 12256 TryInstantiating = false; 12257 } 12258 12259 if (Var->getPointOfInstantiation().isInvalid()) 12260 Var->setTemplateSpecializationKind(TSK, Loc); 12261 12262 if (TryInstantiating) { 12263 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 12264 bool InstantiationDependent = false; 12265 bool IsNonDependent = 12266 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 12267 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 12268 : true; 12269 12270 // Do not instantiate specializations that are still type-dependent. 12271 if (IsNonDependent) { 12272 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 12273 // Do not defer instantiations of variables which could be used in a 12274 // constant expression. 12275 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 12276 } else { 12277 SemaRef.PendingInstantiations 12278 .push_back(std::make_pair(Var, PointOfInstantiation)); 12279 } 12280 } 12281 } 12282 } 12283 12284 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 12285 // the requirements for appearing in a constant expression (5.19) and, if 12286 // it is an object, the lvalue-to-rvalue conversion (4.1) 12287 // is immediately applied." We check the first part here, and 12288 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 12289 // Note that we use the C++11 definition everywhere because nothing in 12290 // C++03 depends on whether we get the C++03 version correct. The second 12291 // part does not apply to references, since they are not objects. 12292 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 12293 // A reference initialized by a constant expression can never be 12294 // odr-used, so simply ignore it. 12295 if (!Var->getType()->isReferenceType()) 12296 SemaRef.MaybeODRUseExprs.insert(E); 12297 } else 12298 MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0); 12299 } 12300 12301 /// \brief Mark a variable referenced, and check whether it is odr-used 12302 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 12303 /// used directly for normal expressions referring to VarDecl. 12304 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 12305 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 12306 } 12307 12308 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 12309 Decl *D, Expr *E, bool OdrUse) { 12310 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 12311 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 12312 return; 12313 } 12314 12315 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 12316 12317 // If this is a call to a method via a cast, also mark the method in the 12318 // derived class used in case codegen can devirtualize the call. 12319 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12320 if (!ME) 12321 return; 12322 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12323 if (!MD) 12324 return; 12325 const Expr *Base = ME->getBase(); 12326 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12327 if (!MostDerivedClassDecl) 12328 return; 12329 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12330 if (!DM || DM->isPure()) 12331 return; 12332 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12333 } 12334 12335 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12336 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12337 // TODO: update this with DR# once a defect report is filed. 12338 // C++11 defect. The address of a pure member should not be an ODR use, even 12339 // if it's a qualified reference. 12340 bool OdrUse = true; 12341 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12342 if (Method->isVirtual()) 12343 OdrUse = false; 12344 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12345 } 12346 12347 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12348 void Sema::MarkMemberReferenced(MemberExpr *E) { 12349 // C++11 [basic.def.odr]p2: 12350 // A non-overloaded function whose name appears as a potentially-evaluated 12351 // expression or a member of a set of candidate functions, if selected by 12352 // overload resolution when referred to from a potentially-evaluated 12353 // expression, is odr-used, unless it is a pure virtual function and its 12354 // name is not explicitly qualified. 12355 bool OdrUse = true; 12356 if (!E->hasQualifier()) { 12357 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12358 if (Method->isPure()) 12359 OdrUse = false; 12360 } 12361 SourceLocation Loc = E->getMemberLoc().isValid() ? 12362 E->getMemberLoc() : E->getLocStart(); 12363 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12364 } 12365 12366 /// \brief Perform marking for a reference to an arbitrary declaration. It 12367 /// marks the declaration referenced, and performs odr-use checking for functions 12368 /// and variables. This method should not be used when building an normal 12369 /// expression which refers to a variable. 12370 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12371 if (OdrUse) { 12372 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12373 MarkVariableReferenced(Loc, VD); 12374 return; 12375 } 12376 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12377 MarkFunctionReferenced(Loc, FD); 12378 return; 12379 } 12380 } 12381 D->setReferenced(); 12382 } 12383 12384 namespace { 12385 // Mark all of the declarations referenced 12386 // FIXME: Not fully implemented yet! We need to have a better understanding 12387 // of when we're entering 12388 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12389 Sema &S; 12390 SourceLocation Loc; 12391 12392 public: 12393 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12394 12395 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12396 12397 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12398 bool TraverseRecordType(RecordType *T); 12399 }; 12400 } 12401 12402 bool MarkReferencedDecls::TraverseTemplateArgument( 12403 const TemplateArgument &Arg) { 12404 if (Arg.getKind() == TemplateArgument::Declaration) { 12405 if (Decl *D = Arg.getAsDecl()) 12406 S.MarkAnyDeclReferenced(Loc, D, true); 12407 } 12408 12409 return Inherited::TraverseTemplateArgument(Arg); 12410 } 12411 12412 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12413 if (ClassTemplateSpecializationDecl *Spec 12414 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12415 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12416 return TraverseTemplateArguments(Args.data(), Args.size()); 12417 } 12418 12419 return true; 12420 } 12421 12422 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12423 MarkReferencedDecls Marker(*this, Loc); 12424 Marker.TraverseType(Context.getCanonicalType(T)); 12425 } 12426 12427 namespace { 12428 /// \brief Helper class that marks all of the declarations referenced by 12429 /// potentially-evaluated subexpressions as "referenced". 12430 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12431 Sema &S; 12432 bool SkipLocalVariables; 12433 12434 public: 12435 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12436 12437 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12438 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12439 12440 void VisitDeclRefExpr(DeclRefExpr *E) { 12441 // If we were asked not to visit local variables, don't. 12442 if (SkipLocalVariables) { 12443 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12444 if (VD->hasLocalStorage()) 12445 return; 12446 } 12447 12448 S.MarkDeclRefReferenced(E); 12449 } 12450 12451 void VisitMemberExpr(MemberExpr *E) { 12452 S.MarkMemberReferenced(E); 12453 Inherited::VisitMemberExpr(E); 12454 } 12455 12456 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12457 S.MarkFunctionReferenced(E->getLocStart(), 12458 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12459 Visit(E->getSubExpr()); 12460 } 12461 12462 void VisitCXXNewExpr(CXXNewExpr *E) { 12463 if (E->getOperatorNew()) 12464 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12465 if (E->getOperatorDelete()) 12466 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12467 Inherited::VisitCXXNewExpr(E); 12468 } 12469 12470 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12471 if (E->getOperatorDelete()) 12472 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12473 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12474 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12475 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12476 S.MarkFunctionReferenced(E->getLocStart(), 12477 S.LookupDestructor(Record)); 12478 } 12479 12480 Inherited::VisitCXXDeleteExpr(E); 12481 } 12482 12483 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12484 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12485 Inherited::VisitCXXConstructExpr(E); 12486 } 12487 12488 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12489 Visit(E->getExpr()); 12490 } 12491 12492 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12493 Inherited::VisitImplicitCastExpr(E); 12494 12495 if (E->getCastKind() == CK_LValueToRValue) 12496 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12497 } 12498 }; 12499 } 12500 12501 /// \brief Mark any declarations that appear within this expression or any 12502 /// potentially-evaluated subexpressions as "referenced". 12503 /// 12504 /// \param SkipLocalVariables If true, don't mark local variables as 12505 /// 'referenced'. 12506 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12507 bool SkipLocalVariables) { 12508 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12509 } 12510 12511 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 12512 /// of the program being compiled. 12513 /// 12514 /// This routine emits the given diagnostic when the code currently being 12515 /// type-checked is "potentially evaluated", meaning that there is a 12516 /// possibility that the code will actually be executable. Code in sizeof() 12517 /// expressions, code used only during overload resolution, etc., are not 12518 /// potentially evaluated. This routine will suppress such diagnostics or, 12519 /// in the absolutely nutty case of potentially potentially evaluated 12520 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 12521 /// later. 12522 /// 12523 /// This routine should be used for all diagnostics that describe the run-time 12524 /// behavior of a program, such as passing a non-POD value through an ellipsis. 12525 /// Failure to do so will likely result in spurious diagnostics or failures 12526 /// during overload resolution or within sizeof/alignof/typeof/typeid. 12527 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12528 const PartialDiagnostic &PD) { 12529 switch (ExprEvalContexts.back().Context) { 12530 case Unevaluated: 12531 case UnevaluatedAbstract: 12532 // The argument will never be evaluated, so don't complain. 12533 break; 12534 12535 case ConstantEvaluated: 12536 // Relevant diagnostics should be produced by constant evaluation. 12537 break; 12538 12539 case PotentiallyEvaluated: 12540 case PotentiallyEvaluatedIfUsed: 12541 if (Statement && getCurFunctionOrMethodDecl()) { 12542 FunctionScopes.back()->PossiblyUnreachableDiags. 12543 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12544 } 12545 else 12546 Diag(Loc, PD); 12547 12548 return true; 12549 } 12550 12551 return false; 12552 } 12553 12554 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12555 CallExpr *CE, FunctionDecl *FD) { 12556 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12557 return false; 12558 12559 // If we're inside a decltype's expression, don't check for a valid return 12560 // type or construct temporaries until we know whether this is the last call. 12561 if (ExprEvalContexts.back().IsDecltype) { 12562 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12563 return false; 12564 } 12565 12566 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12567 FunctionDecl *FD; 12568 CallExpr *CE; 12569 12570 public: 12571 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12572 : FD(FD), CE(CE) { } 12573 12574 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 12575 if (!FD) { 12576 S.Diag(Loc, diag::err_call_incomplete_return) 12577 << T << CE->getSourceRange(); 12578 return; 12579 } 12580 12581 S.Diag(Loc, diag::err_call_function_incomplete_return) 12582 << CE->getSourceRange() << FD->getDeclName() << T; 12583 S.Diag(FD->getLocation(), 12584 diag::note_function_with_incomplete_return_type_declared_here) 12585 << FD->getDeclName(); 12586 } 12587 } Diagnoser(FD, CE); 12588 12589 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12590 return true; 12591 12592 return false; 12593 } 12594 12595 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12596 // will prevent this condition from triggering, which is what we want. 12597 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12598 SourceLocation Loc; 12599 12600 unsigned diagnostic = diag::warn_condition_is_assignment; 12601 bool IsOrAssign = false; 12602 12603 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12604 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12605 return; 12606 12607 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12608 12609 // Greylist some idioms by putting them into a warning subcategory. 12610 if (ObjCMessageExpr *ME 12611 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12612 Selector Sel = ME->getSelector(); 12613 12614 // self = [<foo> init...] 12615 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12616 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12617 12618 // <foo> = [<bar> nextObject] 12619 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12620 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12621 } 12622 12623 Loc = Op->getOperatorLoc(); 12624 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12625 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12626 return; 12627 12628 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12629 Loc = Op->getOperatorLoc(); 12630 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12631 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12632 else { 12633 // Not an assignment. 12634 return; 12635 } 12636 12637 Diag(Loc, diagnostic) << E->getSourceRange(); 12638 12639 SourceLocation Open = E->getLocStart(); 12640 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12641 Diag(Loc, diag::note_condition_assign_silence) 12642 << FixItHint::CreateInsertion(Open, "(") 12643 << FixItHint::CreateInsertion(Close, ")"); 12644 12645 if (IsOrAssign) 12646 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12647 << FixItHint::CreateReplacement(Loc, "!="); 12648 else 12649 Diag(Loc, diag::note_condition_assign_to_comparison) 12650 << FixItHint::CreateReplacement(Loc, "=="); 12651 } 12652 12653 /// \brief Redundant parentheses over an equality comparison can indicate 12654 /// that the user intended an assignment used as condition. 12655 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12656 // Don't warn if the parens came from a macro. 12657 SourceLocation parenLoc = ParenE->getLocStart(); 12658 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12659 return; 12660 // Don't warn for dependent expressions. 12661 if (ParenE->isTypeDependent()) 12662 return; 12663 12664 Expr *E = ParenE->IgnoreParens(); 12665 12666 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12667 if (opE->getOpcode() == BO_EQ && 12668 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12669 == Expr::MLV_Valid) { 12670 SourceLocation Loc = opE->getOperatorLoc(); 12671 12672 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12673 SourceRange ParenERange = ParenE->getSourceRange(); 12674 Diag(Loc, diag::note_equality_comparison_silence) 12675 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12676 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12677 Diag(Loc, diag::note_equality_comparison_to_assign) 12678 << FixItHint::CreateReplacement(Loc, "="); 12679 } 12680 } 12681 12682 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12683 DiagnoseAssignmentAsCondition(E); 12684 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12685 DiagnoseEqualityWithExtraParens(parenE); 12686 12687 ExprResult result = CheckPlaceholderExpr(E); 12688 if (result.isInvalid()) return ExprError(); 12689 E = result.take(); 12690 12691 if (!E->isTypeDependent()) { 12692 if (getLangOpts().CPlusPlus) 12693 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12694 12695 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12696 if (ERes.isInvalid()) 12697 return ExprError(); 12698 E = ERes.take(); 12699 12700 QualType T = E->getType(); 12701 if (!T->isScalarType()) { // C99 6.8.4.1p1 12702 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12703 << T << E->getSourceRange(); 12704 return ExprError(); 12705 } 12706 } 12707 12708 return Owned(E); 12709 } 12710 12711 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12712 Expr *SubExpr) { 12713 if (!SubExpr) 12714 return ExprError(); 12715 12716 return CheckBooleanCondition(SubExpr, Loc); 12717 } 12718 12719 namespace { 12720 /// A visitor for rebuilding a call to an __unknown_any expression 12721 /// to have an appropriate type. 12722 struct RebuildUnknownAnyFunction 12723 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12724 12725 Sema &S; 12726 12727 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12728 12729 ExprResult VisitStmt(Stmt *S) { 12730 llvm_unreachable("unexpected statement!"); 12731 } 12732 12733 ExprResult VisitExpr(Expr *E) { 12734 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12735 << E->getSourceRange(); 12736 return ExprError(); 12737 } 12738 12739 /// Rebuild an expression which simply semantically wraps another 12740 /// expression which it shares the type and value kind of. 12741 template <class T> ExprResult rebuildSugarExpr(T *E) { 12742 ExprResult SubResult = Visit(E->getSubExpr()); 12743 if (SubResult.isInvalid()) return ExprError(); 12744 12745 Expr *SubExpr = SubResult.take(); 12746 E->setSubExpr(SubExpr); 12747 E->setType(SubExpr->getType()); 12748 E->setValueKind(SubExpr->getValueKind()); 12749 assert(E->getObjectKind() == OK_Ordinary); 12750 return E; 12751 } 12752 12753 ExprResult VisitParenExpr(ParenExpr *E) { 12754 return rebuildSugarExpr(E); 12755 } 12756 12757 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12758 return rebuildSugarExpr(E); 12759 } 12760 12761 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12762 ExprResult SubResult = Visit(E->getSubExpr()); 12763 if (SubResult.isInvalid()) return ExprError(); 12764 12765 Expr *SubExpr = SubResult.take(); 12766 E->setSubExpr(SubExpr); 12767 E->setType(S.Context.getPointerType(SubExpr->getType())); 12768 assert(E->getValueKind() == VK_RValue); 12769 assert(E->getObjectKind() == OK_Ordinary); 12770 return E; 12771 } 12772 12773 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12774 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12775 12776 E->setType(VD->getType()); 12777 12778 assert(E->getValueKind() == VK_RValue); 12779 if (S.getLangOpts().CPlusPlus && 12780 !(isa<CXXMethodDecl>(VD) && 12781 cast<CXXMethodDecl>(VD)->isInstance())) 12782 E->setValueKind(VK_LValue); 12783 12784 return E; 12785 } 12786 12787 ExprResult VisitMemberExpr(MemberExpr *E) { 12788 return resolveDecl(E, E->getMemberDecl()); 12789 } 12790 12791 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12792 return resolveDecl(E, E->getDecl()); 12793 } 12794 }; 12795 } 12796 12797 /// Given a function expression of unknown-any type, try to rebuild it 12798 /// to have a function type. 12799 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12800 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12801 if (Result.isInvalid()) return ExprError(); 12802 return S.DefaultFunctionArrayConversion(Result.take()); 12803 } 12804 12805 namespace { 12806 /// A visitor for rebuilding an expression of type __unknown_anytype 12807 /// into one which resolves the type directly on the referring 12808 /// expression. Strict preservation of the original source 12809 /// structure is not a goal. 12810 struct RebuildUnknownAnyExpr 12811 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12812 12813 Sema &S; 12814 12815 /// The current destination type. 12816 QualType DestType; 12817 12818 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12819 : S(S), DestType(CastType) {} 12820 12821 ExprResult VisitStmt(Stmt *S) { 12822 llvm_unreachable("unexpected statement!"); 12823 } 12824 12825 ExprResult VisitExpr(Expr *E) { 12826 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12827 << E->getSourceRange(); 12828 return ExprError(); 12829 } 12830 12831 ExprResult VisitCallExpr(CallExpr *E); 12832 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12833 12834 /// Rebuild an expression which simply semantically wraps another 12835 /// expression which it shares the type and value kind of. 12836 template <class T> ExprResult rebuildSugarExpr(T *E) { 12837 ExprResult SubResult = Visit(E->getSubExpr()); 12838 if (SubResult.isInvalid()) return ExprError(); 12839 Expr *SubExpr = SubResult.take(); 12840 E->setSubExpr(SubExpr); 12841 E->setType(SubExpr->getType()); 12842 E->setValueKind(SubExpr->getValueKind()); 12843 assert(E->getObjectKind() == OK_Ordinary); 12844 return E; 12845 } 12846 12847 ExprResult VisitParenExpr(ParenExpr *E) { 12848 return rebuildSugarExpr(E); 12849 } 12850 12851 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12852 return rebuildSugarExpr(E); 12853 } 12854 12855 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12856 const PointerType *Ptr = DestType->getAs<PointerType>(); 12857 if (!Ptr) { 12858 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12859 << E->getSourceRange(); 12860 return ExprError(); 12861 } 12862 assert(E->getValueKind() == VK_RValue); 12863 assert(E->getObjectKind() == OK_Ordinary); 12864 E->setType(DestType); 12865 12866 // Build the sub-expression as if it were an object of the pointee type. 12867 DestType = Ptr->getPointeeType(); 12868 ExprResult SubResult = Visit(E->getSubExpr()); 12869 if (SubResult.isInvalid()) return ExprError(); 12870 E->setSubExpr(SubResult.take()); 12871 return E; 12872 } 12873 12874 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12875 12876 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12877 12878 ExprResult VisitMemberExpr(MemberExpr *E) { 12879 return resolveDecl(E, E->getMemberDecl()); 12880 } 12881 12882 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12883 return resolveDecl(E, E->getDecl()); 12884 } 12885 }; 12886 } 12887 12888 /// Rebuilds a call expression which yielded __unknown_anytype. 12889 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12890 Expr *CalleeExpr = E->getCallee(); 12891 12892 enum FnKind { 12893 FK_MemberFunction, 12894 FK_FunctionPointer, 12895 FK_BlockPointer 12896 }; 12897 12898 FnKind Kind; 12899 QualType CalleeType = CalleeExpr->getType(); 12900 if (CalleeType == S.Context.BoundMemberTy) { 12901 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12902 Kind = FK_MemberFunction; 12903 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12904 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12905 CalleeType = Ptr->getPointeeType(); 12906 Kind = FK_FunctionPointer; 12907 } else { 12908 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12909 Kind = FK_BlockPointer; 12910 } 12911 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12912 12913 // Verify that this is a legal result type of a function. 12914 if (DestType->isArrayType() || DestType->isFunctionType()) { 12915 unsigned diagID = diag::err_func_returning_array_function; 12916 if (Kind == FK_BlockPointer) 12917 diagID = diag::err_block_returning_array_function; 12918 12919 S.Diag(E->getExprLoc(), diagID) 12920 << DestType->isFunctionType() << DestType; 12921 return ExprError(); 12922 } 12923 12924 // Otherwise, go ahead and set DestType as the call's result. 12925 E->setType(DestType.getNonLValueExprType(S.Context)); 12926 E->setValueKind(Expr::getValueKindForType(DestType)); 12927 assert(E->getObjectKind() == OK_Ordinary); 12928 12929 // Rebuild the function type, replacing the result type with DestType. 12930 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12931 if (Proto) { 12932 // __unknown_anytype(...) is a special case used by the debugger when 12933 // it has no idea what a function's signature is. 12934 // 12935 // We want to build this call essentially under the K&R 12936 // unprototyped rules, but making a FunctionNoProtoType in C++ 12937 // would foul up all sorts of assumptions. However, we cannot 12938 // simply pass all arguments as variadic arguments, nor can we 12939 // portably just call the function under a non-variadic type; see 12940 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12941 // However, it turns out that in practice it is generally safe to 12942 // call a function declared as "A foo(B,C,D);" under the prototype 12943 // "A foo(B,C,D,...);". The only known exception is with the 12944 // Windows ABI, where any variadic function is implicitly cdecl 12945 // regardless of its normal CC. Therefore we change the parameter 12946 // types to match the types of the arguments. 12947 // 12948 // This is a hack, but it is far superior to moving the 12949 // corresponding target-specific code from IR-gen to Sema/AST. 12950 12951 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 12952 SmallVector<QualType, 8> ArgTypes; 12953 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12954 ArgTypes.reserve(E->getNumArgs()); 12955 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12956 Expr *Arg = E->getArg(i); 12957 QualType ArgType = Arg->getType(); 12958 if (E->isLValue()) { 12959 ArgType = S.Context.getLValueReferenceType(ArgType); 12960 } else if (E->isXValue()) { 12961 ArgType = S.Context.getRValueReferenceType(ArgType); 12962 } 12963 ArgTypes.push_back(ArgType); 12964 } 12965 ParamTypes = ArgTypes; 12966 } 12967 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12968 Proto->getExtProtoInfo()); 12969 } else { 12970 DestType = S.Context.getFunctionNoProtoType(DestType, 12971 FnType->getExtInfo()); 12972 } 12973 12974 // Rebuild the appropriate pointer-to-function type. 12975 switch (Kind) { 12976 case FK_MemberFunction: 12977 // Nothing to do. 12978 break; 12979 12980 case FK_FunctionPointer: 12981 DestType = S.Context.getPointerType(DestType); 12982 break; 12983 12984 case FK_BlockPointer: 12985 DestType = S.Context.getBlockPointerType(DestType); 12986 break; 12987 } 12988 12989 // Finally, we can recurse. 12990 ExprResult CalleeResult = Visit(CalleeExpr); 12991 if (!CalleeResult.isUsable()) return ExprError(); 12992 E->setCallee(CalleeResult.take()); 12993 12994 // Bind a temporary if necessary. 12995 return S.MaybeBindToTemporary(E); 12996 } 12997 12998 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12999 // Verify that this is a legal result type of a call. 13000 if (DestType->isArrayType() || DestType->isFunctionType()) { 13001 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 13002 << DestType->isFunctionType() << DestType; 13003 return ExprError(); 13004 } 13005 13006 // Rewrite the method result type if available. 13007 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 13008 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 13009 Method->setReturnType(DestType); 13010 } 13011 13012 // Change the type of the message. 13013 E->setType(DestType.getNonReferenceType()); 13014 E->setValueKind(Expr::getValueKindForType(DestType)); 13015 13016 return S.MaybeBindToTemporary(E); 13017 } 13018 13019 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 13020 // The only case we should ever see here is a function-to-pointer decay. 13021 if (E->getCastKind() == CK_FunctionToPointerDecay) { 13022 assert(E->getValueKind() == VK_RValue); 13023 assert(E->getObjectKind() == OK_Ordinary); 13024 13025 E->setType(DestType); 13026 13027 // Rebuild the sub-expression as the pointee (function) type. 13028 DestType = DestType->castAs<PointerType>()->getPointeeType(); 13029 13030 ExprResult Result = Visit(E->getSubExpr()); 13031 if (!Result.isUsable()) return ExprError(); 13032 13033 E->setSubExpr(Result.take()); 13034 return S.Owned(E); 13035 } else if (E->getCastKind() == CK_LValueToRValue) { 13036 assert(E->getValueKind() == VK_RValue); 13037 assert(E->getObjectKind() == OK_Ordinary); 13038 13039 assert(isa<BlockPointerType>(E->getType())); 13040 13041 E->setType(DestType); 13042 13043 // The sub-expression has to be a lvalue reference, so rebuild it as such. 13044 DestType = S.Context.getLValueReferenceType(DestType); 13045 13046 ExprResult Result = Visit(E->getSubExpr()); 13047 if (!Result.isUsable()) return ExprError(); 13048 13049 E->setSubExpr(Result.take()); 13050 return S.Owned(E); 13051 } else { 13052 llvm_unreachable("Unhandled cast type!"); 13053 } 13054 } 13055 13056 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 13057 ExprValueKind ValueKind = VK_LValue; 13058 QualType Type = DestType; 13059 13060 // We know how to make this work for certain kinds of decls: 13061 13062 // - functions 13063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 13064 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 13065 DestType = Ptr->getPointeeType(); 13066 ExprResult Result = resolveDecl(E, VD); 13067 if (Result.isInvalid()) return ExprError(); 13068 return S.ImpCastExprToType(Result.take(), Type, 13069 CK_FunctionToPointerDecay, VK_RValue); 13070 } 13071 13072 if (!Type->isFunctionType()) { 13073 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 13074 << VD << E->getSourceRange(); 13075 return ExprError(); 13076 } 13077 13078 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 13079 if (MD->isInstance()) { 13080 ValueKind = VK_RValue; 13081 Type = S.Context.BoundMemberTy; 13082 } 13083 13084 // Function references aren't l-values in C. 13085 if (!S.getLangOpts().CPlusPlus) 13086 ValueKind = VK_RValue; 13087 13088 // - variables 13089 } else if (isa<VarDecl>(VD)) { 13090 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 13091 Type = RefTy->getPointeeType(); 13092 } else if (Type->isFunctionType()) { 13093 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 13094 << VD << E->getSourceRange(); 13095 return ExprError(); 13096 } 13097 13098 // - nothing else 13099 } else { 13100 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 13101 << VD << E->getSourceRange(); 13102 return ExprError(); 13103 } 13104 13105 // Modifying the declaration like this is friendly to IR-gen but 13106 // also really dangerous. 13107 VD->setType(DestType); 13108 E->setType(Type); 13109 E->setValueKind(ValueKind); 13110 return S.Owned(E); 13111 } 13112 13113 /// Check a cast of an unknown-any type. We intentionally only 13114 /// trigger this for C-style casts. 13115 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 13116 Expr *CastExpr, CastKind &CastKind, 13117 ExprValueKind &VK, CXXCastPath &Path) { 13118 // Rewrite the casted expression from scratch. 13119 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 13120 if (!result.isUsable()) return ExprError(); 13121 13122 CastExpr = result.take(); 13123 VK = CastExpr->getValueKind(); 13124 CastKind = CK_NoOp; 13125 13126 return CastExpr; 13127 } 13128 13129 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 13130 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 13131 } 13132 13133 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 13134 Expr *arg, QualType ¶mType) { 13135 // If the syntactic form of the argument is not an explicit cast of 13136 // any sort, just do default argument promotion. 13137 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 13138 if (!castArg) { 13139 ExprResult result = DefaultArgumentPromotion(arg); 13140 if (result.isInvalid()) return ExprError(); 13141 paramType = result.get()->getType(); 13142 return result; 13143 } 13144 13145 // Otherwise, use the type that was written in the explicit cast. 13146 assert(!arg->hasPlaceholderType()); 13147 paramType = castArg->getTypeAsWritten(); 13148 13149 // Copy-initialize a parameter of that type. 13150 InitializedEntity entity = 13151 InitializedEntity::InitializeParameter(Context, paramType, 13152 /*consumed*/ false); 13153 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 13154 } 13155 13156 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 13157 Expr *orig = E; 13158 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 13159 while (true) { 13160 E = E->IgnoreParenImpCasts(); 13161 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 13162 E = call->getCallee(); 13163 diagID = diag::err_uncasted_call_of_unknown_any; 13164 } else { 13165 break; 13166 } 13167 } 13168 13169 SourceLocation loc; 13170 NamedDecl *d; 13171 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 13172 loc = ref->getLocation(); 13173 d = ref->getDecl(); 13174 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 13175 loc = mem->getMemberLoc(); 13176 d = mem->getMemberDecl(); 13177 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 13178 diagID = diag::err_uncasted_call_of_unknown_any; 13179 loc = msg->getSelectorStartLoc(); 13180 d = msg->getMethodDecl(); 13181 if (!d) { 13182 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 13183 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 13184 << orig->getSourceRange(); 13185 return ExprError(); 13186 } 13187 } else { 13188 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13189 << E->getSourceRange(); 13190 return ExprError(); 13191 } 13192 13193 S.Diag(loc, diagID) << d << orig->getSourceRange(); 13194 13195 // Never recoverable. 13196 return ExprError(); 13197 } 13198 13199 /// Check for operands with placeholder types and complain if found. 13200 /// Returns true if there was an error and no recovery was possible. 13201 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 13202 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 13203 if (!placeholderType) return Owned(E); 13204 13205 switch (placeholderType->getKind()) { 13206 13207 // Overloaded expressions. 13208 case BuiltinType::Overload: { 13209 // Try to resolve a single function template specialization. 13210 // This is obligatory. 13211 ExprResult result = Owned(E); 13212 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 13213 return result; 13214 13215 // If that failed, try to recover with a call. 13216 } else { 13217 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 13218 /*complain*/ true); 13219 return result; 13220 } 13221 } 13222 13223 // Bound member functions. 13224 case BuiltinType::BoundMember: { 13225 ExprResult result = Owned(E); 13226 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 13227 /*complain*/ true); 13228 return result; 13229 } 13230 13231 // ARC unbridged casts. 13232 case BuiltinType::ARCUnbridgedCast: { 13233 Expr *realCast = stripARCUnbridgedCast(E); 13234 diagnoseARCUnbridgedCast(realCast); 13235 return Owned(realCast); 13236 } 13237 13238 // Expressions of unknown type. 13239 case BuiltinType::UnknownAny: 13240 return diagnoseUnknownAnyExpr(*this, E); 13241 13242 // Pseudo-objects. 13243 case BuiltinType::PseudoObject: 13244 return checkPseudoObjectRValue(E); 13245 13246 case BuiltinType::BuiltinFn: 13247 Diag(E->getLocStart(), diag::err_builtin_fn_use); 13248 return ExprError(); 13249 13250 // Everything else should be impossible. 13251 #define BUILTIN_TYPE(Id, SingletonId) \ 13252 case BuiltinType::Id: 13253 #define PLACEHOLDER_TYPE(Id, SingletonId) 13254 #include "clang/AST/BuiltinTypes.def" 13255 break; 13256 } 13257 13258 llvm_unreachable("invalid placeholder type!"); 13259 } 13260 13261 bool Sema::CheckCaseExpression(Expr *E) { 13262 if (E->isTypeDependent()) 13263 return true; 13264 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 13265 return E->getType()->isIntegralOrEnumerationType(); 13266 return false; 13267 } 13268 13269 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 13270 ExprResult 13271 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 13272 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 13273 "Unknown Objective-C Boolean value!"); 13274 QualType BoolT = Context.ObjCBuiltinBoolTy; 13275 if (!Context.getBOOLDecl()) { 13276 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 13277 Sema::LookupOrdinaryName); 13278 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 13279 NamedDecl *ND = Result.getFoundDecl(); 13280 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 13281 Context.setBOOLDecl(TD); 13282 } 13283 } 13284 if (Context.getBOOLDecl()) 13285 BoolT = Context.getBOOLType(); 13286 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 13287 BoolT, OpLoc)); 13288 } 13289