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 (FunctionDecl::redecl_iterator I = D->redecls_begin(), 172 E = D->redecls_end(); 173 I != E; ++I) { 174 if (I->getStorageClass() != SC_None) 175 return true; 176 } 177 return false; 178 } 179 180 /// \brief Check whether we're in an extern inline function and referring to a 181 /// variable or function with internal linkage (C11 6.7.4p3). 182 /// 183 /// This is only a warning because we used to silently accept this code, but 184 /// in many cases it will not behave correctly. This is not enabled in C++ mode 185 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 186 /// and so while there may still be user mistakes, most of the time we can't 187 /// prove that there are errors. 188 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 189 const NamedDecl *D, 190 SourceLocation Loc) { 191 // This is disabled under C++; there are too many ways for this to fire in 192 // contexts where the warning is a false positive, or where it is technically 193 // correct but benign. 194 if (S.getLangOpts().CPlusPlus) 195 return; 196 197 // Check if this is an inlined function or method. 198 FunctionDecl *Current = S.getCurFunctionDecl(); 199 if (!Current) 200 return; 201 if (!Current->isInlined()) 202 return; 203 if (!Current->isExternallyVisible()) 204 return; 205 206 // Check if the decl has internal linkage. 207 if (D->getFormalLinkage() != InternalLinkage) 208 return; 209 210 // Downgrade from ExtWarn to Extension if 211 // (1) the supposedly external inline function is in the main file, 212 // and probably won't be included anywhere else. 213 // (2) the thing we're referencing is a pure function. 214 // (3) the thing we're referencing is another inline function. 215 // This last can give us false negatives, but it's better than warning on 216 // wrappers for simple C library functions. 217 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 218 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 219 if (!DowngradeWarning && UsedFn) 220 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 221 222 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 223 : diag::warn_internal_in_extern_inline) 224 << /*IsVar=*/!UsedFn << D; 225 226 S.MaybeSuggestAddingStaticToDecl(Current); 227 228 S.Diag(D->getCanonicalDecl()->getLocation(), 229 diag::note_internal_decl_declared_here) 230 << D; 231 } 232 233 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 234 const FunctionDecl *First = Cur->getFirstDecl(); 235 236 // Suggest "static" on the function, if possible. 237 if (!hasAnyExplicitStorageClass(First)) { 238 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 239 Diag(DeclBegin, diag::note_convert_inline_to_static) 240 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 241 } 242 } 243 244 /// \brief Determine whether the use of this declaration is valid, and 245 /// emit any corresponding diagnostics. 246 /// 247 /// This routine diagnoses various problems with referencing 248 /// declarations that can occur when using a declaration. For example, 249 /// it might warn if a deprecated or unavailable declaration is being 250 /// used, or produce an error (and return true) if a C++0x deleted 251 /// function is being used. 252 /// 253 /// \returns true if there was an error (this declaration cannot be 254 /// referenced), false otherwise. 255 /// 256 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 257 const ObjCInterfaceDecl *UnknownObjCClass) { 258 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 259 // If there were any diagnostics suppressed by template argument deduction, 260 // emit them now. 261 SuppressedDiagnosticsMap::iterator 262 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 263 if (Pos != SuppressedDiagnostics.end()) { 264 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 265 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 266 Diag(Suppressed[I].first, Suppressed[I].second); 267 268 // Clear out the list of suppressed diagnostics, so that we don't emit 269 // them again for this specialization. However, we don't obsolete this 270 // entry from the table, because we want to avoid ever emitting these 271 // diagnostics again. 272 Suppressed.clear(); 273 } 274 275 // C++ [basic.start.main]p3: 276 // The function 'main' shall not be used within a program. 277 if (cast<FunctionDecl>(D)->isMain()) 278 Diag(Loc, diag::ext_main_used); 279 } 280 281 // See if this is an auto-typed variable whose initializer we are parsing. 282 if (ParsingInitForAutoVars.count(D)) { 283 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 284 << D->getDeclName(); 285 return true; 286 } 287 288 // See if this is a deleted function. 289 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 290 if (FD->isDeleted()) { 291 Diag(Loc, diag::err_deleted_function_use); 292 NoteDeletedFunction(FD); 293 return true; 294 } 295 296 // If the function has a deduced return type, and we can't deduce it, 297 // then we can't use it either. 298 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() && 299 DeduceReturnType(FD, Loc)) 300 return true; 301 } 302 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 303 304 DiagnoseUnusedOfDecl(*this, D, Loc); 305 306 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 307 308 return false; 309 } 310 311 /// \brief Retrieve the message suffix that should be added to a 312 /// diagnostic complaining about the given function being deleted or 313 /// unavailable. 314 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 315 std::string Message; 316 if (FD->getAvailability(&Message)) 317 return ": " + Message; 318 319 return std::string(); 320 } 321 322 /// DiagnoseSentinelCalls - This routine checks whether a call or 323 /// message-send is to a declaration with the sentinel attribute, and 324 /// if so, it checks that the requirements of the sentinel are 325 /// satisfied. 326 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 327 ArrayRef<Expr *> Args) { 328 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 329 if (!attr) 330 return; 331 332 // The number of formal parameters of the declaration. 333 unsigned numFormalParams; 334 335 // The kind of declaration. This is also an index into a %select in 336 // the diagnostic. 337 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 338 339 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 340 numFormalParams = MD->param_size(); 341 calleeType = CT_Method; 342 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 343 numFormalParams = FD->param_size(); 344 calleeType = CT_Function; 345 } else if (isa<VarDecl>(D)) { 346 QualType type = cast<ValueDecl>(D)->getType(); 347 const FunctionType *fn = 0; 348 if (const PointerType *ptr = type->getAs<PointerType>()) { 349 fn = ptr->getPointeeType()->getAs<FunctionType>(); 350 if (!fn) return; 351 calleeType = CT_Function; 352 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 353 fn = ptr->getPointeeType()->castAs<FunctionType>(); 354 calleeType = CT_Block; 355 } else { 356 return; 357 } 358 359 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 360 numFormalParams = proto->getNumParams(); 361 } else { 362 numFormalParams = 0; 363 } 364 } else { 365 return; 366 } 367 368 // "nullPos" is the number of formal parameters at the end which 369 // effectively count as part of the variadic arguments. This is 370 // useful if you would prefer to not have *any* formal parameters, 371 // but the language forces you to have at least one. 372 unsigned nullPos = attr->getNullPos(); 373 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 374 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 375 376 // The number of arguments which should follow the sentinel. 377 unsigned numArgsAfterSentinel = attr->getSentinel(); 378 379 // If there aren't enough arguments for all the formal parameters, 380 // the sentinel, and the args after the sentinel, complain. 381 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 382 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 383 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 384 return; 385 } 386 387 // Otherwise, find the sentinel expression. 388 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 389 if (!sentinelExpr) return; 390 if (sentinelExpr->isValueDependent()) return; 391 if (Context.isSentinelNullExpr(sentinelExpr)) return; 392 393 // Pick a reasonable string to insert. Optimistically use 'nil' or 394 // 'NULL' if those are actually defined in the context. Only use 395 // 'nil' for ObjC methods, where it's much more likely that the 396 // variadic arguments form a list of object pointers. 397 SourceLocation MissingNilLoc 398 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 399 std::string NullValue; 400 if (calleeType == CT_Method && 401 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 402 NullValue = "nil"; 403 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 404 NullValue = "NULL"; 405 else 406 NullValue = "(void*) 0"; 407 408 if (MissingNilLoc.isInvalid()) 409 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 410 else 411 Diag(MissingNilLoc, diag::warn_missing_sentinel) 412 << int(calleeType) 413 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 414 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 415 } 416 417 SourceRange Sema::getExprRange(Expr *E) const { 418 return E ? E->getSourceRange() : SourceRange(); 419 } 420 421 //===----------------------------------------------------------------------===// 422 // Standard Promotions and Conversions 423 //===----------------------------------------------------------------------===// 424 425 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 426 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 427 // Handle any placeholder expressions which made it here. 428 if (E->getType()->isPlaceholderType()) { 429 ExprResult result = CheckPlaceholderExpr(E); 430 if (result.isInvalid()) return ExprError(); 431 E = result.take(); 432 } 433 434 QualType Ty = E->getType(); 435 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 436 437 if (Ty->isFunctionType()) { 438 // If we are here, we are not calling a function but taking 439 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 440 if (getLangOpts().OpenCL) { 441 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 442 return ExprError(); 443 } 444 E = ImpCastExprToType(E, Context.getPointerType(Ty), 445 CK_FunctionToPointerDecay).take(); 446 } else if (Ty->isArrayType()) { 447 // In C90 mode, arrays only promote to pointers if the array expression is 448 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 449 // type 'array of type' is converted to an expression that has type 'pointer 450 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 451 // that has type 'array of type' ...". The relevant change is "an lvalue" 452 // (C90) to "an expression" (C99). 453 // 454 // C++ 4.2p1: 455 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 456 // T" can be converted to an rvalue of type "pointer to T". 457 // 458 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 459 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 460 CK_ArrayToPointerDecay).take(); 461 } 462 return Owned(E); 463 } 464 465 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 466 // Check to see if we are dereferencing a null pointer. If so, 467 // and if not volatile-qualified, this is undefined behavior that the 468 // optimizer will delete, so warn about it. People sometimes try to use this 469 // to get a deterministic trap and are surprised by clang's behavior. This 470 // only handles the pattern "*null", which is a very syntactic check. 471 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 472 if (UO->getOpcode() == UO_Deref && 473 UO->getSubExpr()->IgnoreParenCasts()-> 474 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 475 !UO->getType().isVolatileQualified()) { 476 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 477 S.PDiag(diag::warn_indirection_through_null) 478 << UO->getSubExpr()->getSourceRange()); 479 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 480 S.PDiag(diag::note_indirection_through_null)); 481 } 482 } 483 484 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 485 SourceLocation AssignLoc, 486 const Expr* RHS) { 487 const ObjCIvarDecl *IV = OIRE->getDecl(); 488 if (!IV) 489 return; 490 491 DeclarationName MemberName = IV->getDeclName(); 492 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 493 if (!Member || !Member->isStr("isa")) 494 return; 495 496 const Expr *Base = OIRE->getBase(); 497 QualType BaseType = Base->getType(); 498 if (OIRE->isArrow()) 499 BaseType = BaseType->getPointeeType(); 500 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 501 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 502 ObjCInterfaceDecl *ClassDeclared = 0; 503 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 504 if (!ClassDeclared->getSuperClass() 505 && (*ClassDeclared->ivar_begin()) == IV) { 506 if (RHS) { 507 NamedDecl *ObjectSetClass = 508 S.LookupSingleName(S.TUScope, 509 &S.Context.Idents.get("object_setClass"), 510 SourceLocation(), S.LookupOrdinaryName); 511 if (ObjectSetClass) { 512 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 513 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 514 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 515 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 516 AssignLoc), ",") << 517 FixItHint::CreateInsertion(RHSLocEnd, ")"); 518 } 519 else 520 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 521 } else { 522 NamedDecl *ObjectGetClass = 523 S.LookupSingleName(S.TUScope, 524 &S.Context.Idents.get("object_getClass"), 525 SourceLocation(), S.LookupOrdinaryName); 526 if (ObjectGetClass) 527 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 528 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 529 FixItHint::CreateReplacement( 530 SourceRange(OIRE->getOpLoc(), 531 OIRE->getLocEnd()), ")"); 532 else 533 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 534 } 535 S.Diag(IV->getLocation(), diag::note_ivar_decl); 536 } 537 } 538 } 539 540 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 541 // Handle any placeholder expressions which made it here. 542 if (E->getType()->isPlaceholderType()) { 543 ExprResult result = CheckPlaceholderExpr(E); 544 if (result.isInvalid()) return ExprError(); 545 E = result.take(); 546 } 547 548 // C++ [conv.lval]p1: 549 // A glvalue of a non-function, non-array type T can be 550 // converted to a prvalue. 551 if (!E->isGLValue()) return Owned(E); 552 553 QualType T = E->getType(); 554 assert(!T.isNull() && "r-value conversion on typeless expression?"); 555 556 // We don't want to throw lvalue-to-rvalue casts on top of 557 // expressions of certain types in C++. 558 if (getLangOpts().CPlusPlus && 559 (E->getType() == Context.OverloadTy || 560 T->isDependentType() || 561 T->isRecordType())) 562 return Owned(E); 563 564 // The C standard is actually really unclear on this point, and 565 // DR106 tells us what the result should be but not why. It's 566 // generally best to say that void types just doesn't undergo 567 // lvalue-to-rvalue at all. Note that expressions of unqualified 568 // 'void' type are never l-values, but qualified void can be. 569 if (T->isVoidType()) 570 return Owned(E); 571 572 // OpenCL usually rejects direct accesses to values of 'half' type. 573 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 574 T->isHalfType()) { 575 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 576 << 0 << T; 577 return ExprError(); 578 } 579 580 CheckForNullPointerDereference(*this, E); 581 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 582 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 583 &Context.Idents.get("object_getClass"), 584 SourceLocation(), LookupOrdinaryName); 585 if (ObjectGetClass) 586 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 587 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 588 FixItHint::CreateReplacement( 589 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 590 else 591 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 592 } 593 else if (const ObjCIvarRefExpr *OIRE = 594 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 595 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 596 597 // C++ [conv.lval]p1: 598 // [...] If T is a non-class type, the type of the prvalue is the 599 // cv-unqualified version of T. Otherwise, the type of the 600 // rvalue is T. 601 // 602 // C99 6.3.2.1p2: 603 // If the lvalue has qualified type, the value has the unqualified 604 // version of the type of the lvalue; otherwise, the value has the 605 // type of the lvalue. 606 if (T.hasQualifiers()) 607 T = T.getUnqualifiedType(); 608 609 UpdateMarkingForLValueToRValue(E); 610 611 // Loading a __weak object implicitly retains the value, so we need a cleanup to 612 // balance that. 613 if (getLangOpts().ObjCAutoRefCount && 614 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 615 ExprNeedsCleanups = true; 616 617 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 618 E, 0, VK_RValue)); 619 620 // C11 6.3.2.1p2: 621 // ... if the lvalue has atomic type, the value has the non-atomic version 622 // of the type of the lvalue ... 623 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 624 T = Atomic->getValueType().getUnqualifiedType(); 625 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 626 Res.get(), 0, VK_RValue)); 627 } 628 629 return Res; 630 } 631 632 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 633 ExprResult Res = DefaultFunctionArrayConversion(E); 634 if (Res.isInvalid()) 635 return ExprError(); 636 Res = DefaultLvalueConversion(Res.take()); 637 if (Res.isInvalid()) 638 return ExprError(); 639 return Res; 640 } 641 642 /// CallExprUnaryConversions - a special case of an unary conversion 643 /// performed on a function designator of a call expression. 644 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 645 QualType Ty = E->getType(); 646 ExprResult Res = E; 647 // Only do implicit cast for a function type, but not for a pointer 648 // to function type. 649 if (Ty->isFunctionType()) { 650 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 651 CK_FunctionToPointerDecay).take(); 652 if (Res.isInvalid()) 653 return ExprError(); 654 } 655 Res = DefaultLvalueConversion(Res.take()); 656 if (Res.isInvalid()) 657 return ExprError(); 658 return Owned(Res.take()); 659 } 660 661 /// UsualUnaryConversions - Performs various conversions that are common to most 662 /// operators (C99 6.3). The conversions of array and function types are 663 /// sometimes suppressed. For example, the array->pointer conversion doesn't 664 /// apply if the array is an argument to the sizeof or address (&) operators. 665 /// In these instances, this routine should *not* be called. 666 ExprResult Sema::UsualUnaryConversions(Expr *E) { 667 // First, convert to an r-value. 668 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 669 if (Res.isInvalid()) 670 return ExprError(); 671 E = Res.take(); 672 673 QualType Ty = E->getType(); 674 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 675 676 // Half FP have to be promoted to float unless it is natively supported 677 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 678 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 679 680 // Try to perform integral promotions if the object has a theoretically 681 // promotable type. 682 if (Ty->isIntegralOrUnscopedEnumerationType()) { 683 // C99 6.3.1.1p2: 684 // 685 // The following may be used in an expression wherever an int or 686 // unsigned int may be used: 687 // - an object or expression with an integer type whose integer 688 // conversion rank is less than or equal to the rank of int 689 // and unsigned int. 690 // - A bit-field of type _Bool, int, signed int, or unsigned int. 691 // 692 // If an int can represent all values of the original type, the 693 // value is converted to an int; otherwise, it is converted to an 694 // unsigned int. These are called the integer promotions. All 695 // other types are unchanged by the integer promotions. 696 697 QualType PTy = Context.isPromotableBitField(E); 698 if (!PTy.isNull()) { 699 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 700 return Owned(E); 701 } 702 if (Ty->isPromotableIntegerType()) { 703 QualType PT = Context.getPromotedIntegerType(Ty); 704 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 705 return Owned(E); 706 } 707 } 708 return Owned(E); 709 } 710 711 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 712 /// do not have a prototype. Arguments that have type float or __fp16 713 /// are promoted to double. All other argument types are converted by 714 /// UsualUnaryConversions(). 715 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 716 QualType Ty = E->getType(); 717 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 718 719 ExprResult Res = UsualUnaryConversions(E); 720 if (Res.isInvalid()) 721 return ExprError(); 722 E = Res.take(); 723 724 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 725 // double. 726 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 727 if (BTy && (BTy->getKind() == BuiltinType::Half || 728 BTy->getKind() == BuiltinType::Float)) 729 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 730 731 // C++ performs lvalue-to-rvalue conversion as a default argument 732 // promotion, even on class types, but note: 733 // C++11 [conv.lval]p2: 734 // When an lvalue-to-rvalue conversion occurs in an unevaluated 735 // operand or a subexpression thereof the value contained in the 736 // referenced object is not accessed. Otherwise, if the glvalue 737 // has a class type, the conversion copy-initializes a temporary 738 // of type T from the glvalue and the result of the conversion 739 // is a prvalue for the temporary. 740 // FIXME: add some way to gate this entire thing for correctness in 741 // potentially potentially evaluated contexts. 742 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 743 ExprResult Temp = PerformCopyInitialization( 744 InitializedEntity::InitializeTemporary(E->getType()), 745 E->getExprLoc(), 746 Owned(E)); 747 if (Temp.isInvalid()) 748 return ExprError(); 749 E = Temp.get(); 750 } 751 752 return Owned(E); 753 } 754 755 /// Determine the degree of POD-ness for an expression. 756 /// Incomplete types are considered POD, since this check can be performed 757 /// when we're in an unevaluated context. 758 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 759 if (Ty->isIncompleteType()) { 760 // C++11 [expr.call]p7: 761 // After these conversions, if the argument does not have arithmetic, 762 // enumeration, pointer, pointer to member, or class type, the program 763 // is ill-formed. 764 // 765 // Since we've already performed array-to-pointer and function-to-pointer 766 // decay, the only such type in C++ is cv void. This also handles 767 // initializer lists as variadic arguments. 768 if (Ty->isVoidType()) 769 return VAK_Invalid; 770 771 if (Ty->isObjCObjectType()) 772 return VAK_Invalid; 773 return VAK_Valid; 774 } 775 776 if (Ty.isCXX98PODType(Context)) 777 return VAK_Valid; 778 779 // C++11 [expr.call]p7: 780 // Passing a potentially-evaluated argument of class type (Clause 9) 781 // having a non-trivial copy constructor, a non-trivial move constructor, 782 // or a non-trivial destructor, with no corresponding parameter, 783 // is conditionally-supported with implementation-defined semantics. 784 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 785 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 786 if (!Record->hasNonTrivialCopyConstructor() && 787 !Record->hasNonTrivialMoveConstructor() && 788 !Record->hasNonTrivialDestructor()) 789 return VAK_ValidInCXX11; 790 791 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 792 return VAK_Valid; 793 794 if (Ty->isObjCObjectType()) 795 return VAK_Invalid; 796 797 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 798 // permitted to reject them. We should consider doing so. 799 return VAK_Undefined; 800 } 801 802 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 803 // Don't allow one to pass an Objective-C interface to a vararg. 804 const QualType &Ty = E->getType(); 805 VarArgKind VAK = isValidVarArgType(Ty); 806 807 // Complain about passing non-POD types through varargs. 808 switch (VAK) { 809 case VAK_ValidInCXX11: 810 DiagRuntimeBehavior( 811 E->getLocStart(), 0, 812 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 813 << Ty << CT); 814 // Fall through. 815 case VAK_Valid: 816 if (Ty->isRecordType()) { 817 // This is unlikely to be what the user intended. If the class has a 818 // 'c_str' member function, the user probably meant to call that. 819 DiagRuntimeBehavior(E->getLocStart(), 0, 820 PDiag(diag::warn_pass_class_arg_to_vararg) 821 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 822 } 823 break; 824 825 case VAK_Undefined: 826 DiagRuntimeBehavior( 827 E->getLocStart(), 0, 828 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 829 << getLangOpts().CPlusPlus11 << Ty << CT); 830 break; 831 832 case VAK_Invalid: 833 if (Ty->isObjCObjectType()) 834 DiagRuntimeBehavior( 835 E->getLocStart(), 0, 836 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 837 << Ty << CT); 838 else 839 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 840 << isa<InitListExpr>(E) << Ty << CT; 841 break; 842 } 843 } 844 845 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 846 /// will create a trap if the resulting type is not a POD type. 847 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 848 FunctionDecl *FDecl) { 849 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 850 // Strip the unbridged-cast placeholder expression off, if applicable. 851 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 852 (CT == VariadicMethod || 853 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 854 E = stripARCUnbridgedCast(E); 855 856 // Otherwise, do normal placeholder checking. 857 } else { 858 ExprResult ExprRes = CheckPlaceholderExpr(E); 859 if (ExprRes.isInvalid()) 860 return ExprError(); 861 E = ExprRes.take(); 862 } 863 } 864 865 ExprResult ExprRes = DefaultArgumentPromotion(E); 866 if (ExprRes.isInvalid()) 867 return ExprError(); 868 E = ExprRes.take(); 869 870 // Diagnostics regarding non-POD argument types are 871 // emitted along with format string checking in Sema::CheckFunctionCall(). 872 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 873 // Turn this into a trap. 874 CXXScopeSpec SS; 875 SourceLocation TemplateKWLoc; 876 UnqualifiedId Name; 877 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 878 E->getLocStart()); 879 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 880 Name, true, false); 881 if (TrapFn.isInvalid()) 882 return ExprError(); 883 884 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 885 E->getLocStart(), None, 886 E->getLocEnd()); 887 if (Call.isInvalid()) 888 return ExprError(); 889 890 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 891 Call.get(), E); 892 if (Comma.isInvalid()) 893 return ExprError(); 894 return Comma.get(); 895 } 896 897 if (!getLangOpts().CPlusPlus && 898 RequireCompleteType(E->getExprLoc(), E->getType(), 899 diag::err_call_incomplete_argument)) 900 return ExprError(); 901 902 return Owned(E); 903 } 904 905 /// \brief Converts an integer to complex float type. Helper function of 906 /// UsualArithmeticConversions() 907 /// 908 /// \return false if the integer expression is an integer type and is 909 /// successfully converted to the complex type. 910 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 911 ExprResult &ComplexExpr, 912 QualType IntTy, 913 QualType ComplexTy, 914 bool SkipCast) { 915 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 916 if (SkipCast) return false; 917 if (IntTy->isIntegerType()) { 918 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 919 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 920 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 921 CK_FloatingRealToComplex); 922 } else { 923 assert(IntTy->isComplexIntegerType()); 924 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 925 CK_IntegralComplexToFloatingComplex); 926 } 927 return false; 928 } 929 930 /// \brief Takes two complex float types and converts them to the same type. 931 /// Helper function of UsualArithmeticConversions() 932 static QualType 933 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 934 ExprResult &RHS, QualType LHSType, 935 QualType RHSType, 936 bool IsCompAssign) { 937 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 938 939 if (order < 0) { 940 // _Complex float -> _Complex double 941 if (!IsCompAssign) 942 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 943 return RHSType; 944 } 945 if (order > 0) 946 // _Complex float -> _Complex double 947 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 948 return LHSType; 949 } 950 951 /// \brief Converts otherExpr to complex float and promotes complexExpr if 952 /// necessary. Helper function of UsualArithmeticConversions() 953 static QualType handleOtherComplexFloatConversion(Sema &S, 954 ExprResult &ComplexExpr, 955 ExprResult &OtherExpr, 956 QualType ComplexTy, 957 QualType OtherTy, 958 bool ConvertComplexExpr, 959 bool ConvertOtherExpr) { 960 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 961 962 // If just the complexExpr is complex, the otherExpr needs to be converted, 963 // and the complexExpr might need to be promoted. 964 if (order > 0) { // complexExpr is wider 965 // float -> _Complex double 966 if (ConvertOtherExpr) { 967 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 968 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 969 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 970 CK_FloatingRealToComplex); 971 } 972 return ComplexTy; 973 } 974 975 // otherTy is at least as wide. Find its corresponding complex type. 976 QualType result = (order == 0 ? ComplexTy : 977 S.Context.getComplexType(OtherTy)); 978 979 // double -> _Complex double 980 if (ConvertOtherExpr) 981 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 982 CK_FloatingRealToComplex); 983 984 // _Complex float -> _Complex double 985 if (ConvertComplexExpr && order < 0) 986 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 987 CK_FloatingComplexCast); 988 989 return result; 990 } 991 992 /// \brief Handle arithmetic conversion with complex types. Helper function of 993 /// UsualArithmeticConversions() 994 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 995 ExprResult &RHS, QualType LHSType, 996 QualType RHSType, 997 bool IsCompAssign) { 998 // if we have an integer operand, the result is the complex type. 999 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1000 /*skipCast*/false)) 1001 return LHSType; 1002 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1003 /*skipCast*/IsCompAssign)) 1004 return RHSType; 1005 1006 // This handles complex/complex, complex/float, or float/complex. 1007 // When both operands are complex, the shorter operand is converted to the 1008 // type of the longer, and that is the type of the result. This corresponds 1009 // to what is done when combining two real floating-point operands. 1010 // The fun begins when size promotion occur across type domains. 1011 // From H&S 6.3.4: When one operand is complex and the other is a real 1012 // floating-point type, the less precise type is converted, within it's 1013 // real or complex domain, to the precision of the other type. For example, 1014 // when combining a "long double" with a "double _Complex", the 1015 // "double _Complex" is promoted to "long double _Complex". 1016 1017 bool LHSComplexFloat = LHSType->isComplexType(); 1018 bool RHSComplexFloat = RHSType->isComplexType(); 1019 1020 // If both are complex, just cast to the more precise type. 1021 if (LHSComplexFloat && RHSComplexFloat) 1022 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 1023 LHSType, RHSType, 1024 IsCompAssign); 1025 1026 // If only one operand is complex, promote it if necessary and convert the 1027 // other operand to complex. 1028 if (LHSComplexFloat) 1029 return handleOtherComplexFloatConversion( 1030 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1031 /*convertOtherExpr*/ true); 1032 1033 assert(RHSComplexFloat); 1034 return handleOtherComplexFloatConversion( 1035 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1036 /*convertOtherExpr*/ !IsCompAssign); 1037 } 1038 1039 /// \brief Hande arithmetic conversion from integer to float. Helper function 1040 /// of UsualArithmeticConversions() 1041 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1042 ExprResult &IntExpr, 1043 QualType FloatTy, QualType IntTy, 1044 bool ConvertFloat, bool ConvertInt) { 1045 if (IntTy->isIntegerType()) { 1046 if (ConvertInt) 1047 // Convert intExpr to the lhs floating point type. 1048 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 1049 CK_IntegralToFloating); 1050 return FloatTy; 1051 } 1052 1053 // Convert both sides to the appropriate complex float. 1054 assert(IntTy->isComplexIntegerType()); 1055 QualType result = S.Context.getComplexType(FloatTy); 1056 1057 // _Complex int -> _Complex float 1058 if (ConvertInt) 1059 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 1060 CK_IntegralComplexToFloatingComplex); 1061 1062 // float -> _Complex float 1063 if (ConvertFloat) 1064 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1065 CK_FloatingRealToComplex); 1066 1067 return result; 1068 } 1069 1070 /// \brief Handle arithmethic conversion with floating point types. Helper 1071 /// function of UsualArithmeticConversions() 1072 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1073 ExprResult &RHS, QualType LHSType, 1074 QualType RHSType, bool IsCompAssign) { 1075 bool LHSFloat = LHSType->isRealFloatingType(); 1076 bool RHSFloat = RHSType->isRealFloatingType(); 1077 1078 // If we have two real floating types, convert the smaller operand 1079 // to the bigger result. 1080 if (LHSFloat && RHSFloat) { 1081 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1082 if (order > 0) { 1083 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1084 return LHSType; 1085 } 1086 1087 assert(order < 0 && "illegal float comparison"); 1088 if (!IsCompAssign) 1089 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1090 return RHSType; 1091 } 1092 1093 if (LHSFloat) 1094 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1095 /*convertFloat=*/!IsCompAssign, 1096 /*convertInt=*/ true); 1097 assert(RHSFloat); 1098 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1099 /*convertInt=*/ true, 1100 /*convertFloat=*/!IsCompAssign); 1101 } 1102 1103 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1104 1105 namespace { 1106 /// These helper callbacks are placed in an anonymous namespace to 1107 /// permit their use as function template parameters. 1108 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1109 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1110 } 1111 1112 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1113 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1114 CK_IntegralComplexCast); 1115 } 1116 } 1117 1118 /// \brief Handle integer arithmetic conversions. Helper function of 1119 /// UsualArithmeticConversions() 1120 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1121 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1122 ExprResult &RHS, QualType LHSType, 1123 QualType RHSType, bool IsCompAssign) { 1124 // The rules for this case are in C99 6.3.1.8 1125 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1126 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1127 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1128 if (LHSSigned == RHSSigned) { 1129 // Same signedness; use the higher-ranked type 1130 if (order >= 0) { 1131 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1132 return LHSType; 1133 } else if (!IsCompAssign) 1134 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1135 return RHSType; 1136 } else if (order != (LHSSigned ? 1 : -1)) { 1137 // The unsigned type has greater than or equal rank to the 1138 // signed type, so use the unsigned type 1139 if (RHSSigned) { 1140 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1141 return LHSType; 1142 } else if (!IsCompAssign) 1143 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1144 return RHSType; 1145 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1146 // The two types are different widths; if we are here, that 1147 // means the signed type is larger than the unsigned type, so 1148 // use the signed type. 1149 if (LHSSigned) { 1150 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1151 return LHSType; 1152 } else if (!IsCompAssign) 1153 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1154 return RHSType; 1155 } else { 1156 // The signed type is higher-ranked than the unsigned type, 1157 // but isn't actually any bigger (like unsigned int and long 1158 // on most 32-bit systems). Use the unsigned type corresponding 1159 // to the signed type. 1160 QualType result = 1161 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1162 RHS = (*doRHSCast)(S, RHS.take(), result); 1163 if (!IsCompAssign) 1164 LHS = (*doLHSCast)(S, LHS.take(), result); 1165 return result; 1166 } 1167 } 1168 1169 /// \brief Handle conversions with GCC complex int extension. Helper function 1170 /// of UsualArithmeticConversions() 1171 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1172 ExprResult &RHS, QualType LHSType, 1173 QualType RHSType, 1174 bool IsCompAssign) { 1175 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1176 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1177 1178 if (LHSComplexInt && RHSComplexInt) { 1179 QualType LHSEltType = LHSComplexInt->getElementType(); 1180 QualType RHSEltType = RHSComplexInt->getElementType(); 1181 QualType ScalarType = 1182 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1183 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1184 1185 return S.Context.getComplexType(ScalarType); 1186 } 1187 1188 if (LHSComplexInt) { 1189 QualType LHSEltType = LHSComplexInt->getElementType(); 1190 QualType ScalarType = 1191 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1192 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1193 QualType ComplexType = S.Context.getComplexType(ScalarType); 1194 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1195 CK_IntegralRealToComplex); 1196 1197 return ComplexType; 1198 } 1199 1200 assert(RHSComplexInt); 1201 1202 QualType RHSEltType = RHSComplexInt->getElementType(); 1203 QualType ScalarType = 1204 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1205 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1206 QualType ComplexType = S.Context.getComplexType(ScalarType); 1207 1208 if (!IsCompAssign) 1209 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1210 CK_IntegralRealToComplex); 1211 return ComplexType; 1212 } 1213 1214 /// UsualArithmeticConversions - Performs various conversions that are common to 1215 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1216 /// routine returns the first non-arithmetic type found. The client is 1217 /// responsible for emitting appropriate error diagnostics. 1218 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1219 bool IsCompAssign) { 1220 if (!IsCompAssign) { 1221 LHS = UsualUnaryConversions(LHS.take()); 1222 if (LHS.isInvalid()) 1223 return QualType(); 1224 } 1225 1226 RHS = UsualUnaryConversions(RHS.take()); 1227 if (RHS.isInvalid()) 1228 return QualType(); 1229 1230 // For conversion purposes, we ignore any qualifiers. 1231 // For example, "const float" and "float" are equivalent. 1232 QualType LHSType = 1233 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1234 QualType RHSType = 1235 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1236 1237 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1238 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1239 LHSType = AtomicLHS->getValueType(); 1240 1241 // If both types are identical, no conversion is needed. 1242 if (LHSType == RHSType) 1243 return LHSType; 1244 1245 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1246 // The caller can deal with this (e.g. pointer + int). 1247 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1248 return QualType(); 1249 1250 // Apply unary and bitfield promotions to the LHS's type. 1251 QualType LHSUnpromotedType = LHSType; 1252 if (LHSType->isPromotableIntegerType()) 1253 LHSType = Context.getPromotedIntegerType(LHSType); 1254 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1255 if (!LHSBitfieldPromoteTy.isNull()) 1256 LHSType = LHSBitfieldPromoteTy; 1257 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1258 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1259 1260 // If both types are identical, no conversion is needed. 1261 if (LHSType == RHSType) 1262 return LHSType; 1263 1264 // At this point, we have two different arithmetic types. 1265 1266 // Handle complex types first (C99 6.3.1.8p1). 1267 if (LHSType->isComplexType() || RHSType->isComplexType()) 1268 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1269 IsCompAssign); 1270 1271 // Now handle "real" floating types (i.e. float, double, long double). 1272 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1273 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1274 IsCompAssign); 1275 1276 // Handle GCC complex int extension. 1277 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1278 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1279 IsCompAssign); 1280 1281 // Finally, we have two differing integer types. 1282 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1283 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1284 } 1285 1286 1287 //===----------------------------------------------------------------------===// 1288 // Semantic Analysis for various Expression Types 1289 //===----------------------------------------------------------------------===// 1290 1291 1292 ExprResult 1293 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1294 SourceLocation DefaultLoc, 1295 SourceLocation RParenLoc, 1296 Expr *ControllingExpr, 1297 ArrayRef<ParsedType> ArgTypes, 1298 ArrayRef<Expr *> ArgExprs) { 1299 unsigned NumAssocs = ArgTypes.size(); 1300 assert(NumAssocs == ArgExprs.size()); 1301 1302 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1303 for (unsigned i = 0; i < NumAssocs; ++i) { 1304 if (ArgTypes[i]) 1305 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1306 else 1307 Types[i] = 0; 1308 } 1309 1310 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1311 ControllingExpr, 1312 llvm::makeArrayRef(Types, NumAssocs), 1313 ArgExprs); 1314 delete [] Types; 1315 return ER; 1316 } 1317 1318 ExprResult 1319 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1320 SourceLocation DefaultLoc, 1321 SourceLocation RParenLoc, 1322 Expr *ControllingExpr, 1323 ArrayRef<TypeSourceInfo *> Types, 1324 ArrayRef<Expr *> Exprs) { 1325 unsigned NumAssocs = Types.size(); 1326 assert(NumAssocs == Exprs.size()); 1327 if (ControllingExpr->getType()->isPlaceholderType()) { 1328 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1329 if (result.isInvalid()) return ExprError(); 1330 ControllingExpr = result.take(); 1331 } 1332 1333 bool TypeErrorFound = false, 1334 IsResultDependent = ControllingExpr->isTypeDependent(), 1335 ContainsUnexpandedParameterPack 1336 = ControllingExpr->containsUnexpandedParameterPack(); 1337 1338 for (unsigned i = 0; i < NumAssocs; ++i) { 1339 if (Exprs[i]->containsUnexpandedParameterPack()) 1340 ContainsUnexpandedParameterPack = true; 1341 1342 if (Types[i]) { 1343 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1344 ContainsUnexpandedParameterPack = true; 1345 1346 if (Types[i]->getType()->isDependentType()) { 1347 IsResultDependent = true; 1348 } else { 1349 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1350 // complete object type other than a variably modified type." 1351 unsigned D = 0; 1352 if (Types[i]->getType()->isIncompleteType()) 1353 D = diag::err_assoc_type_incomplete; 1354 else if (!Types[i]->getType()->isObjectType()) 1355 D = diag::err_assoc_type_nonobject; 1356 else if (Types[i]->getType()->isVariablyModifiedType()) 1357 D = diag::err_assoc_type_variably_modified; 1358 1359 if (D != 0) { 1360 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1361 << Types[i]->getTypeLoc().getSourceRange() 1362 << Types[i]->getType(); 1363 TypeErrorFound = true; 1364 } 1365 1366 // C11 6.5.1.1p2 "No two generic associations in the same generic 1367 // selection shall specify compatible types." 1368 for (unsigned j = i+1; j < NumAssocs; ++j) 1369 if (Types[j] && !Types[j]->getType()->isDependentType() && 1370 Context.typesAreCompatible(Types[i]->getType(), 1371 Types[j]->getType())) { 1372 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1373 diag::err_assoc_compatible_types) 1374 << Types[j]->getTypeLoc().getSourceRange() 1375 << Types[j]->getType() 1376 << Types[i]->getType(); 1377 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1378 diag::note_compat_assoc) 1379 << Types[i]->getTypeLoc().getSourceRange() 1380 << Types[i]->getType(); 1381 TypeErrorFound = true; 1382 } 1383 } 1384 } 1385 } 1386 if (TypeErrorFound) 1387 return ExprError(); 1388 1389 // If we determined that the generic selection is result-dependent, don't 1390 // try to compute the result expression. 1391 if (IsResultDependent) 1392 return Owned(new (Context) GenericSelectionExpr( 1393 Context, KeyLoc, ControllingExpr, 1394 Types, Exprs, 1395 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1396 1397 SmallVector<unsigned, 1> CompatIndices; 1398 unsigned DefaultIndex = -1U; 1399 for (unsigned i = 0; i < NumAssocs; ++i) { 1400 if (!Types[i]) 1401 DefaultIndex = i; 1402 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1403 Types[i]->getType())) 1404 CompatIndices.push_back(i); 1405 } 1406 1407 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1408 // type compatible with at most one of the types named in its generic 1409 // association list." 1410 if (CompatIndices.size() > 1) { 1411 // We strip parens here because the controlling expression is typically 1412 // parenthesized in macro definitions. 1413 ControllingExpr = ControllingExpr->IgnoreParens(); 1414 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1415 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1416 << (unsigned) CompatIndices.size(); 1417 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1418 E = CompatIndices.end(); I != E; ++I) { 1419 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1420 diag::note_compat_assoc) 1421 << Types[*I]->getTypeLoc().getSourceRange() 1422 << Types[*I]->getType(); 1423 } 1424 return ExprError(); 1425 } 1426 1427 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1428 // its controlling expression shall have type compatible with exactly one of 1429 // the types named in its generic association list." 1430 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1431 // We strip parens here because the controlling expression is typically 1432 // parenthesized in macro definitions. 1433 ControllingExpr = ControllingExpr->IgnoreParens(); 1434 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1435 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1436 return ExprError(); 1437 } 1438 1439 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1440 // type name that is compatible with the type of the controlling expression, 1441 // then the result expression of the generic selection is the expression 1442 // in that generic association. Otherwise, the result expression of the 1443 // generic selection is the expression in the default generic association." 1444 unsigned ResultIndex = 1445 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1446 1447 return Owned(new (Context) GenericSelectionExpr( 1448 Context, KeyLoc, ControllingExpr, 1449 Types, Exprs, 1450 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1451 ResultIndex)); 1452 } 1453 1454 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1455 /// location of the token and the offset of the ud-suffix within it. 1456 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1457 unsigned Offset) { 1458 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1459 S.getLangOpts()); 1460 } 1461 1462 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1463 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1464 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1465 IdentifierInfo *UDSuffix, 1466 SourceLocation UDSuffixLoc, 1467 ArrayRef<Expr*> Args, 1468 SourceLocation LitEndLoc) { 1469 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1470 1471 QualType ArgTy[2]; 1472 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1473 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1474 if (ArgTy[ArgIdx]->isArrayType()) 1475 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1476 } 1477 1478 DeclarationName OpName = 1479 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1480 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1481 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1482 1483 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1484 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1485 /*AllowRaw*/false, /*AllowTemplate*/false, 1486 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1487 return ExprError(); 1488 1489 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1490 } 1491 1492 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1493 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1494 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1495 /// multiple tokens. However, the common case is that StringToks points to one 1496 /// string. 1497 /// 1498 ExprResult 1499 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1500 Scope *UDLScope) { 1501 assert(NumStringToks && "Must have at least one string!"); 1502 1503 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1504 if (Literal.hadError) 1505 return ExprError(); 1506 1507 SmallVector<SourceLocation, 4> StringTokLocs; 1508 for (unsigned i = 0; i != NumStringToks; ++i) 1509 StringTokLocs.push_back(StringToks[i].getLocation()); 1510 1511 QualType CharTy = Context.CharTy; 1512 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1513 if (Literal.isWide()) { 1514 CharTy = Context.getWideCharType(); 1515 Kind = StringLiteral::Wide; 1516 } else if (Literal.isUTF8()) { 1517 Kind = StringLiteral::UTF8; 1518 } else if (Literal.isUTF16()) { 1519 CharTy = Context.Char16Ty; 1520 Kind = StringLiteral::UTF16; 1521 } else if (Literal.isUTF32()) { 1522 CharTy = Context.Char32Ty; 1523 Kind = StringLiteral::UTF32; 1524 } else if (Literal.isPascal()) { 1525 CharTy = Context.UnsignedCharTy; 1526 } 1527 1528 QualType CharTyConst = CharTy; 1529 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1530 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1531 CharTyConst.addConst(); 1532 1533 // Get an array type for the string, according to C99 6.4.5. This includes 1534 // the nul terminator character as well as the string length for pascal 1535 // strings. 1536 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1537 llvm::APInt(32, Literal.GetNumStringChars()+1), 1538 ArrayType::Normal, 0); 1539 1540 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1541 if (getLangOpts().OpenCL) { 1542 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1543 } 1544 1545 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1546 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1547 Kind, Literal.Pascal, StrTy, 1548 &StringTokLocs[0], 1549 StringTokLocs.size()); 1550 if (Literal.getUDSuffix().empty()) 1551 return Owned(Lit); 1552 1553 // We're building a user-defined literal. 1554 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1555 SourceLocation UDSuffixLoc = 1556 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1557 Literal.getUDSuffixOffset()); 1558 1559 // Make sure we're allowed user-defined literals here. 1560 if (!UDLScope) 1561 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1562 1563 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1564 // operator "" X (str, len) 1565 QualType SizeType = Context.getSizeType(); 1566 1567 DeclarationName OpName = 1568 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1569 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1570 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1571 1572 QualType ArgTy[] = { 1573 Context.getArrayDecayedType(StrTy), SizeType 1574 }; 1575 1576 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1577 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1578 /*AllowRaw*/false, /*AllowTemplate*/false, 1579 /*AllowStringTemplate*/true)) { 1580 1581 case LOLR_Cooked: { 1582 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1583 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1584 StringTokLocs[0]); 1585 Expr *Args[] = { Lit, LenArg }; 1586 1587 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1588 } 1589 1590 case LOLR_StringTemplate: { 1591 TemplateArgumentListInfo ExplicitArgs; 1592 1593 unsigned CharBits = Context.getIntWidth(CharTy); 1594 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1595 llvm::APSInt Value(CharBits, CharIsUnsigned); 1596 1597 TemplateArgument TypeArg(CharTy); 1598 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1599 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1600 1601 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1602 Value = Lit->getCodeUnit(I); 1603 TemplateArgument Arg(Context, Value, CharTy); 1604 TemplateArgumentLocInfo ArgInfo; 1605 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1606 } 1607 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1608 &ExplicitArgs); 1609 } 1610 case LOLR_Raw: 1611 case LOLR_Template: 1612 llvm_unreachable("unexpected literal operator lookup result"); 1613 case LOLR_Error: 1614 return ExprError(); 1615 } 1616 llvm_unreachable("unexpected literal operator lookup result"); 1617 } 1618 1619 ExprResult 1620 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1621 SourceLocation Loc, 1622 const CXXScopeSpec *SS) { 1623 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1624 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1625 } 1626 1627 /// BuildDeclRefExpr - Build an expression that references a 1628 /// declaration that does not require a closure capture. 1629 ExprResult 1630 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1631 const DeclarationNameInfo &NameInfo, 1632 const CXXScopeSpec *SS, NamedDecl *FoundD, 1633 const TemplateArgumentListInfo *TemplateArgs) { 1634 if (getLangOpts().CUDA) 1635 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1636 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1637 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1638 CalleeTarget = IdentifyCUDATarget(Callee); 1639 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1640 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1641 << CalleeTarget << D->getIdentifier() << CallerTarget; 1642 Diag(D->getLocation(), diag::note_previous_decl) 1643 << D->getIdentifier(); 1644 return ExprError(); 1645 } 1646 } 1647 1648 bool refersToEnclosingScope = 1649 (CurContext != D->getDeclContext() && 1650 D->getDeclContext()->isFunctionOrMethod()) || 1651 (isa<VarDecl>(D) && 1652 cast<VarDecl>(D)->isInitCapture()); 1653 1654 DeclRefExpr *E; 1655 if (isa<VarTemplateSpecializationDecl>(D)) { 1656 VarTemplateSpecializationDecl *VarSpec = 1657 cast<VarTemplateSpecializationDecl>(D); 1658 1659 E = DeclRefExpr::Create( 1660 Context, 1661 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1662 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1663 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1664 } else { 1665 assert(!TemplateArgs && "No template arguments for non-variable" 1666 " template specialization references"); 1667 E = DeclRefExpr::Create( 1668 Context, 1669 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1670 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1671 } 1672 1673 MarkDeclRefReferenced(E); 1674 1675 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1676 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1677 DiagnosticsEngine::Level Level = 1678 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1679 E->getLocStart()); 1680 if (Level != DiagnosticsEngine::Ignored) 1681 recordUseOfEvaluatedWeak(E); 1682 } 1683 1684 // Just in case we're building an illegal pointer-to-member. 1685 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1686 if (FD && FD->isBitField()) 1687 E->setObjectKind(OK_BitField); 1688 1689 return Owned(E); 1690 } 1691 1692 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1693 /// possibly a list of template arguments. 1694 /// 1695 /// If this produces template arguments, it is permitted to call 1696 /// DecomposeTemplateName. 1697 /// 1698 /// This actually loses a lot of source location information for 1699 /// non-standard name kinds; we should consider preserving that in 1700 /// some way. 1701 void 1702 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1703 TemplateArgumentListInfo &Buffer, 1704 DeclarationNameInfo &NameInfo, 1705 const TemplateArgumentListInfo *&TemplateArgs) { 1706 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1707 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1708 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1709 1710 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1711 Id.TemplateId->NumArgs); 1712 translateTemplateArguments(TemplateArgsPtr, Buffer); 1713 1714 TemplateName TName = Id.TemplateId->Template.get(); 1715 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1716 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1717 TemplateArgs = &Buffer; 1718 } else { 1719 NameInfo = GetNameFromUnqualifiedId(Id); 1720 TemplateArgs = 0; 1721 } 1722 } 1723 1724 /// Diagnose an empty lookup. 1725 /// 1726 /// \return false if new lookup candidates were found 1727 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1728 CorrectionCandidateCallback &CCC, 1729 TemplateArgumentListInfo *ExplicitTemplateArgs, 1730 ArrayRef<Expr *> Args) { 1731 DeclarationName Name = R.getLookupName(); 1732 1733 unsigned diagnostic = diag::err_undeclared_var_use; 1734 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1735 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1736 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1737 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1738 diagnostic = diag::err_undeclared_use; 1739 diagnostic_suggest = diag::err_undeclared_use_suggest; 1740 } 1741 1742 // If the original lookup was an unqualified lookup, fake an 1743 // unqualified lookup. This is useful when (for example) the 1744 // original lookup would not have found something because it was a 1745 // dependent name. 1746 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1747 ? CurContext : 0; 1748 while (DC) { 1749 if (isa<CXXRecordDecl>(DC)) { 1750 LookupQualifiedName(R, DC); 1751 1752 if (!R.empty()) { 1753 // Don't give errors about ambiguities in this lookup. 1754 R.suppressDiagnostics(); 1755 1756 // During a default argument instantiation the CurContext points 1757 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1758 // function parameter list, hence add an explicit check. 1759 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1760 ActiveTemplateInstantiations.back().Kind == 1761 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1762 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1763 bool isInstance = CurMethod && 1764 CurMethod->isInstance() && 1765 DC == CurMethod->getParent() && !isDefaultArgument; 1766 1767 1768 // Give a code modification hint to insert 'this->'. 1769 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1770 // Actually quite difficult! 1771 if (getLangOpts().MSVCCompat) 1772 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1773 if (isInstance) { 1774 Diag(R.getNameLoc(), diagnostic) << Name 1775 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1776 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1777 CallsUndergoingInstantiation.back()->getCallee()); 1778 1779 CXXMethodDecl *DepMethod; 1780 if (CurMethod->isDependentContext()) 1781 DepMethod = CurMethod; 1782 else if (CurMethod->getTemplatedKind() == 1783 FunctionDecl::TK_FunctionTemplateSpecialization) 1784 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1785 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1786 else 1787 DepMethod = cast<CXXMethodDecl>( 1788 CurMethod->getInstantiatedFromMemberFunction()); 1789 assert(DepMethod && "No template pattern found"); 1790 1791 QualType DepThisType = DepMethod->getThisType(Context); 1792 CheckCXXThisCapture(R.getNameLoc()); 1793 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1794 R.getNameLoc(), DepThisType, false); 1795 TemplateArgumentListInfo TList; 1796 if (ULE->hasExplicitTemplateArgs()) 1797 ULE->copyTemplateArgumentsInto(TList); 1798 1799 CXXScopeSpec SS; 1800 SS.Adopt(ULE->getQualifierLoc()); 1801 CXXDependentScopeMemberExpr *DepExpr = 1802 CXXDependentScopeMemberExpr::Create( 1803 Context, DepThis, DepThisType, true, SourceLocation(), 1804 SS.getWithLocInContext(Context), 1805 ULE->getTemplateKeywordLoc(), 0, 1806 R.getLookupNameInfo(), 1807 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1808 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1809 } else { 1810 Diag(R.getNameLoc(), diagnostic) << Name; 1811 } 1812 1813 // Do we really want to note all of these? 1814 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1815 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1816 1817 // Return true if we are inside a default argument instantiation 1818 // and the found name refers to an instance member function, otherwise 1819 // the function calling DiagnoseEmptyLookup will try to create an 1820 // implicit member call and this is wrong for default argument. 1821 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1822 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1823 return true; 1824 } 1825 1826 // Tell the callee to try to recover. 1827 return false; 1828 } 1829 1830 R.clear(); 1831 } 1832 1833 // In Microsoft mode, if we are performing lookup from within a friend 1834 // function definition declared at class scope then we must set 1835 // DC to the lexical parent to be able to search into the parent 1836 // class. 1837 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1838 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1839 DC->getLexicalParent()->isRecord()) 1840 DC = DC->getLexicalParent(); 1841 else 1842 DC = DC->getParent(); 1843 } 1844 1845 // We didn't find anything, so try to correct for a typo. 1846 TypoCorrection Corrected; 1847 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1848 S, &SS, CCC))) { 1849 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1850 bool DroppedSpecifier = 1851 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1852 R.setLookupName(Corrected.getCorrection()); 1853 1854 bool AcceptableWithRecovery = false; 1855 bool AcceptableWithoutRecovery = false; 1856 NamedDecl *ND = Corrected.getCorrectionDecl(); 1857 if (ND) { 1858 if (Corrected.isOverloaded()) { 1859 OverloadCandidateSet OCS(R.getNameLoc()); 1860 OverloadCandidateSet::iterator Best; 1861 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1862 CDEnd = Corrected.end(); 1863 CD != CDEnd; ++CD) { 1864 if (FunctionTemplateDecl *FTD = 1865 dyn_cast<FunctionTemplateDecl>(*CD)) 1866 AddTemplateOverloadCandidate( 1867 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1868 Args, OCS); 1869 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1870 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1871 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1872 Args, OCS); 1873 } 1874 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1875 case OR_Success: 1876 ND = Best->Function; 1877 Corrected.setCorrectionDecl(ND); 1878 break; 1879 default: 1880 // FIXME: Arbitrarily pick the first declaration for the note. 1881 Corrected.setCorrectionDecl(ND); 1882 break; 1883 } 1884 } 1885 R.addDecl(ND); 1886 1887 AcceptableWithRecovery = 1888 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1889 // FIXME: If we ended up with a typo for a type name or 1890 // Objective-C class name, we're in trouble because the parser 1891 // is in the wrong place to recover. Suggest the typo 1892 // correction, but don't make it a fix-it since we're not going 1893 // to recover well anyway. 1894 AcceptableWithoutRecovery = 1895 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1896 } else { 1897 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1898 // because we aren't able to recover. 1899 AcceptableWithoutRecovery = true; 1900 } 1901 1902 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1903 unsigned NoteID = (Corrected.getCorrectionDecl() && 1904 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1905 ? diag::note_implicit_param_decl 1906 : diag::note_previous_decl; 1907 if (SS.isEmpty()) 1908 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1909 PDiag(NoteID), AcceptableWithRecovery); 1910 else 1911 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1912 << Name << computeDeclContext(SS, false) 1913 << DroppedSpecifier << SS.getRange(), 1914 PDiag(NoteID), AcceptableWithRecovery); 1915 1916 // Tell the callee whether to try to recover. 1917 return !AcceptableWithRecovery; 1918 } 1919 } 1920 R.clear(); 1921 1922 // Emit a special diagnostic for failed member lookups. 1923 // FIXME: computing the declaration context might fail here (?) 1924 if (!SS.isEmpty()) { 1925 Diag(R.getNameLoc(), diag::err_no_member) 1926 << Name << computeDeclContext(SS, false) 1927 << SS.getRange(); 1928 return true; 1929 } 1930 1931 // Give up, we can't recover. 1932 Diag(R.getNameLoc(), diagnostic) << Name; 1933 return true; 1934 } 1935 1936 ExprResult Sema::ActOnIdExpression(Scope *S, 1937 CXXScopeSpec &SS, 1938 SourceLocation TemplateKWLoc, 1939 UnqualifiedId &Id, 1940 bool HasTrailingLParen, 1941 bool IsAddressOfOperand, 1942 CorrectionCandidateCallback *CCC, 1943 bool IsInlineAsmIdentifier) { 1944 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1945 "cannot be direct & operand and have a trailing lparen"); 1946 if (SS.isInvalid()) 1947 return ExprError(); 1948 1949 TemplateArgumentListInfo TemplateArgsBuffer; 1950 1951 // Decompose the UnqualifiedId into the following data. 1952 DeclarationNameInfo NameInfo; 1953 const TemplateArgumentListInfo *TemplateArgs; 1954 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1955 1956 DeclarationName Name = NameInfo.getName(); 1957 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1958 SourceLocation NameLoc = NameInfo.getLoc(); 1959 1960 // C++ [temp.dep.expr]p3: 1961 // An id-expression is type-dependent if it contains: 1962 // -- an identifier that was declared with a dependent type, 1963 // (note: handled after lookup) 1964 // -- a template-id that is dependent, 1965 // (note: handled in BuildTemplateIdExpr) 1966 // -- a conversion-function-id that specifies a dependent type, 1967 // -- a nested-name-specifier that contains a class-name that 1968 // names a dependent type. 1969 // Determine whether this is a member of an unknown specialization; 1970 // we need to handle these differently. 1971 bool DependentID = false; 1972 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1973 Name.getCXXNameType()->isDependentType()) { 1974 DependentID = true; 1975 } else if (SS.isSet()) { 1976 if (DeclContext *DC = computeDeclContext(SS, false)) { 1977 if (RequireCompleteDeclContext(SS, DC)) 1978 return ExprError(); 1979 } else { 1980 DependentID = true; 1981 } 1982 } 1983 1984 if (DependentID) 1985 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1986 IsAddressOfOperand, TemplateArgs); 1987 1988 // Perform the required lookup. 1989 LookupResult R(*this, NameInfo, 1990 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1991 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1992 if (TemplateArgs) { 1993 // Lookup the template name again to correctly establish the context in 1994 // which it was found. This is really unfortunate as we already did the 1995 // lookup to determine that it was a template name in the first place. If 1996 // this becomes a performance hit, we can work harder to preserve those 1997 // results until we get here but it's likely not worth it. 1998 bool MemberOfUnknownSpecialization; 1999 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2000 MemberOfUnknownSpecialization); 2001 2002 if (MemberOfUnknownSpecialization || 2003 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2004 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2005 IsAddressOfOperand, TemplateArgs); 2006 } else { 2007 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2008 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2009 2010 // If the result might be in a dependent base class, this is a dependent 2011 // id-expression. 2012 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2013 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2014 IsAddressOfOperand, TemplateArgs); 2015 2016 // If this reference is in an Objective-C method, then we need to do 2017 // some special Objective-C lookup, too. 2018 if (IvarLookupFollowUp) { 2019 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2020 if (E.isInvalid()) 2021 return ExprError(); 2022 2023 if (Expr *Ex = E.takeAs<Expr>()) 2024 return Owned(Ex); 2025 } 2026 } 2027 2028 if (R.isAmbiguous()) 2029 return ExprError(); 2030 2031 // Determine whether this name might be a candidate for 2032 // argument-dependent lookup. 2033 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2034 2035 if (R.empty() && !ADL) { 2036 2037 // Otherwise, this could be an implicitly declared function reference (legal 2038 // in C90, extension in C99, forbidden in C++). 2039 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2040 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2041 if (D) R.addDecl(D); 2042 } 2043 2044 // If this name wasn't predeclared and if this is not a function 2045 // call, diagnose the problem. 2046 if (R.empty()) { 2047 // In Microsoft mode, if we are inside a template class member function 2048 // whose parent class has dependent base classes, and we can't resolve 2049 // an identifier, then assume the identifier is a member of a dependent 2050 // base class. The goal is to postpone name lookup to instantiation time 2051 // to be able to search into the type dependent base 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 (getLangOpts().MSVCCompat) { 2057 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 2058 if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) { 2059 assert(SS.isEmpty() && "qualifiers should be already handled"); 2060 QualType ThisType = MD->getThisType(Context); 2061 // Since the 'this' expression is synthesized, we don't need to 2062 // perform the double-lookup check. 2063 NamedDecl *FirstQualifierInScope = 0; 2064 return Owned(CXXDependentScopeMemberExpr::Create( 2065 Context, /*This=*/0, ThisType, /*IsArrow=*/true, 2066 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), 2067 TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs)); 2068 } 2069 } 2070 2071 // Don't diagnose an empty lookup for inline assmebly. 2072 if (IsInlineAsmIdentifier) 2073 return ExprError(); 2074 2075 CorrectionCandidateCallback DefaultValidator; 2076 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2077 return ExprError(); 2078 2079 assert(!R.empty() && 2080 "DiagnoseEmptyLookup returned false but added no results"); 2081 2082 // If we found an Objective-C instance variable, let 2083 // LookupInObjCMethod build the appropriate expression to 2084 // reference the ivar. 2085 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2086 R.clear(); 2087 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2088 // In a hopelessly buggy code, Objective-C instance variable 2089 // lookup fails and no expression will be built to reference it. 2090 if (!E.isInvalid() && !E.get()) 2091 return ExprError(); 2092 return E; 2093 } 2094 } 2095 } 2096 2097 // This is guaranteed from this point on. 2098 assert(!R.empty() || ADL); 2099 2100 // Check whether this might be a C++ implicit instance member access. 2101 // C++ [class.mfct.non-static]p3: 2102 // When an id-expression that is not part of a class member access 2103 // syntax and not used to form a pointer to member is used in the 2104 // body of a non-static member function of class X, if name lookup 2105 // resolves the name in the id-expression to a non-static non-type 2106 // member of some class C, the id-expression is transformed into a 2107 // class member access expression using (*this) as the 2108 // postfix-expression to the left of the . operator. 2109 // 2110 // But we don't actually need to do this for '&' operands if R 2111 // resolved to a function or overloaded function set, because the 2112 // expression is ill-formed if it actually works out to be a 2113 // non-static member function: 2114 // 2115 // C++ [expr.ref]p4: 2116 // Otherwise, if E1.E2 refers to a non-static member function. . . 2117 // [t]he expression can be used only as the left-hand operand of a 2118 // member function call. 2119 // 2120 // There are other safeguards against such uses, but it's important 2121 // to get this right here so that we don't end up making a 2122 // spuriously dependent expression if we're inside a dependent 2123 // instance method. 2124 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2125 bool MightBeImplicitMember; 2126 if (!IsAddressOfOperand) 2127 MightBeImplicitMember = true; 2128 else if (!SS.isEmpty()) 2129 MightBeImplicitMember = false; 2130 else if (R.isOverloadedResult()) 2131 MightBeImplicitMember = false; 2132 else if (R.isUnresolvableResult()) 2133 MightBeImplicitMember = true; 2134 else 2135 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2136 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2137 isa<MSPropertyDecl>(R.getFoundDecl()); 2138 2139 if (MightBeImplicitMember) 2140 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2141 R, TemplateArgs); 2142 } 2143 2144 if (TemplateArgs || TemplateKWLoc.isValid()) { 2145 2146 // In C++1y, if this is a variable template id, then check it 2147 // in BuildTemplateIdExpr(). 2148 // The single lookup result must be a variable template declaration. 2149 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2150 Id.TemplateId->Kind == TNK_Var_template) { 2151 assert(R.getAsSingle<VarTemplateDecl>() && 2152 "There should only be one declaration found."); 2153 } 2154 2155 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2156 } 2157 2158 return BuildDeclarationNameExpr(SS, R, ADL); 2159 } 2160 2161 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2162 /// declaration name, generally during template instantiation. 2163 /// There's a large number of things which don't need to be done along 2164 /// this path. 2165 ExprResult 2166 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2167 const DeclarationNameInfo &NameInfo, 2168 bool IsAddressOfOperand) { 2169 DeclContext *DC = computeDeclContext(SS, false); 2170 if (!DC) 2171 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2172 NameInfo, /*TemplateArgs=*/0); 2173 2174 if (RequireCompleteDeclContext(SS, DC)) 2175 return ExprError(); 2176 2177 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2178 LookupQualifiedName(R, DC); 2179 2180 if (R.isAmbiguous()) 2181 return ExprError(); 2182 2183 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2184 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2185 NameInfo, /*TemplateArgs=*/0); 2186 2187 if (R.empty()) { 2188 Diag(NameInfo.getLoc(), diag::err_no_member) 2189 << NameInfo.getName() << DC << SS.getRange(); 2190 return ExprError(); 2191 } 2192 2193 // Defend against this resolving to an implicit member access. We usually 2194 // won't get here if this might be a legitimate a class member (we end up in 2195 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2196 // a pointer-to-member or in an unevaluated context in C++11. 2197 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2198 return BuildPossibleImplicitMemberExpr(SS, 2199 /*TemplateKWLoc=*/SourceLocation(), 2200 R, /*TemplateArgs=*/0); 2201 2202 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2203 } 2204 2205 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2206 /// detected that we're currently inside an ObjC method. Perform some 2207 /// additional lookup. 2208 /// 2209 /// Ideally, most of this would be done by lookup, but there's 2210 /// actually quite a lot of extra work involved. 2211 /// 2212 /// Returns a null sentinel to indicate trivial success. 2213 ExprResult 2214 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2215 IdentifierInfo *II, bool AllowBuiltinCreation) { 2216 SourceLocation Loc = Lookup.getNameLoc(); 2217 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2218 2219 // Check for error condition which is already reported. 2220 if (!CurMethod) 2221 return ExprError(); 2222 2223 // There are two cases to handle here. 1) scoped lookup could have failed, 2224 // in which case we should look for an ivar. 2) scoped lookup could have 2225 // found a decl, but that decl is outside the current instance method (i.e. 2226 // a global variable). In these two cases, we do a lookup for an ivar with 2227 // this name, if the lookup sucedes, we replace it our current decl. 2228 2229 // If we're in a class method, we don't normally want to look for 2230 // ivars. But if we don't find anything else, and there's an 2231 // ivar, that's an error. 2232 bool IsClassMethod = CurMethod->isClassMethod(); 2233 2234 bool LookForIvars; 2235 if (Lookup.empty()) 2236 LookForIvars = true; 2237 else if (IsClassMethod) 2238 LookForIvars = false; 2239 else 2240 LookForIvars = (Lookup.isSingleResult() && 2241 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2242 ObjCInterfaceDecl *IFace = 0; 2243 if (LookForIvars) { 2244 IFace = CurMethod->getClassInterface(); 2245 ObjCInterfaceDecl *ClassDeclared; 2246 ObjCIvarDecl *IV = 0; 2247 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2248 // Diagnose using an ivar in a class method. 2249 if (IsClassMethod) 2250 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2251 << IV->getDeclName()); 2252 2253 // If we're referencing an invalid decl, just return this as a silent 2254 // error node. The error diagnostic was already emitted on the decl. 2255 if (IV->isInvalidDecl()) 2256 return ExprError(); 2257 2258 // Check if referencing a field with __attribute__((deprecated)). 2259 if (DiagnoseUseOfDecl(IV, Loc)) 2260 return ExprError(); 2261 2262 // Diagnose the use of an ivar outside of the declaring class. 2263 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2264 !declaresSameEntity(ClassDeclared, IFace) && 2265 !getLangOpts().DebuggerSupport) 2266 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2267 2268 // FIXME: This should use a new expr for a direct reference, don't 2269 // turn this into Self->ivar, just return a BareIVarExpr or something. 2270 IdentifierInfo &II = Context.Idents.get("self"); 2271 UnqualifiedId SelfName; 2272 SelfName.setIdentifier(&II, SourceLocation()); 2273 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2274 CXXScopeSpec SelfScopeSpec; 2275 SourceLocation TemplateKWLoc; 2276 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2277 SelfName, false, false); 2278 if (SelfExpr.isInvalid()) 2279 return ExprError(); 2280 2281 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2282 if (SelfExpr.isInvalid()) 2283 return ExprError(); 2284 2285 MarkAnyDeclReferenced(Loc, IV, true); 2286 2287 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2288 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2289 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2290 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2291 2292 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2293 Loc, IV->getLocation(), 2294 SelfExpr.take(), 2295 true, true); 2296 2297 if (getLangOpts().ObjCAutoRefCount) { 2298 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2299 DiagnosticsEngine::Level Level = 2300 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2301 if (Level != DiagnosticsEngine::Ignored) 2302 recordUseOfEvaluatedWeak(Result); 2303 } 2304 if (CurContext->isClosure()) 2305 Diag(Loc, diag::warn_implicitly_retains_self) 2306 << FixItHint::CreateInsertion(Loc, "self->"); 2307 } 2308 2309 return Owned(Result); 2310 } 2311 } else if (CurMethod->isInstanceMethod()) { 2312 // We should warn if a local variable hides an ivar. 2313 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2314 ObjCInterfaceDecl *ClassDeclared; 2315 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2316 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2317 declaresSameEntity(IFace, ClassDeclared)) 2318 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2319 } 2320 } 2321 } else if (Lookup.isSingleResult() && 2322 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2323 // If accessing a stand-alone ivar in a class method, this is an error. 2324 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2325 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2326 << IV->getDeclName()); 2327 } 2328 2329 if (Lookup.empty() && II && AllowBuiltinCreation) { 2330 // FIXME. Consolidate this with similar code in LookupName. 2331 if (unsigned BuiltinID = II->getBuiltinID()) { 2332 if (!(getLangOpts().CPlusPlus && 2333 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2334 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2335 S, Lookup.isForRedeclaration(), 2336 Lookup.getNameLoc()); 2337 if (D) Lookup.addDecl(D); 2338 } 2339 } 2340 } 2341 // Sentinel value saying that we didn't do anything special. 2342 return Owned((Expr*) 0); 2343 } 2344 2345 /// \brief Cast a base object to a member's actual type. 2346 /// 2347 /// Logically this happens in three phases: 2348 /// 2349 /// * First we cast from the base type to the naming class. 2350 /// The naming class is the class into which we were looking 2351 /// when we found the member; it's the qualifier type if a 2352 /// qualifier was provided, and otherwise it's the base type. 2353 /// 2354 /// * Next we cast from the naming class to the declaring class. 2355 /// If the member we found was brought into a class's scope by 2356 /// a using declaration, this is that class; otherwise it's 2357 /// the class declaring the member. 2358 /// 2359 /// * Finally we cast from the declaring class to the "true" 2360 /// declaring class of the member. This conversion does not 2361 /// obey access control. 2362 ExprResult 2363 Sema::PerformObjectMemberConversion(Expr *From, 2364 NestedNameSpecifier *Qualifier, 2365 NamedDecl *FoundDecl, 2366 NamedDecl *Member) { 2367 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2368 if (!RD) 2369 return Owned(From); 2370 2371 QualType DestRecordType; 2372 QualType DestType; 2373 QualType FromRecordType; 2374 QualType FromType = From->getType(); 2375 bool PointerConversions = false; 2376 if (isa<FieldDecl>(Member)) { 2377 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2378 2379 if (FromType->getAs<PointerType>()) { 2380 DestType = Context.getPointerType(DestRecordType); 2381 FromRecordType = FromType->getPointeeType(); 2382 PointerConversions = true; 2383 } else { 2384 DestType = DestRecordType; 2385 FromRecordType = FromType; 2386 } 2387 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2388 if (Method->isStatic()) 2389 return Owned(From); 2390 2391 DestType = Method->getThisType(Context); 2392 DestRecordType = DestType->getPointeeType(); 2393 2394 if (FromType->getAs<PointerType>()) { 2395 FromRecordType = FromType->getPointeeType(); 2396 PointerConversions = true; 2397 } else { 2398 FromRecordType = FromType; 2399 DestType = DestRecordType; 2400 } 2401 } else { 2402 // No conversion necessary. 2403 return Owned(From); 2404 } 2405 2406 if (DestType->isDependentType() || FromType->isDependentType()) 2407 return Owned(From); 2408 2409 // If the unqualified types are the same, no conversion is necessary. 2410 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2411 return Owned(From); 2412 2413 SourceRange FromRange = From->getSourceRange(); 2414 SourceLocation FromLoc = FromRange.getBegin(); 2415 2416 ExprValueKind VK = From->getValueKind(); 2417 2418 // C++ [class.member.lookup]p8: 2419 // [...] Ambiguities can often be resolved by qualifying a name with its 2420 // class name. 2421 // 2422 // If the member was a qualified name and the qualified referred to a 2423 // specific base subobject type, we'll cast to that intermediate type 2424 // first and then to the object in which the member is declared. That allows 2425 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2426 // 2427 // class Base { public: int x; }; 2428 // class Derived1 : public Base { }; 2429 // class Derived2 : public Base { }; 2430 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2431 // 2432 // void VeryDerived::f() { 2433 // x = 17; // error: ambiguous base subobjects 2434 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2435 // } 2436 if (Qualifier && Qualifier->getAsType()) { 2437 QualType QType = QualType(Qualifier->getAsType(), 0); 2438 assert(QType->isRecordType() && "lookup done with non-record type"); 2439 2440 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2441 2442 // In C++98, the qualifier type doesn't actually have to be a base 2443 // type of the object type, in which case we just ignore it. 2444 // Otherwise build the appropriate casts. 2445 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2446 CXXCastPath BasePath; 2447 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2448 FromLoc, FromRange, &BasePath)) 2449 return ExprError(); 2450 2451 if (PointerConversions) 2452 QType = Context.getPointerType(QType); 2453 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2454 VK, &BasePath).take(); 2455 2456 FromType = QType; 2457 FromRecordType = QRecordType; 2458 2459 // If the qualifier type was the same as the destination type, 2460 // we're done. 2461 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2462 return Owned(From); 2463 } 2464 } 2465 2466 bool IgnoreAccess = false; 2467 2468 // If we actually found the member through a using declaration, cast 2469 // down to the using declaration's type. 2470 // 2471 // Pointer equality is fine here because only one declaration of a 2472 // class ever has member declarations. 2473 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2474 assert(isa<UsingShadowDecl>(FoundDecl)); 2475 QualType URecordType = Context.getTypeDeclType( 2476 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2477 2478 // We only need to do this if the naming-class to declaring-class 2479 // conversion is non-trivial. 2480 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2481 assert(IsDerivedFrom(FromRecordType, URecordType)); 2482 CXXCastPath BasePath; 2483 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2484 FromLoc, FromRange, &BasePath)) 2485 return ExprError(); 2486 2487 QualType UType = URecordType; 2488 if (PointerConversions) 2489 UType = Context.getPointerType(UType); 2490 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2491 VK, &BasePath).take(); 2492 FromType = UType; 2493 FromRecordType = URecordType; 2494 } 2495 2496 // We don't do access control for the conversion from the 2497 // declaring class to the true declaring class. 2498 IgnoreAccess = true; 2499 } 2500 2501 CXXCastPath BasePath; 2502 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2503 FromLoc, FromRange, &BasePath, 2504 IgnoreAccess)) 2505 return ExprError(); 2506 2507 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2508 VK, &BasePath); 2509 } 2510 2511 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2512 const LookupResult &R, 2513 bool HasTrailingLParen) { 2514 // Only when used directly as the postfix-expression of a call. 2515 if (!HasTrailingLParen) 2516 return false; 2517 2518 // Never if a scope specifier was provided. 2519 if (SS.isSet()) 2520 return false; 2521 2522 // Only in C++ or ObjC++. 2523 if (!getLangOpts().CPlusPlus) 2524 return false; 2525 2526 // Turn off ADL when we find certain kinds of declarations during 2527 // normal lookup: 2528 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2529 NamedDecl *D = *I; 2530 2531 // C++0x [basic.lookup.argdep]p3: 2532 // -- a declaration of a class member 2533 // Since using decls preserve this property, we check this on the 2534 // original decl. 2535 if (D->isCXXClassMember()) 2536 return false; 2537 2538 // C++0x [basic.lookup.argdep]p3: 2539 // -- a block-scope function declaration that is not a 2540 // using-declaration 2541 // NOTE: we also trigger this for function templates (in fact, we 2542 // don't check the decl type at all, since all other decl types 2543 // turn off ADL anyway). 2544 if (isa<UsingShadowDecl>(D)) 2545 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2546 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2547 return false; 2548 2549 // C++0x [basic.lookup.argdep]p3: 2550 // -- a declaration that is neither a function or a function 2551 // template 2552 // And also for builtin functions. 2553 if (isa<FunctionDecl>(D)) { 2554 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2555 2556 // But also builtin functions. 2557 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2558 return false; 2559 } else if (!isa<FunctionTemplateDecl>(D)) 2560 return false; 2561 } 2562 2563 return true; 2564 } 2565 2566 2567 /// Diagnoses obvious problems with the use of the given declaration 2568 /// as an expression. This is only actually called for lookups that 2569 /// were not overloaded, and it doesn't promise that the declaration 2570 /// will in fact be used. 2571 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2572 if (isa<TypedefNameDecl>(D)) { 2573 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2574 return true; 2575 } 2576 2577 if (isa<ObjCInterfaceDecl>(D)) { 2578 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2579 return true; 2580 } 2581 2582 if (isa<NamespaceDecl>(D)) { 2583 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2584 return true; 2585 } 2586 2587 return false; 2588 } 2589 2590 ExprResult 2591 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2592 LookupResult &R, 2593 bool NeedsADL) { 2594 // If this is a single, fully-resolved result and we don't need ADL, 2595 // just build an ordinary singleton decl ref. 2596 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2597 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2598 R.getRepresentativeDecl()); 2599 2600 // We only need to check the declaration if there's exactly one 2601 // result, because in the overloaded case the results can only be 2602 // functions and function templates. 2603 if (R.isSingleResult() && 2604 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2605 return ExprError(); 2606 2607 // Otherwise, just build an unresolved lookup expression. Suppress 2608 // any lookup-related diagnostics; we'll hash these out later, when 2609 // we've picked a target. 2610 R.suppressDiagnostics(); 2611 2612 UnresolvedLookupExpr *ULE 2613 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2614 SS.getWithLocInContext(Context), 2615 R.getLookupNameInfo(), 2616 NeedsADL, R.isOverloadedResult(), 2617 R.begin(), R.end()); 2618 2619 return Owned(ULE); 2620 } 2621 2622 /// \brief Complete semantic analysis for a reference to the given declaration. 2623 ExprResult Sema::BuildDeclarationNameExpr( 2624 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2625 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2626 assert(D && "Cannot refer to a NULL declaration"); 2627 assert(!isa<FunctionTemplateDecl>(D) && 2628 "Cannot refer unambiguously to a function template"); 2629 2630 SourceLocation Loc = NameInfo.getLoc(); 2631 if (CheckDeclInExpr(*this, Loc, D)) 2632 return ExprError(); 2633 2634 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2635 // Specifically diagnose references to class templates that are missing 2636 // a template argument list. 2637 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2638 << Template << SS.getRange(); 2639 Diag(Template->getLocation(), diag::note_template_decl_here); 2640 return ExprError(); 2641 } 2642 2643 // Make sure that we're referring to a value. 2644 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2645 if (!VD) { 2646 Diag(Loc, diag::err_ref_non_value) 2647 << D << SS.getRange(); 2648 Diag(D->getLocation(), diag::note_declared_at); 2649 return ExprError(); 2650 } 2651 2652 // Check whether this declaration can be used. Note that we suppress 2653 // this check when we're going to perform argument-dependent lookup 2654 // on this function name, because this might not be the function 2655 // that overload resolution actually selects. 2656 if (DiagnoseUseOfDecl(VD, Loc)) 2657 return ExprError(); 2658 2659 // Only create DeclRefExpr's for valid Decl's. 2660 if (VD->isInvalidDecl()) 2661 return ExprError(); 2662 2663 // Handle members of anonymous structs and unions. If we got here, 2664 // and the reference is to a class member indirect field, then this 2665 // must be the subject of a pointer-to-member expression. 2666 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2667 if (!indirectField->isCXXClassMember()) 2668 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2669 indirectField); 2670 2671 { 2672 QualType type = VD->getType(); 2673 ExprValueKind valueKind = VK_RValue; 2674 2675 switch (D->getKind()) { 2676 // Ignore all the non-ValueDecl kinds. 2677 #define ABSTRACT_DECL(kind) 2678 #define VALUE(type, base) 2679 #define DECL(type, base) \ 2680 case Decl::type: 2681 #include "clang/AST/DeclNodes.inc" 2682 llvm_unreachable("invalid value decl kind"); 2683 2684 // These shouldn't make it here. 2685 case Decl::ObjCAtDefsField: 2686 case Decl::ObjCIvar: 2687 llvm_unreachable("forming non-member reference to ivar?"); 2688 2689 // Enum constants are always r-values and never references. 2690 // Unresolved using declarations are dependent. 2691 case Decl::EnumConstant: 2692 case Decl::UnresolvedUsingValue: 2693 valueKind = VK_RValue; 2694 break; 2695 2696 // Fields and indirect fields that got here must be for 2697 // pointer-to-member expressions; we just call them l-values for 2698 // internal consistency, because this subexpression doesn't really 2699 // exist in the high-level semantics. 2700 case Decl::Field: 2701 case Decl::IndirectField: 2702 assert(getLangOpts().CPlusPlus && 2703 "building reference to field in C?"); 2704 2705 // These can't have reference type in well-formed programs, but 2706 // for internal consistency we do this anyway. 2707 type = type.getNonReferenceType(); 2708 valueKind = VK_LValue; 2709 break; 2710 2711 // Non-type template parameters are either l-values or r-values 2712 // depending on the type. 2713 case Decl::NonTypeTemplateParm: { 2714 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2715 type = reftype->getPointeeType(); 2716 valueKind = VK_LValue; // even if the parameter is an r-value reference 2717 break; 2718 } 2719 2720 // For non-references, we need to strip qualifiers just in case 2721 // the template parameter was declared as 'const int' or whatever. 2722 valueKind = VK_RValue; 2723 type = type.getUnqualifiedType(); 2724 break; 2725 } 2726 2727 case Decl::Var: 2728 case Decl::VarTemplateSpecialization: 2729 case Decl::VarTemplatePartialSpecialization: 2730 // In C, "extern void blah;" is valid and is an r-value. 2731 if (!getLangOpts().CPlusPlus && 2732 !type.hasQualifiers() && 2733 type->isVoidType()) { 2734 valueKind = VK_RValue; 2735 break; 2736 } 2737 // fallthrough 2738 2739 case Decl::ImplicitParam: 2740 case Decl::ParmVar: { 2741 // These are always l-values. 2742 valueKind = VK_LValue; 2743 type = type.getNonReferenceType(); 2744 2745 // FIXME: Does the addition of const really only apply in 2746 // potentially-evaluated contexts? Since the variable isn't actually 2747 // captured in an unevaluated context, it seems that the answer is no. 2748 if (!isUnevaluatedContext()) { 2749 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2750 if (!CapturedType.isNull()) 2751 type = CapturedType; 2752 } 2753 2754 break; 2755 } 2756 2757 case Decl::Function: { 2758 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2759 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2760 type = Context.BuiltinFnTy; 2761 valueKind = VK_RValue; 2762 break; 2763 } 2764 } 2765 2766 const FunctionType *fty = type->castAs<FunctionType>(); 2767 2768 // If we're referring to a function with an __unknown_anytype 2769 // result type, make the entire expression __unknown_anytype. 2770 if (fty->getReturnType() == Context.UnknownAnyTy) { 2771 type = Context.UnknownAnyTy; 2772 valueKind = VK_RValue; 2773 break; 2774 } 2775 2776 // Functions are l-values in C++. 2777 if (getLangOpts().CPlusPlus) { 2778 valueKind = VK_LValue; 2779 break; 2780 } 2781 2782 // C99 DR 316 says that, if a function type comes from a 2783 // function definition (without a prototype), that type is only 2784 // used for checking compatibility. Therefore, when referencing 2785 // the function, we pretend that we don't have the full function 2786 // type. 2787 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2788 isa<FunctionProtoType>(fty)) 2789 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2790 fty->getExtInfo()); 2791 2792 // Functions are r-values in C. 2793 valueKind = VK_RValue; 2794 break; 2795 } 2796 2797 case Decl::MSProperty: 2798 valueKind = VK_LValue; 2799 break; 2800 2801 case Decl::CXXMethod: 2802 // If we're referring to a method with an __unknown_anytype 2803 // result type, make the entire expression __unknown_anytype. 2804 // This should only be possible with a type written directly. 2805 if (const FunctionProtoType *proto 2806 = dyn_cast<FunctionProtoType>(VD->getType())) 2807 if (proto->getReturnType() == Context.UnknownAnyTy) { 2808 type = Context.UnknownAnyTy; 2809 valueKind = VK_RValue; 2810 break; 2811 } 2812 2813 // C++ methods are l-values if static, r-values if non-static. 2814 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2815 valueKind = VK_LValue; 2816 break; 2817 } 2818 // fallthrough 2819 2820 case Decl::CXXConversion: 2821 case Decl::CXXDestructor: 2822 case Decl::CXXConstructor: 2823 valueKind = VK_RValue; 2824 break; 2825 } 2826 2827 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2828 TemplateArgs); 2829 } 2830 } 2831 2832 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2833 PredefinedExpr::IdentType IT) { 2834 // Pick the current block, lambda, captured statement or function. 2835 Decl *currentDecl = 0; 2836 if (const BlockScopeInfo *BSI = getCurBlock()) 2837 currentDecl = BSI->TheDecl; 2838 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2839 currentDecl = LSI->CallOperator; 2840 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2841 currentDecl = CSI->TheCapturedDecl; 2842 else 2843 currentDecl = getCurFunctionOrMethodDecl(); 2844 2845 if (!currentDecl) { 2846 Diag(Loc, diag::ext_predef_outside_function); 2847 currentDecl = Context.getTranslationUnitDecl(); 2848 } 2849 2850 QualType ResTy; 2851 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2852 ResTy = Context.DependentTy; 2853 else { 2854 // Pre-defined identifiers are of type char[x], where x is the length of 2855 // the string. 2856 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2857 2858 llvm::APInt LengthI(32, Length + 1); 2859 if (IT == PredefinedExpr::LFunction) 2860 ResTy = Context.WideCharTy.withConst(); 2861 else 2862 ResTy = Context.CharTy.withConst(); 2863 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2864 } 2865 2866 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2867 } 2868 2869 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2870 PredefinedExpr::IdentType IT; 2871 2872 switch (Kind) { 2873 default: llvm_unreachable("Unknown simple primary expr!"); 2874 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2875 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2876 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; 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::warn_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, bool HasExplicitTemplateArgs) 3980 : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs), 3981 FunctionName(FuncName) {} 3982 3983 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 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, 3998 DeclarationNameInfo FuncName, 3999 ArrayRef<Expr *> Args) { 4000 FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(), 4001 Args.size(), false); 4002 if (TypoCorrection Corrected = 4003 S.CorrectTypo(FuncName, Sema::LookupOrdinaryName, 4004 S.getScopeForContext(S.CurContext), NULL, CCC)) { 4005 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4006 if (Corrected.isOverloaded()) { 4007 OverloadCandidateSet OCS(FuncName.getLoc()); 4008 OverloadCandidateSet::iterator Best; 4009 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4010 CDEnd = Corrected.end(); 4011 CD != CDEnd; ++CD) { 4012 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4013 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4014 OCS); 4015 } 4016 switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) { 4017 case OR_Success: 4018 ND = Best->Function; 4019 Corrected.setCorrectionDecl(ND); 4020 break; 4021 default: 4022 break; 4023 } 4024 } 4025 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4026 return Corrected; 4027 } 4028 } 4029 } 4030 return TypoCorrection(); 4031 } 4032 4033 /// ConvertArgumentsForCall - Converts the arguments specified in 4034 /// Args/NumArgs to the parameter types of the function FDecl with 4035 /// function prototype Proto. Call is the call expression itself, and 4036 /// Fn is the function expression. For a C++ member function, this 4037 /// routine does not attempt to convert the object argument. Returns 4038 /// true if the call is ill-formed. 4039 bool 4040 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4041 FunctionDecl *FDecl, 4042 const FunctionProtoType *Proto, 4043 ArrayRef<Expr *> Args, 4044 SourceLocation RParenLoc, 4045 bool IsExecConfig) { 4046 // Bail out early if calling a builtin with custom typechecking. 4047 // We don't need to do this in the 4048 if (FDecl) 4049 if (unsigned ID = FDecl->getBuiltinID()) 4050 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4051 return false; 4052 4053 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4054 // assignment, to the types of the corresponding parameter, ... 4055 unsigned NumParams = Proto->getNumParams(); 4056 bool Invalid = false; 4057 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4058 unsigned FnKind = Fn->getType()->isBlockPointerType() 4059 ? 1 /* block */ 4060 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4061 : 0 /* function */); 4062 4063 // If too few arguments are available (and we don't have default 4064 // arguments for the remaining parameters), don't make the call. 4065 if (Args.size() < NumParams) { 4066 if (Args.size() < MinArgs) { 4067 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4068 TypoCorrection TC; 4069 if (FDecl && (TC = TryTypoCorrectionForCall( 4070 *this, DeclarationNameInfo(FDecl->getDeclName(), 4071 (ME ? ME->getMemberLoc() 4072 : Fn->getLocStart())), 4073 Args))) { 4074 unsigned diag_id = 4075 MinArgs == NumParams && !Proto->isVariadic() 4076 ? diag::err_typecheck_call_too_few_args_suggest 4077 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4078 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4079 << static_cast<unsigned>(Args.size()) 4080 << TC.getCorrectionRange()); 4081 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4082 Diag(RParenLoc, 4083 MinArgs == NumParams && !Proto->isVariadic() 4084 ? diag::err_typecheck_call_too_few_args_one 4085 : diag::err_typecheck_call_too_few_args_at_least_one) 4086 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4087 else 4088 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4089 ? diag::err_typecheck_call_too_few_args 4090 : diag::err_typecheck_call_too_few_args_at_least) 4091 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4092 << Fn->getSourceRange(); 4093 4094 // Emit the location of the prototype. 4095 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4096 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4097 << FDecl; 4098 4099 return true; 4100 } 4101 Call->setNumArgs(Context, NumParams); 4102 } 4103 4104 // If too many are passed and not variadic, error on the extras and drop 4105 // them. 4106 if (Args.size() > NumParams) { 4107 if (!Proto->isVariadic()) { 4108 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4109 TypoCorrection TC; 4110 if (FDecl && (TC = TryTypoCorrectionForCall( 4111 *this, DeclarationNameInfo(FDecl->getDeclName(), 4112 (ME ? ME->getMemberLoc() 4113 : Fn->getLocStart())), 4114 Args))) { 4115 unsigned diag_id = 4116 MinArgs == NumParams && !Proto->isVariadic() 4117 ? diag::err_typecheck_call_too_many_args_suggest 4118 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4119 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4120 << static_cast<unsigned>(Args.size()) 4121 << TC.getCorrectionRange()); 4122 } else if (NumParams == 1 && FDecl && 4123 FDecl->getParamDecl(0)->getDeclName()) 4124 Diag(Args[NumParams]->getLocStart(), 4125 MinArgs == NumParams 4126 ? diag::err_typecheck_call_too_many_args_one 4127 : diag::err_typecheck_call_too_many_args_at_most_one) 4128 << FnKind << FDecl->getParamDecl(0) 4129 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4130 << SourceRange(Args[NumParams]->getLocStart(), 4131 Args.back()->getLocEnd()); 4132 else 4133 Diag(Args[NumParams]->getLocStart(), 4134 MinArgs == NumParams 4135 ? diag::err_typecheck_call_too_many_args 4136 : diag::err_typecheck_call_too_many_args_at_most) 4137 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4138 << Fn->getSourceRange() 4139 << SourceRange(Args[NumParams]->getLocStart(), 4140 Args.back()->getLocEnd()); 4141 4142 // Emit the location of the prototype. 4143 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4144 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4145 << FDecl; 4146 4147 // This deletes the extra arguments. 4148 Call->setNumArgs(Context, NumParams); 4149 return true; 4150 } 4151 } 4152 SmallVector<Expr *, 8> AllArgs; 4153 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4154 4155 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4156 Proto, 0, Args, AllArgs, CallType); 4157 if (Invalid) 4158 return true; 4159 unsigned TotalNumArgs = AllArgs.size(); 4160 for (unsigned i = 0; i < TotalNumArgs; ++i) 4161 Call->setArg(i, AllArgs[i]); 4162 4163 return false; 4164 } 4165 4166 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4167 const FunctionProtoType *Proto, 4168 unsigned FirstParam, ArrayRef<Expr *> Args, 4169 SmallVectorImpl<Expr *> &AllArgs, 4170 VariadicCallType CallType, bool AllowExplicit, 4171 bool IsListInitialization) { 4172 unsigned NumParams = Proto->getNumParams(); 4173 unsigned NumArgsToCheck = Args.size(); 4174 bool Invalid = false; 4175 if (Args.size() != NumParams) 4176 // Use default arguments for missing arguments 4177 NumArgsToCheck = NumParams; 4178 unsigned ArgIx = 0; 4179 // Continue to check argument types (even if we have too few/many args). 4180 for (unsigned i = FirstParam; i != NumArgsToCheck; i++) { 4181 QualType ProtoArgType = Proto->getParamType(i); 4182 4183 Expr *Arg; 4184 ParmVarDecl *Param; 4185 if (ArgIx < Args.size()) { 4186 Arg = Args[ArgIx++]; 4187 4188 if (RequireCompleteType(Arg->getLocStart(), 4189 ProtoArgType, 4190 diag::err_call_incomplete_argument, Arg)) 4191 return true; 4192 4193 // Pass the argument 4194 Param = 0; 4195 if (FDecl && i < FDecl->getNumParams()) 4196 Param = FDecl->getParamDecl(i); 4197 4198 // Strip the unbridged-cast placeholder expression off, if applicable. 4199 bool CFAudited = false; 4200 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4201 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4202 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4203 Arg = stripARCUnbridgedCast(Arg); 4204 else if (getLangOpts().ObjCAutoRefCount && 4205 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4206 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4207 CFAudited = true; 4208 4209 InitializedEntity Entity = 4210 Param ? InitializedEntity::InitializeParameter(Context, Param, 4211 ProtoArgType) 4212 : InitializedEntity::InitializeParameter( 4213 Context, ProtoArgType, Proto->isParamConsumed(i)); 4214 4215 // Remember that parameter belongs to a CF audited API. 4216 if (CFAudited) 4217 Entity.setParameterCFAudited(); 4218 4219 ExprResult ArgE = PerformCopyInitialization(Entity, 4220 SourceLocation(), 4221 Owned(Arg), 4222 IsListInitialization, 4223 AllowExplicit); 4224 if (ArgE.isInvalid()) 4225 return true; 4226 4227 Arg = ArgE.takeAs<Expr>(); 4228 } else { 4229 assert(FDecl && "can't use default arguments without a known callee"); 4230 Param = FDecl->getParamDecl(i); 4231 4232 ExprResult ArgExpr = 4233 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4234 if (ArgExpr.isInvalid()) 4235 return true; 4236 4237 Arg = ArgExpr.takeAs<Expr>(); 4238 } 4239 4240 // Check for array bounds violations for each argument to the call. This 4241 // check only triggers warnings when the argument isn't a more complex Expr 4242 // with its own checking, such as a BinaryOperator. 4243 CheckArrayAccess(Arg); 4244 4245 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4246 CheckStaticArrayArgument(CallLoc, Param, Arg); 4247 4248 AllArgs.push_back(Arg); 4249 } 4250 4251 // If this is a variadic call, handle args passed through "...". 4252 if (CallType != VariadicDoesNotApply) { 4253 // Assume that extern "C" functions with variadic arguments that 4254 // return __unknown_anytype aren't *really* variadic. 4255 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4256 FDecl->isExternC()) { 4257 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4258 QualType paramType; // ignored 4259 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4260 Invalid |= arg.isInvalid(); 4261 AllArgs.push_back(arg.take()); 4262 } 4263 4264 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4265 } else { 4266 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4267 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4268 FDecl); 4269 Invalid |= Arg.isInvalid(); 4270 AllArgs.push_back(Arg.take()); 4271 } 4272 } 4273 4274 // Check for array bounds violations. 4275 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4276 CheckArrayAccess(Args[i]); 4277 } 4278 return Invalid; 4279 } 4280 4281 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4282 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4283 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4284 TL = DTL.getOriginalLoc(); 4285 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4286 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4287 << ATL.getLocalSourceRange(); 4288 } 4289 4290 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4291 /// array parameter, check that it is non-null, and that if it is formed by 4292 /// array-to-pointer decay, the underlying array is sufficiently large. 4293 /// 4294 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4295 /// array type derivation, then for each call to the function, the value of the 4296 /// corresponding actual argument shall provide access to the first element of 4297 /// an array with at least as many elements as specified by the size expression. 4298 void 4299 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4300 ParmVarDecl *Param, 4301 const Expr *ArgExpr) { 4302 // Static array parameters are not supported in C++. 4303 if (!Param || getLangOpts().CPlusPlus) 4304 return; 4305 4306 QualType OrigTy = Param->getOriginalType(); 4307 4308 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4309 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4310 return; 4311 4312 if (ArgExpr->isNullPointerConstant(Context, 4313 Expr::NPC_NeverValueDependent)) { 4314 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4315 DiagnoseCalleeStaticArrayParam(*this, Param); 4316 return; 4317 } 4318 4319 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4320 if (!CAT) 4321 return; 4322 4323 const ConstantArrayType *ArgCAT = 4324 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4325 if (!ArgCAT) 4326 return; 4327 4328 if (ArgCAT->getSize().ult(CAT->getSize())) { 4329 Diag(CallLoc, diag::warn_static_array_too_small) 4330 << ArgExpr->getSourceRange() 4331 << (unsigned) ArgCAT->getSize().getZExtValue() 4332 << (unsigned) CAT->getSize().getZExtValue(); 4333 DiagnoseCalleeStaticArrayParam(*this, Param); 4334 } 4335 } 4336 4337 /// Given a function expression of unknown-any type, try to rebuild it 4338 /// to have a function type. 4339 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4340 4341 /// Is the given type a placeholder that we need to lower out 4342 /// immediately during argument processing? 4343 static bool isPlaceholderToRemoveAsArg(QualType type) { 4344 // Placeholders are never sugared. 4345 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4346 if (!placeholder) return false; 4347 4348 switch (placeholder->getKind()) { 4349 // Ignore all the non-placeholder types. 4350 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4351 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4352 #include "clang/AST/BuiltinTypes.def" 4353 return false; 4354 4355 // We cannot lower out overload sets; they might validly be resolved 4356 // by the call machinery. 4357 case BuiltinType::Overload: 4358 return false; 4359 4360 // Unbridged casts in ARC can be handled in some call positions and 4361 // should be left in place. 4362 case BuiltinType::ARCUnbridgedCast: 4363 return false; 4364 4365 // Pseudo-objects should be converted as soon as possible. 4366 case BuiltinType::PseudoObject: 4367 return true; 4368 4369 // The debugger mode could theoretically but currently does not try 4370 // to resolve unknown-typed arguments based on known parameter types. 4371 case BuiltinType::UnknownAny: 4372 return true; 4373 4374 // These are always invalid as call arguments and should be reported. 4375 case BuiltinType::BoundMember: 4376 case BuiltinType::BuiltinFn: 4377 return true; 4378 } 4379 llvm_unreachable("bad builtin type kind"); 4380 } 4381 4382 /// Check an argument list for placeholders that we won't try to 4383 /// handle later. 4384 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4385 // Apply this processing to all the arguments at once instead of 4386 // dying at the first failure. 4387 bool hasInvalid = false; 4388 for (size_t i = 0, e = args.size(); i != e; i++) { 4389 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4390 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4391 if (result.isInvalid()) hasInvalid = true; 4392 else args[i] = result.take(); 4393 } 4394 } 4395 return hasInvalid; 4396 } 4397 4398 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4399 /// This provides the location of the left/right parens and a list of comma 4400 /// locations. 4401 ExprResult 4402 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4403 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4404 Expr *ExecConfig, bool IsExecConfig) { 4405 // Since this might be a postfix expression, get rid of ParenListExprs. 4406 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4407 if (Result.isInvalid()) return ExprError(); 4408 Fn = Result.take(); 4409 4410 if (checkArgsForPlaceholders(*this, ArgExprs)) 4411 return ExprError(); 4412 4413 if (getLangOpts().CPlusPlus) { 4414 // If this is a pseudo-destructor expression, build the call immediately. 4415 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4416 if (!ArgExprs.empty()) { 4417 // Pseudo-destructor calls should not have any arguments. 4418 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4419 << FixItHint::CreateRemoval( 4420 SourceRange(ArgExprs[0]->getLocStart(), 4421 ArgExprs.back()->getLocEnd())); 4422 } 4423 4424 return Owned(new (Context) CallExpr(Context, Fn, None, 4425 Context.VoidTy, VK_RValue, 4426 RParenLoc)); 4427 } 4428 if (Fn->getType() == Context.PseudoObjectTy) { 4429 ExprResult result = CheckPlaceholderExpr(Fn); 4430 if (result.isInvalid()) return ExprError(); 4431 Fn = result.take(); 4432 } 4433 4434 // Determine whether this is a dependent call inside a C++ template, 4435 // in which case we won't do any semantic analysis now. 4436 // FIXME: Will need to cache the results of name lookup (including ADL) in 4437 // Fn. 4438 bool Dependent = false; 4439 if (Fn->isTypeDependent()) 4440 Dependent = true; 4441 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4442 Dependent = true; 4443 4444 if (Dependent) { 4445 if (ExecConfig) { 4446 return Owned(new (Context) CUDAKernelCallExpr( 4447 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4448 Context.DependentTy, VK_RValue, RParenLoc)); 4449 } else { 4450 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4451 Context.DependentTy, VK_RValue, 4452 RParenLoc)); 4453 } 4454 } 4455 4456 // Determine whether this is a call to an object (C++ [over.call.object]). 4457 if (Fn->getType()->isRecordType()) 4458 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4459 ArgExprs, RParenLoc)); 4460 4461 if (Fn->getType() == Context.UnknownAnyTy) { 4462 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4463 if (result.isInvalid()) return ExprError(); 4464 Fn = result.take(); 4465 } 4466 4467 if (Fn->getType() == Context.BoundMemberTy) { 4468 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4469 } 4470 } 4471 4472 // Check for overloaded calls. This can happen even in C due to extensions. 4473 if (Fn->getType() == Context.OverloadTy) { 4474 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4475 4476 // We aren't supposed to apply this logic for if there's an '&' involved. 4477 if (!find.HasFormOfMemberPointer) { 4478 OverloadExpr *ovl = find.Expression; 4479 if (isa<UnresolvedLookupExpr>(ovl)) { 4480 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4481 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4482 RParenLoc, ExecConfig); 4483 } else { 4484 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4485 RParenLoc); 4486 } 4487 } 4488 } 4489 4490 // If we're directly calling a function, get the appropriate declaration. 4491 if (Fn->getType() == Context.UnknownAnyTy) { 4492 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4493 if (result.isInvalid()) return ExprError(); 4494 Fn = result.take(); 4495 } 4496 4497 Expr *NakedFn = Fn->IgnoreParens(); 4498 4499 NamedDecl *NDecl = 0; 4500 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4501 if (UnOp->getOpcode() == UO_AddrOf) 4502 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4503 4504 if (isa<DeclRefExpr>(NakedFn)) 4505 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4506 else if (isa<MemberExpr>(NakedFn)) 4507 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4508 4509 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4510 if (FD->hasAttr<EnableIfAttr>()) { 4511 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4512 Diag(Fn->getLocStart(), 4513 isa<CXXMethodDecl>(FD) ? 4514 diag::err_ovl_no_viable_member_function_in_call : 4515 diag::err_ovl_no_viable_function_in_call) 4516 << FD << FD->getSourceRange(); 4517 Diag(FD->getLocation(), 4518 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4519 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4520 } 4521 } 4522 } 4523 4524 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4525 ExecConfig, IsExecConfig); 4526 } 4527 4528 ExprResult 4529 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4530 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4531 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4532 if (!ConfigDecl) 4533 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4534 << "cudaConfigureCall"); 4535 QualType ConfigQTy = ConfigDecl->getType(); 4536 4537 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4538 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4539 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4540 4541 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4542 /*IsExecConfig=*/true); 4543 } 4544 4545 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4546 /// 4547 /// __builtin_astype( value, dst type ) 4548 /// 4549 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4550 SourceLocation BuiltinLoc, 4551 SourceLocation RParenLoc) { 4552 ExprValueKind VK = VK_RValue; 4553 ExprObjectKind OK = OK_Ordinary; 4554 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4555 QualType SrcTy = E->getType(); 4556 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4557 return ExprError(Diag(BuiltinLoc, 4558 diag::err_invalid_astype_of_different_size) 4559 << DstTy 4560 << SrcTy 4561 << E->getSourceRange()); 4562 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4563 RParenLoc)); 4564 } 4565 4566 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4567 /// provided arguments. 4568 /// 4569 /// __builtin_convertvector( value, dst type ) 4570 /// 4571 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4572 SourceLocation BuiltinLoc, 4573 SourceLocation RParenLoc) { 4574 TypeSourceInfo *TInfo; 4575 GetTypeFromParser(ParsedDestTy, &TInfo); 4576 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4577 } 4578 4579 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4580 /// i.e. an expression not of \p OverloadTy. The expression should 4581 /// unary-convert to an expression of function-pointer or 4582 /// block-pointer type. 4583 /// 4584 /// \param NDecl the declaration being called, if available 4585 ExprResult 4586 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4587 SourceLocation LParenLoc, 4588 ArrayRef<Expr *> Args, 4589 SourceLocation RParenLoc, 4590 Expr *Config, bool IsExecConfig) { 4591 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4592 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4593 4594 // Promote the function operand. 4595 // We special-case function promotion here because we only allow promoting 4596 // builtin functions to function pointers in the callee of a call. 4597 ExprResult Result; 4598 if (BuiltinID && 4599 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4600 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4601 CK_BuiltinFnToFnPtr).take(); 4602 } else { 4603 Result = CallExprUnaryConversions(Fn); 4604 } 4605 if (Result.isInvalid()) 4606 return ExprError(); 4607 Fn = Result.take(); 4608 4609 // Make the call expr early, before semantic checks. This guarantees cleanup 4610 // of arguments and function on error. 4611 CallExpr *TheCall; 4612 if (Config) 4613 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4614 cast<CallExpr>(Config), Args, 4615 Context.BoolTy, VK_RValue, 4616 RParenLoc); 4617 else 4618 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4619 VK_RValue, RParenLoc); 4620 4621 // Bail out early if calling a builtin with custom typechecking. 4622 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4623 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4624 4625 retry: 4626 const FunctionType *FuncT; 4627 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4628 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4629 // have type pointer to function". 4630 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4631 if (FuncT == 0) 4632 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4633 << Fn->getType() << Fn->getSourceRange()); 4634 } else if (const BlockPointerType *BPT = 4635 Fn->getType()->getAs<BlockPointerType>()) { 4636 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4637 } else { 4638 // Handle calls to expressions of unknown-any type. 4639 if (Fn->getType() == Context.UnknownAnyTy) { 4640 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4641 if (rewrite.isInvalid()) return ExprError(); 4642 Fn = rewrite.take(); 4643 TheCall->setCallee(Fn); 4644 goto retry; 4645 } 4646 4647 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4648 << Fn->getType() << Fn->getSourceRange()); 4649 } 4650 4651 if (getLangOpts().CUDA) { 4652 if (Config) { 4653 // CUDA: Kernel calls must be to global functions 4654 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4655 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4656 << FDecl->getName() << Fn->getSourceRange()); 4657 4658 // CUDA: Kernel function must have 'void' return type 4659 if (!FuncT->getReturnType()->isVoidType()) 4660 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4661 << Fn->getType() << Fn->getSourceRange()); 4662 } else { 4663 // CUDA: Calls to global functions must be configured 4664 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4665 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4666 << FDecl->getName() << Fn->getSourceRange()); 4667 } 4668 } 4669 4670 // Check for a valid return type 4671 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 4672 FDecl)) 4673 return ExprError(); 4674 4675 // We know the result type of the call, set it. 4676 TheCall->setType(FuncT->getCallResultType(Context)); 4677 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 4678 4679 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4680 if (Proto) { 4681 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4682 IsExecConfig)) 4683 return ExprError(); 4684 } else { 4685 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4686 4687 if (FDecl) { 4688 // Check if we have too few/too many template arguments, based 4689 // on our knowledge of the function definition. 4690 const FunctionDecl *Def = 0; 4691 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4692 Proto = Def->getType()->getAs<FunctionProtoType>(); 4693 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4694 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4695 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4696 } 4697 4698 // If the function we're calling isn't a function prototype, but we have 4699 // a function prototype from a prior declaratiom, use that prototype. 4700 if (!FDecl->hasPrototype()) 4701 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4702 } 4703 4704 // Promote the arguments (C99 6.5.2.2p6). 4705 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4706 Expr *Arg = Args[i]; 4707 4708 if (Proto && i < Proto->getNumParams()) { 4709 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4710 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 4711 ExprResult ArgE = PerformCopyInitialization(Entity, 4712 SourceLocation(), 4713 Owned(Arg)); 4714 if (ArgE.isInvalid()) 4715 return true; 4716 4717 Arg = ArgE.takeAs<Expr>(); 4718 4719 } else { 4720 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4721 4722 if (ArgE.isInvalid()) 4723 return true; 4724 4725 Arg = ArgE.takeAs<Expr>(); 4726 } 4727 4728 if (RequireCompleteType(Arg->getLocStart(), 4729 Arg->getType(), 4730 diag::err_call_incomplete_argument, Arg)) 4731 return ExprError(); 4732 4733 TheCall->setArg(i, Arg); 4734 } 4735 } 4736 4737 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4738 if (!Method->isStatic()) 4739 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4740 << Fn->getSourceRange()); 4741 4742 // Check for sentinels 4743 if (NDecl) 4744 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4745 4746 // Do special checking on direct calls to functions. 4747 if (FDecl) { 4748 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4749 return ExprError(); 4750 4751 if (BuiltinID) 4752 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4753 } else if (NDecl) { 4754 if (CheckPointerCall(NDecl, TheCall, Proto)) 4755 return ExprError(); 4756 } else { 4757 if (CheckOtherCall(TheCall, Proto)) 4758 return ExprError(); 4759 } 4760 4761 return MaybeBindToTemporary(TheCall); 4762 } 4763 4764 ExprResult 4765 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4766 SourceLocation RParenLoc, Expr *InitExpr) { 4767 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4768 // FIXME: put back this assert when initializers are worked out. 4769 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4770 4771 TypeSourceInfo *TInfo; 4772 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4773 if (!TInfo) 4774 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4775 4776 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4777 } 4778 4779 ExprResult 4780 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4781 SourceLocation RParenLoc, Expr *LiteralExpr) { 4782 QualType literalType = TInfo->getType(); 4783 4784 if (literalType->isArrayType()) { 4785 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4786 diag::err_illegal_decl_array_incomplete_type, 4787 SourceRange(LParenLoc, 4788 LiteralExpr->getSourceRange().getEnd()))) 4789 return ExprError(); 4790 if (literalType->isVariableArrayType()) 4791 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4792 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4793 } else if (!literalType->isDependentType() && 4794 RequireCompleteType(LParenLoc, literalType, 4795 diag::err_typecheck_decl_incomplete_type, 4796 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4797 return ExprError(); 4798 4799 InitializedEntity Entity 4800 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4801 InitializationKind Kind 4802 = InitializationKind::CreateCStyleCast(LParenLoc, 4803 SourceRange(LParenLoc, RParenLoc), 4804 /*InitList=*/true); 4805 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4806 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4807 &literalType); 4808 if (Result.isInvalid()) 4809 return ExprError(); 4810 LiteralExpr = Result.get(); 4811 4812 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4813 if (isFileScope && 4814 !LiteralExpr->isTypeDependent() && 4815 !LiteralExpr->isValueDependent() && 4816 !literalType->isDependentType()) { // 6.5.2.5p3 4817 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4818 return ExprError(); 4819 } 4820 4821 // In C, compound literals are l-values for some reason. 4822 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4823 4824 return MaybeBindToTemporary( 4825 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4826 VK, LiteralExpr, isFileScope)); 4827 } 4828 4829 ExprResult 4830 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4831 SourceLocation RBraceLoc) { 4832 // Immediately handle non-overload placeholders. Overloads can be 4833 // resolved contextually, but everything else here can't. 4834 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4835 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4836 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4837 4838 // Ignore failures; dropping the entire initializer list because 4839 // of one failure would be terrible for indexing/etc. 4840 if (result.isInvalid()) continue; 4841 4842 InitArgList[I] = result.take(); 4843 } 4844 } 4845 4846 // Semantic analysis for initializers is done by ActOnDeclarator() and 4847 // CheckInitializer() - it requires knowledge of the object being intialized. 4848 4849 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4850 RBraceLoc); 4851 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4852 return Owned(E); 4853 } 4854 4855 /// Do an explicit extend of the given block pointer if we're in ARC. 4856 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4857 assert(E.get()->getType()->isBlockPointerType()); 4858 assert(E.get()->isRValue()); 4859 4860 // Only do this in an r-value context. 4861 if (!S.getLangOpts().ObjCAutoRefCount) return; 4862 4863 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4864 CK_ARCExtendBlockObject, E.get(), 4865 /*base path*/ 0, VK_RValue); 4866 S.ExprNeedsCleanups = true; 4867 } 4868 4869 /// Prepare a conversion of the given expression to an ObjC object 4870 /// pointer type. 4871 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4872 QualType type = E.get()->getType(); 4873 if (type->isObjCObjectPointerType()) { 4874 return CK_BitCast; 4875 } else if (type->isBlockPointerType()) { 4876 maybeExtendBlockObject(*this, E); 4877 return CK_BlockPointerToObjCPointerCast; 4878 } else { 4879 assert(type->isPointerType()); 4880 return CK_CPointerToObjCPointerCast; 4881 } 4882 } 4883 4884 /// Prepares for a scalar cast, performing all the necessary stages 4885 /// except the final cast and returning the kind required. 4886 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4887 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4888 // Also, callers should have filtered out the invalid cases with 4889 // pointers. Everything else should be possible. 4890 4891 QualType SrcTy = Src.get()->getType(); 4892 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4893 return CK_NoOp; 4894 4895 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4896 case Type::STK_MemberPointer: 4897 llvm_unreachable("member pointer type in C"); 4898 4899 case Type::STK_CPointer: 4900 case Type::STK_BlockPointer: 4901 case Type::STK_ObjCObjectPointer: 4902 switch (DestTy->getScalarTypeKind()) { 4903 case Type::STK_CPointer: { 4904 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 4905 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 4906 if (SrcAS != DestAS) 4907 return CK_AddressSpaceConversion; 4908 return CK_BitCast; 4909 } 4910 case Type::STK_BlockPointer: 4911 return (SrcKind == Type::STK_BlockPointer 4912 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4913 case Type::STK_ObjCObjectPointer: 4914 if (SrcKind == Type::STK_ObjCObjectPointer) 4915 return CK_BitCast; 4916 if (SrcKind == Type::STK_CPointer) 4917 return CK_CPointerToObjCPointerCast; 4918 maybeExtendBlockObject(*this, Src); 4919 return CK_BlockPointerToObjCPointerCast; 4920 case Type::STK_Bool: 4921 return CK_PointerToBoolean; 4922 case Type::STK_Integral: 4923 return CK_PointerToIntegral; 4924 case Type::STK_Floating: 4925 case Type::STK_FloatingComplex: 4926 case Type::STK_IntegralComplex: 4927 case Type::STK_MemberPointer: 4928 llvm_unreachable("illegal cast from pointer"); 4929 } 4930 llvm_unreachable("Should have returned before this"); 4931 4932 case Type::STK_Bool: // casting from bool is like casting from an integer 4933 case Type::STK_Integral: 4934 switch (DestTy->getScalarTypeKind()) { 4935 case Type::STK_CPointer: 4936 case Type::STK_ObjCObjectPointer: 4937 case Type::STK_BlockPointer: 4938 if (Src.get()->isNullPointerConstant(Context, 4939 Expr::NPC_ValueDependentIsNull)) 4940 return CK_NullToPointer; 4941 return CK_IntegralToPointer; 4942 case Type::STK_Bool: 4943 return CK_IntegralToBoolean; 4944 case Type::STK_Integral: 4945 return CK_IntegralCast; 4946 case Type::STK_Floating: 4947 return CK_IntegralToFloating; 4948 case Type::STK_IntegralComplex: 4949 Src = ImpCastExprToType(Src.take(), 4950 DestTy->castAs<ComplexType>()->getElementType(), 4951 CK_IntegralCast); 4952 return CK_IntegralRealToComplex; 4953 case Type::STK_FloatingComplex: 4954 Src = ImpCastExprToType(Src.take(), 4955 DestTy->castAs<ComplexType>()->getElementType(), 4956 CK_IntegralToFloating); 4957 return CK_FloatingRealToComplex; 4958 case Type::STK_MemberPointer: 4959 llvm_unreachable("member pointer type in C"); 4960 } 4961 llvm_unreachable("Should have returned before this"); 4962 4963 case Type::STK_Floating: 4964 switch (DestTy->getScalarTypeKind()) { 4965 case Type::STK_Floating: 4966 return CK_FloatingCast; 4967 case Type::STK_Bool: 4968 return CK_FloatingToBoolean; 4969 case Type::STK_Integral: 4970 return CK_FloatingToIntegral; 4971 case Type::STK_FloatingComplex: 4972 Src = ImpCastExprToType(Src.take(), 4973 DestTy->castAs<ComplexType>()->getElementType(), 4974 CK_FloatingCast); 4975 return CK_FloatingRealToComplex; 4976 case Type::STK_IntegralComplex: 4977 Src = ImpCastExprToType(Src.take(), 4978 DestTy->castAs<ComplexType>()->getElementType(), 4979 CK_FloatingToIntegral); 4980 return CK_IntegralRealToComplex; 4981 case Type::STK_CPointer: 4982 case Type::STK_ObjCObjectPointer: 4983 case Type::STK_BlockPointer: 4984 llvm_unreachable("valid float->pointer cast?"); 4985 case Type::STK_MemberPointer: 4986 llvm_unreachable("member pointer type in C"); 4987 } 4988 llvm_unreachable("Should have returned before this"); 4989 4990 case Type::STK_FloatingComplex: 4991 switch (DestTy->getScalarTypeKind()) { 4992 case Type::STK_FloatingComplex: 4993 return CK_FloatingComplexCast; 4994 case Type::STK_IntegralComplex: 4995 return CK_FloatingComplexToIntegralComplex; 4996 case Type::STK_Floating: { 4997 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4998 if (Context.hasSameType(ET, DestTy)) 4999 return CK_FloatingComplexToReal; 5000 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 5001 return CK_FloatingCast; 5002 } 5003 case Type::STK_Bool: 5004 return CK_FloatingComplexToBoolean; 5005 case Type::STK_Integral: 5006 Src = ImpCastExprToType(Src.take(), 5007 SrcTy->castAs<ComplexType>()->getElementType(), 5008 CK_FloatingComplexToReal); 5009 return CK_FloatingToIntegral; 5010 case Type::STK_CPointer: 5011 case Type::STK_ObjCObjectPointer: 5012 case Type::STK_BlockPointer: 5013 llvm_unreachable("valid complex float->pointer cast?"); 5014 case Type::STK_MemberPointer: 5015 llvm_unreachable("member pointer type in C"); 5016 } 5017 llvm_unreachable("Should have returned before this"); 5018 5019 case Type::STK_IntegralComplex: 5020 switch (DestTy->getScalarTypeKind()) { 5021 case Type::STK_FloatingComplex: 5022 return CK_IntegralComplexToFloatingComplex; 5023 case Type::STK_IntegralComplex: 5024 return CK_IntegralComplexCast; 5025 case Type::STK_Integral: { 5026 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5027 if (Context.hasSameType(ET, DestTy)) 5028 return CK_IntegralComplexToReal; 5029 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 5030 return CK_IntegralCast; 5031 } 5032 case Type::STK_Bool: 5033 return CK_IntegralComplexToBoolean; 5034 case Type::STK_Floating: 5035 Src = ImpCastExprToType(Src.take(), 5036 SrcTy->castAs<ComplexType>()->getElementType(), 5037 CK_IntegralComplexToReal); 5038 return CK_IntegralToFloating; 5039 case Type::STK_CPointer: 5040 case Type::STK_ObjCObjectPointer: 5041 case Type::STK_BlockPointer: 5042 llvm_unreachable("valid complex int->pointer cast?"); 5043 case Type::STK_MemberPointer: 5044 llvm_unreachable("member pointer type in C"); 5045 } 5046 llvm_unreachable("Should have returned before this"); 5047 } 5048 5049 llvm_unreachable("Unhandled scalar cast"); 5050 } 5051 5052 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5053 CastKind &Kind) { 5054 assert(VectorTy->isVectorType() && "Not a vector type!"); 5055 5056 if (Ty->isVectorType() || Ty->isIntegerType()) { 5057 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 5058 return Diag(R.getBegin(), 5059 Ty->isVectorType() ? 5060 diag::err_invalid_conversion_between_vectors : 5061 diag::err_invalid_conversion_between_vector_and_integer) 5062 << VectorTy << Ty << R; 5063 } else 5064 return Diag(R.getBegin(), 5065 diag::err_invalid_conversion_between_vector_and_scalar) 5066 << VectorTy << Ty << R; 5067 5068 Kind = CK_BitCast; 5069 return false; 5070 } 5071 5072 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5073 Expr *CastExpr, CastKind &Kind) { 5074 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5075 5076 QualType SrcTy = CastExpr->getType(); 5077 5078 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5079 // an ExtVectorType. 5080 // In OpenCL, casts between vectors of different types are not allowed. 5081 // (See OpenCL 6.2). 5082 if (SrcTy->isVectorType()) { 5083 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 5084 || (getLangOpts().OpenCL && 5085 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5086 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5087 << DestTy << SrcTy << R; 5088 return ExprError(); 5089 } 5090 Kind = CK_BitCast; 5091 return Owned(CastExpr); 5092 } 5093 5094 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5095 // conversion will take place first from scalar to elt type, and then 5096 // splat from elt type to vector. 5097 if (SrcTy->isPointerType()) 5098 return Diag(R.getBegin(), 5099 diag::err_invalid_conversion_between_vector_and_scalar) 5100 << DestTy << SrcTy << R; 5101 5102 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5103 ExprResult CastExprRes = Owned(CastExpr); 5104 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5105 if (CastExprRes.isInvalid()) 5106 return ExprError(); 5107 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 5108 5109 Kind = CK_VectorSplat; 5110 return Owned(CastExpr); 5111 } 5112 5113 ExprResult 5114 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5115 Declarator &D, ParsedType &Ty, 5116 SourceLocation RParenLoc, Expr *CastExpr) { 5117 assert(!D.isInvalidType() && (CastExpr != 0) && 5118 "ActOnCastExpr(): missing type or expr"); 5119 5120 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5121 if (D.isInvalidType()) 5122 return ExprError(); 5123 5124 if (getLangOpts().CPlusPlus) { 5125 // Check that there are no default arguments (C++ only). 5126 CheckExtraCXXDefaultArguments(D); 5127 } 5128 5129 checkUnusedDeclAttributes(D); 5130 5131 QualType castType = castTInfo->getType(); 5132 Ty = CreateParsedType(castType, castTInfo); 5133 5134 bool isVectorLiteral = false; 5135 5136 // Check for an altivec or OpenCL literal, 5137 // i.e. all the elements are integer constants. 5138 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5139 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5140 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5141 && castType->isVectorType() && (PE || PLE)) { 5142 if (PLE && PLE->getNumExprs() == 0) { 5143 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5144 return ExprError(); 5145 } 5146 if (PE || PLE->getNumExprs() == 1) { 5147 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5148 if (!E->getType()->isVectorType()) 5149 isVectorLiteral = true; 5150 } 5151 else 5152 isVectorLiteral = true; 5153 } 5154 5155 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5156 // then handle it as such. 5157 if (isVectorLiteral) 5158 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5159 5160 // If the Expr being casted is a ParenListExpr, handle it specially. 5161 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5162 // sequence of BinOp comma operators. 5163 if (isa<ParenListExpr>(CastExpr)) { 5164 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5165 if (Result.isInvalid()) return ExprError(); 5166 CastExpr = Result.take(); 5167 } 5168 5169 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5170 !getSourceManager().isInSystemMacro(LParenLoc)) 5171 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5172 5173 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5174 } 5175 5176 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5177 SourceLocation RParenLoc, Expr *E, 5178 TypeSourceInfo *TInfo) { 5179 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5180 "Expected paren or paren list expression"); 5181 5182 Expr **exprs; 5183 unsigned numExprs; 5184 Expr *subExpr; 5185 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5186 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5187 LiteralLParenLoc = PE->getLParenLoc(); 5188 LiteralRParenLoc = PE->getRParenLoc(); 5189 exprs = PE->getExprs(); 5190 numExprs = PE->getNumExprs(); 5191 } else { // isa<ParenExpr> by assertion at function entrance 5192 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5193 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5194 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5195 exprs = &subExpr; 5196 numExprs = 1; 5197 } 5198 5199 QualType Ty = TInfo->getType(); 5200 assert(Ty->isVectorType() && "Expected vector type"); 5201 5202 SmallVector<Expr *, 8> initExprs; 5203 const VectorType *VTy = Ty->getAs<VectorType>(); 5204 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5205 5206 // '(...)' form of vector initialization in AltiVec: the number of 5207 // initializers must be one or must match the size of the vector. 5208 // If a single value is specified in the initializer then it will be 5209 // replicated to all the components of the vector 5210 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5211 // The number of initializers must be one or must match the size of the 5212 // vector. If a single value is specified in the initializer then it will 5213 // be replicated to all the components of the vector 5214 if (numExprs == 1) { 5215 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5216 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5217 if (Literal.isInvalid()) 5218 return ExprError(); 5219 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5220 PrepareScalarCast(Literal, ElemTy)); 5221 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5222 } 5223 else if (numExprs < numElems) { 5224 Diag(E->getExprLoc(), 5225 diag::err_incorrect_number_of_vector_initializers); 5226 return ExprError(); 5227 } 5228 else 5229 initExprs.append(exprs, exprs + numExprs); 5230 } 5231 else { 5232 // For OpenCL, when the number of initializers is a single value, 5233 // it will be replicated to all components of the vector. 5234 if (getLangOpts().OpenCL && 5235 VTy->getVectorKind() == VectorType::GenericVector && 5236 numExprs == 1) { 5237 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5238 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5239 if (Literal.isInvalid()) 5240 return ExprError(); 5241 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5242 PrepareScalarCast(Literal, ElemTy)); 5243 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5244 } 5245 5246 initExprs.append(exprs, exprs + numExprs); 5247 } 5248 // FIXME: This means that pretty-printing the final AST will produce curly 5249 // braces instead of the original commas. 5250 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5251 initExprs, LiteralRParenLoc); 5252 initE->setType(Ty); 5253 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5254 } 5255 5256 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5257 /// the ParenListExpr into a sequence of comma binary operators. 5258 ExprResult 5259 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5260 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5261 if (!E) 5262 return Owned(OrigExpr); 5263 5264 ExprResult Result(E->getExpr(0)); 5265 5266 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5267 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5268 E->getExpr(i)); 5269 5270 if (Result.isInvalid()) return ExprError(); 5271 5272 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5273 } 5274 5275 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5276 SourceLocation R, 5277 MultiExprArg Val) { 5278 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5279 return Owned(expr); 5280 } 5281 5282 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5283 /// constant and the other is not a pointer. Returns true if a diagnostic is 5284 /// emitted. 5285 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5286 SourceLocation QuestionLoc) { 5287 Expr *NullExpr = LHSExpr; 5288 Expr *NonPointerExpr = RHSExpr; 5289 Expr::NullPointerConstantKind NullKind = 5290 NullExpr->isNullPointerConstant(Context, 5291 Expr::NPC_ValueDependentIsNotNull); 5292 5293 if (NullKind == Expr::NPCK_NotNull) { 5294 NullExpr = RHSExpr; 5295 NonPointerExpr = LHSExpr; 5296 NullKind = 5297 NullExpr->isNullPointerConstant(Context, 5298 Expr::NPC_ValueDependentIsNotNull); 5299 } 5300 5301 if (NullKind == Expr::NPCK_NotNull) 5302 return false; 5303 5304 if (NullKind == Expr::NPCK_ZeroExpression) 5305 return false; 5306 5307 if (NullKind == Expr::NPCK_ZeroLiteral) { 5308 // In this case, check to make sure that we got here from a "NULL" 5309 // string in the source code. 5310 NullExpr = NullExpr->IgnoreParenImpCasts(); 5311 SourceLocation loc = NullExpr->getExprLoc(); 5312 if (!findMacroSpelling(loc, "NULL")) 5313 return false; 5314 } 5315 5316 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5317 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5318 << NonPointerExpr->getType() << DiagType 5319 << NonPointerExpr->getSourceRange(); 5320 return true; 5321 } 5322 5323 /// \brief Return false if the condition expression is valid, true otherwise. 5324 static bool checkCondition(Sema &S, Expr *Cond) { 5325 QualType CondTy = Cond->getType(); 5326 5327 // C99 6.5.15p2 5328 if (CondTy->isScalarType()) return false; 5329 5330 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5331 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5332 return false; 5333 5334 // Emit the proper error message. 5335 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5336 diag::err_typecheck_cond_expect_scalar : 5337 diag::err_typecheck_cond_expect_scalar_or_vector) 5338 << CondTy; 5339 return true; 5340 } 5341 5342 /// \brief Return false if the two expressions can be converted to a vector, 5343 /// true otherwise 5344 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5345 ExprResult &RHS, 5346 QualType CondTy) { 5347 // Both operands should be of scalar type. 5348 if (!LHS.get()->getType()->isScalarType()) { 5349 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5350 << CondTy; 5351 return true; 5352 } 5353 if (!RHS.get()->getType()->isScalarType()) { 5354 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5355 << CondTy; 5356 return true; 5357 } 5358 5359 // Implicity convert these scalars to the type of the condition. 5360 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5361 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5362 return false; 5363 } 5364 5365 /// \brief Handle when one or both operands are void type. 5366 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5367 ExprResult &RHS) { 5368 Expr *LHSExpr = LHS.get(); 5369 Expr *RHSExpr = RHS.get(); 5370 5371 if (!LHSExpr->getType()->isVoidType()) 5372 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5373 << RHSExpr->getSourceRange(); 5374 if (!RHSExpr->getType()->isVoidType()) 5375 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5376 << LHSExpr->getSourceRange(); 5377 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5378 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5379 return S.Context.VoidTy; 5380 } 5381 5382 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5383 /// true otherwise. 5384 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5385 QualType PointerTy) { 5386 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5387 !NullExpr.get()->isNullPointerConstant(S.Context, 5388 Expr::NPC_ValueDependentIsNull)) 5389 return true; 5390 5391 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5392 return false; 5393 } 5394 5395 /// \brief Checks compatibility between two pointers and return the resulting 5396 /// type. 5397 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5398 ExprResult &RHS, 5399 SourceLocation Loc) { 5400 QualType LHSTy = LHS.get()->getType(); 5401 QualType RHSTy = RHS.get()->getType(); 5402 5403 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5404 // Two identical pointers types are always compatible. 5405 return LHSTy; 5406 } 5407 5408 QualType lhptee, rhptee; 5409 5410 // Get the pointee types. 5411 bool IsBlockPointer = false; 5412 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5413 lhptee = LHSBTy->getPointeeType(); 5414 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5415 IsBlockPointer = true; 5416 } else { 5417 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5418 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5419 } 5420 5421 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5422 // differently qualified versions of compatible types, the result type is 5423 // a pointer to an appropriately qualified version of the composite 5424 // type. 5425 5426 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5427 // clause doesn't make sense for our extensions. E.g. address space 2 should 5428 // be incompatible with address space 3: they may live on different devices or 5429 // anything. 5430 Qualifiers lhQual = lhptee.getQualifiers(); 5431 Qualifiers rhQual = rhptee.getQualifiers(); 5432 5433 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5434 lhQual.removeCVRQualifiers(); 5435 rhQual.removeCVRQualifiers(); 5436 5437 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5438 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5439 5440 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5441 5442 if (CompositeTy.isNull()) { 5443 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5444 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5445 << RHS.get()->getSourceRange(); 5446 // In this situation, we assume void* type. No especially good 5447 // reason, but this is what gcc does, and we do have to pick 5448 // to get a consistent AST. 5449 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5450 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5451 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5452 return incompatTy; 5453 } 5454 5455 // The pointer types are compatible. 5456 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5457 if (IsBlockPointer) 5458 ResultTy = S.Context.getBlockPointerType(ResultTy); 5459 else 5460 ResultTy = S.Context.getPointerType(ResultTy); 5461 5462 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5463 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5464 return ResultTy; 5465 } 5466 5467 /// \brief Return the resulting type when the operands are both block pointers. 5468 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5469 ExprResult &LHS, 5470 ExprResult &RHS, 5471 SourceLocation Loc) { 5472 QualType LHSTy = LHS.get()->getType(); 5473 QualType RHSTy = RHS.get()->getType(); 5474 5475 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5476 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5477 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5478 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5479 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5480 return destType; 5481 } 5482 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5483 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5484 << RHS.get()->getSourceRange(); 5485 return QualType(); 5486 } 5487 5488 // We have 2 block pointer types. 5489 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5490 } 5491 5492 /// \brief Return the resulting type when the operands are both pointers. 5493 static QualType 5494 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5495 ExprResult &RHS, 5496 SourceLocation Loc) { 5497 // get the pointer types 5498 QualType LHSTy = LHS.get()->getType(); 5499 QualType RHSTy = RHS.get()->getType(); 5500 5501 // get the "pointed to" types 5502 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5503 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5504 5505 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5506 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5507 // Figure out necessary qualifiers (C99 6.5.15p6) 5508 QualType destPointee 5509 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5510 QualType destType = S.Context.getPointerType(destPointee); 5511 // Add qualifiers if necessary. 5512 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5513 // Promote to void*. 5514 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5515 return destType; 5516 } 5517 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5518 QualType destPointee 5519 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5520 QualType destType = S.Context.getPointerType(destPointee); 5521 // Add qualifiers if necessary. 5522 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5523 // Promote to void*. 5524 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5525 return destType; 5526 } 5527 5528 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5529 } 5530 5531 /// \brief Return false if the first expression is not an integer and the second 5532 /// expression is not a pointer, true otherwise. 5533 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5534 Expr* PointerExpr, SourceLocation Loc, 5535 bool IsIntFirstExpr) { 5536 if (!PointerExpr->getType()->isPointerType() || 5537 !Int.get()->getType()->isIntegerType()) 5538 return false; 5539 5540 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5541 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5542 5543 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5544 << Expr1->getType() << Expr2->getType() 5545 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5546 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5547 CK_IntegralToPointer); 5548 return true; 5549 } 5550 5551 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5552 /// In that case, LHS = cond. 5553 /// C99 6.5.15 5554 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5555 ExprResult &RHS, ExprValueKind &VK, 5556 ExprObjectKind &OK, 5557 SourceLocation QuestionLoc) { 5558 5559 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5560 if (!LHSResult.isUsable()) return QualType(); 5561 LHS = LHSResult; 5562 5563 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5564 if (!RHSResult.isUsable()) return QualType(); 5565 RHS = RHSResult; 5566 5567 // C++ is sufficiently different to merit its own checker. 5568 if (getLangOpts().CPlusPlus) 5569 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5570 5571 VK = VK_RValue; 5572 OK = OK_Ordinary; 5573 5574 // First, check the condition. 5575 Cond = UsualUnaryConversions(Cond.take()); 5576 if (Cond.isInvalid()) 5577 return QualType(); 5578 if (checkCondition(*this, Cond.get())) 5579 return QualType(); 5580 5581 // Now check the two expressions. 5582 if (LHS.get()->getType()->isVectorType() || 5583 RHS.get()->getType()->isVectorType()) 5584 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5585 5586 UsualArithmeticConversions(LHS, RHS); 5587 if (LHS.isInvalid() || RHS.isInvalid()) 5588 return QualType(); 5589 5590 QualType CondTy = Cond.get()->getType(); 5591 QualType LHSTy = LHS.get()->getType(); 5592 QualType RHSTy = RHS.get()->getType(); 5593 5594 // If the condition is a vector, and both operands are scalar, 5595 // attempt to implicity convert them to the vector type to act like the 5596 // built in select. (OpenCL v1.1 s6.3.i) 5597 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5598 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5599 return QualType(); 5600 5601 // If both operands have arithmetic type, do the usual arithmetic conversions 5602 // to find a common type: C99 6.5.15p3,5. 5603 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5604 return LHS.get()->getType(); 5605 5606 // If both operands are the same structure or union type, the result is that 5607 // type. 5608 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5609 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5610 if (LHSRT->getDecl() == RHSRT->getDecl()) 5611 // "If both the operands have structure or union type, the result has 5612 // that type." This implies that CV qualifiers are dropped. 5613 return LHSTy.getUnqualifiedType(); 5614 // FIXME: Type of conditional expression must be complete in C mode. 5615 } 5616 5617 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5618 // The following || allows only one side to be void (a GCC-ism). 5619 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5620 return checkConditionalVoidType(*this, LHS, RHS); 5621 } 5622 5623 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5624 // the type of the other operand." 5625 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5626 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5627 5628 // All objective-c pointer type analysis is done here. 5629 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5630 QuestionLoc); 5631 if (LHS.isInvalid() || RHS.isInvalid()) 5632 return QualType(); 5633 if (!compositeType.isNull()) 5634 return compositeType; 5635 5636 5637 // Handle block pointer types. 5638 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5639 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5640 QuestionLoc); 5641 5642 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5643 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5644 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5645 QuestionLoc); 5646 5647 // GCC compatibility: soften pointer/integer mismatch. Note that 5648 // null pointers have been filtered out by this point. 5649 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5650 /*isIntFirstExpr=*/true)) 5651 return RHSTy; 5652 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5653 /*isIntFirstExpr=*/false)) 5654 return LHSTy; 5655 5656 // Emit a better diagnostic if one of the expressions is a null pointer 5657 // constant and the other is not a pointer type. In this case, the user most 5658 // likely forgot to take the address of the other expression. 5659 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5660 return QualType(); 5661 5662 // Otherwise, the operands are not compatible. 5663 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5664 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5665 << RHS.get()->getSourceRange(); 5666 return QualType(); 5667 } 5668 5669 /// FindCompositeObjCPointerType - Helper method to find composite type of 5670 /// two objective-c pointer types of the two input expressions. 5671 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5672 SourceLocation QuestionLoc) { 5673 QualType LHSTy = LHS.get()->getType(); 5674 QualType RHSTy = RHS.get()->getType(); 5675 5676 // Handle things like Class and struct objc_class*. Here we case the result 5677 // to the pseudo-builtin, because that will be implicitly cast back to the 5678 // redefinition type if an attempt is made to access its fields. 5679 if (LHSTy->isObjCClassType() && 5680 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5681 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5682 return LHSTy; 5683 } 5684 if (RHSTy->isObjCClassType() && 5685 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5686 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5687 return RHSTy; 5688 } 5689 // And the same for struct objc_object* / id 5690 if (LHSTy->isObjCIdType() && 5691 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5692 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5693 return LHSTy; 5694 } 5695 if (RHSTy->isObjCIdType() && 5696 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5697 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5698 return RHSTy; 5699 } 5700 // And the same for struct objc_selector* / SEL 5701 if (Context.isObjCSelType(LHSTy) && 5702 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5703 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5704 return LHSTy; 5705 } 5706 if (Context.isObjCSelType(RHSTy) && 5707 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5708 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5709 return RHSTy; 5710 } 5711 // Check constraints for Objective-C object pointers types. 5712 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5713 5714 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5715 // Two identical object pointer types are always compatible. 5716 return LHSTy; 5717 } 5718 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5719 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5720 QualType compositeType = LHSTy; 5721 5722 // If both operands are interfaces and either operand can be 5723 // assigned to the other, use that type as the composite 5724 // type. This allows 5725 // xxx ? (A*) a : (B*) b 5726 // where B is a subclass of A. 5727 // 5728 // Additionally, as for assignment, if either type is 'id' 5729 // allow silent coercion. Finally, if the types are 5730 // incompatible then make sure to use 'id' as the composite 5731 // type so the result is acceptable for sending messages to. 5732 5733 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5734 // It could return the composite type. 5735 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5736 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5737 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5738 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5739 } else if ((LHSTy->isObjCQualifiedIdType() || 5740 RHSTy->isObjCQualifiedIdType()) && 5741 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5742 // Need to handle "id<xx>" explicitly. 5743 // GCC allows qualified id and any Objective-C type to devolve to 5744 // id. Currently localizing to here until clear this should be 5745 // part of ObjCQualifiedIdTypesAreCompatible. 5746 compositeType = Context.getObjCIdType(); 5747 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5748 compositeType = Context.getObjCIdType(); 5749 } else if (!(compositeType = 5750 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5751 ; 5752 else { 5753 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5754 << LHSTy << RHSTy 5755 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5756 QualType incompatTy = Context.getObjCIdType(); 5757 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5758 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5759 return incompatTy; 5760 } 5761 // The object pointer types are compatible. 5762 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5763 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5764 return compositeType; 5765 } 5766 // Check Objective-C object pointer types and 'void *' 5767 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5768 if (getLangOpts().ObjCAutoRefCount) { 5769 // ARC forbids the implicit conversion of object pointers to 'void *', 5770 // so these types are not compatible. 5771 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5772 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5773 LHS = RHS = true; 5774 return QualType(); 5775 } 5776 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5777 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5778 QualType destPointee 5779 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5780 QualType destType = Context.getPointerType(destPointee); 5781 // Add qualifiers if necessary. 5782 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5783 // Promote to void*. 5784 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5785 return destType; 5786 } 5787 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5788 if (getLangOpts().ObjCAutoRefCount) { 5789 // ARC forbids the implicit conversion of object pointers to 'void *', 5790 // so these types are not compatible. 5791 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5792 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5793 LHS = RHS = true; 5794 return QualType(); 5795 } 5796 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5797 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5798 QualType destPointee 5799 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5800 QualType destType = Context.getPointerType(destPointee); 5801 // Add qualifiers if necessary. 5802 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5803 // Promote to void*. 5804 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5805 return destType; 5806 } 5807 return QualType(); 5808 } 5809 5810 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5811 /// ParenRange in parentheses. 5812 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5813 const PartialDiagnostic &Note, 5814 SourceRange ParenRange) { 5815 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5816 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5817 EndLoc.isValid()) { 5818 Self.Diag(Loc, Note) 5819 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5820 << FixItHint::CreateInsertion(EndLoc, ")"); 5821 } else { 5822 // We can't display the parentheses, so just show the bare note. 5823 Self.Diag(Loc, Note) << ParenRange; 5824 } 5825 } 5826 5827 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5828 return Opc >= BO_Mul && Opc <= BO_Shr; 5829 } 5830 5831 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5832 /// expression, either using a built-in or overloaded operator, 5833 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5834 /// expression. 5835 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5836 Expr **RHSExprs) { 5837 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5838 E = E->IgnoreImpCasts(); 5839 E = E->IgnoreConversionOperator(); 5840 E = E->IgnoreImpCasts(); 5841 5842 // Built-in binary operator. 5843 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5844 if (IsArithmeticOp(OP->getOpcode())) { 5845 *Opcode = OP->getOpcode(); 5846 *RHSExprs = OP->getRHS(); 5847 return true; 5848 } 5849 } 5850 5851 // Overloaded operator. 5852 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5853 if (Call->getNumArgs() != 2) 5854 return false; 5855 5856 // Make sure this is really a binary operator that is safe to pass into 5857 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5858 OverloadedOperatorKind OO = Call->getOperator(); 5859 if (OO < OO_Plus || OO > OO_Arrow || 5860 OO == OO_PlusPlus || OO == OO_MinusMinus) 5861 return false; 5862 5863 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5864 if (IsArithmeticOp(OpKind)) { 5865 *Opcode = OpKind; 5866 *RHSExprs = Call->getArg(1); 5867 return true; 5868 } 5869 } 5870 5871 return false; 5872 } 5873 5874 static bool IsLogicOp(BinaryOperatorKind Opc) { 5875 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5876 } 5877 5878 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5879 /// or is a logical expression such as (x==y) which has int type, but is 5880 /// commonly interpreted as boolean. 5881 static bool ExprLooksBoolean(Expr *E) { 5882 E = E->IgnoreParenImpCasts(); 5883 5884 if (E->getType()->isBooleanType()) 5885 return true; 5886 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5887 return IsLogicOp(OP->getOpcode()); 5888 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5889 return OP->getOpcode() == UO_LNot; 5890 5891 return false; 5892 } 5893 5894 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5895 /// and binary operator are mixed in a way that suggests the programmer assumed 5896 /// the conditional operator has higher precedence, for example: 5897 /// "int x = a + someBinaryCondition ? 1 : 2". 5898 static void DiagnoseConditionalPrecedence(Sema &Self, 5899 SourceLocation OpLoc, 5900 Expr *Condition, 5901 Expr *LHSExpr, 5902 Expr *RHSExpr) { 5903 BinaryOperatorKind CondOpcode; 5904 Expr *CondRHS; 5905 5906 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5907 return; 5908 if (!ExprLooksBoolean(CondRHS)) 5909 return; 5910 5911 // The condition is an arithmetic binary expression, with a right- 5912 // hand side that looks boolean, so warn. 5913 5914 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5915 << Condition->getSourceRange() 5916 << BinaryOperator::getOpcodeStr(CondOpcode); 5917 5918 SuggestParentheses(Self, OpLoc, 5919 Self.PDiag(diag::note_precedence_silence) 5920 << BinaryOperator::getOpcodeStr(CondOpcode), 5921 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5922 5923 SuggestParentheses(Self, OpLoc, 5924 Self.PDiag(diag::note_precedence_conditional_first), 5925 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5926 } 5927 5928 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5929 /// in the case of a the GNU conditional expr extension. 5930 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5931 SourceLocation ColonLoc, 5932 Expr *CondExpr, Expr *LHSExpr, 5933 Expr *RHSExpr) { 5934 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5935 // was the condition. 5936 OpaqueValueExpr *opaqueValue = 0; 5937 Expr *commonExpr = 0; 5938 if (LHSExpr == 0) { 5939 commonExpr = CondExpr; 5940 // Lower out placeholder types first. This is important so that we don't 5941 // try to capture a placeholder. This happens in few cases in C++; such 5942 // as Objective-C++'s dictionary subscripting syntax. 5943 if (commonExpr->hasPlaceholderType()) { 5944 ExprResult result = CheckPlaceholderExpr(commonExpr); 5945 if (!result.isUsable()) return ExprError(); 5946 commonExpr = result.take(); 5947 } 5948 // We usually want to apply unary conversions *before* saving, except 5949 // in the special case of a C++ l-value conditional. 5950 if (!(getLangOpts().CPlusPlus 5951 && !commonExpr->isTypeDependent() 5952 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5953 && commonExpr->isGLValue() 5954 && commonExpr->isOrdinaryOrBitFieldObject() 5955 && RHSExpr->isOrdinaryOrBitFieldObject() 5956 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5957 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5958 if (commonRes.isInvalid()) 5959 return ExprError(); 5960 commonExpr = commonRes.take(); 5961 } 5962 5963 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5964 commonExpr->getType(), 5965 commonExpr->getValueKind(), 5966 commonExpr->getObjectKind(), 5967 commonExpr); 5968 LHSExpr = CondExpr = opaqueValue; 5969 } 5970 5971 ExprValueKind VK = VK_RValue; 5972 ExprObjectKind OK = OK_Ordinary; 5973 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5974 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5975 VK, OK, QuestionLoc); 5976 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5977 RHS.isInvalid()) 5978 return ExprError(); 5979 5980 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5981 RHS.get()); 5982 5983 if (!commonExpr) 5984 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5985 LHS.take(), ColonLoc, 5986 RHS.take(), result, VK, OK)); 5987 5988 return Owned(new (Context) 5989 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5990 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5991 OK)); 5992 } 5993 5994 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5995 // being closely modeled after the C99 spec:-). The odd characteristic of this 5996 // routine is it effectively iqnores the qualifiers on the top level pointee. 5997 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5998 // FIXME: add a couple examples in this comment. 5999 static Sema::AssignConvertType 6000 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6001 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6002 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6003 6004 // get the "pointed to" type (ignoring qualifiers at the top level) 6005 const Type *lhptee, *rhptee; 6006 Qualifiers lhq, rhq; 6007 std::tie(lhptee, lhq) = 6008 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6009 std::tie(rhptee, rhq) = 6010 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6011 6012 Sema::AssignConvertType ConvTy = Sema::Compatible; 6013 6014 // C99 6.5.16.1p1: This following citation is common to constraints 6015 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6016 // qualifiers of the type *pointed to* by the right; 6017 6018 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6019 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6020 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6021 // Ignore lifetime for further calculation. 6022 lhq.removeObjCLifetime(); 6023 rhq.removeObjCLifetime(); 6024 } 6025 6026 if (!lhq.compatiblyIncludes(rhq)) { 6027 // Treat address-space mismatches as fatal. TODO: address subspaces 6028 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 6029 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6030 6031 // It's okay to add or remove GC or lifetime qualifiers when converting to 6032 // and from void*. 6033 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6034 .compatiblyIncludes( 6035 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6036 && (lhptee->isVoidType() || rhptee->isVoidType())) 6037 ; // keep old 6038 6039 // Treat lifetime mismatches as fatal. 6040 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6041 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6042 6043 // For GCC compatibility, other qualifier mismatches are treated 6044 // as still compatible in C. 6045 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6046 } 6047 6048 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6049 // incomplete type and the other is a pointer to a qualified or unqualified 6050 // version of void... 6051 if (lhptee->isVoidType()) { 6052 if (rhptee->isIncompleteOrObjectType()) 6053 return ConvTy; 6054 6055 // As an extension, we allow cast to/from void* to function pointer. 6056 assert(rhptee->isFunctionType()); 6057 return Sema::FunctionVoidPointer; 6058 } 6059 6060 if (rhptee->isVoidType()) { 6061 if (lhptee->isIncompleteOrObjectType()) 6062 return ConvTy; 6063 6064 // As an extension, we allow cast to/from void* to function pointer. 6065 assert(lhptee->isFunctionType()); 6066 return Sema::FunctionVoidPointer; 6067 } 6068 6069 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6070 // unqualified versions of compatible types, ... 6071 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6072 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6073 // Check if the pointee types are compatible ignoring the sign. 6074 // We explicitly check for char so that we catch "char" vs 6075 // "unsigned char" on systems where "char" is unsigned. 6076 if (lhptee->isCharType()) 6077 ltrans = S.Context.UnsignedCharTy; 6078 else if (lhptee->hasSignedIntegerRepresentation()) 6079 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6080 6081 if (rhptee->isCharType()) 6082 rtrans = S.Context.UnsignedCharTy; 6083 else if (rhptee->hasSignedIntegerRepresentation()) 6084 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6085 6086 if (ltrans == rtrans) { 6087 // Types are compatible ignoring the sign. Qualifier incompatibility 6088 // takes priority over sign incompatibility because the sign 6089 // warning can be disabled. 6090 if (ConvTy != Sema::Compatible) 6091 return ConvTy; 6092 6093 return Sema::IncompatiblePointerSign; 6094 } 6095 6096 // If we are a multi-level pointer, it's possible that our issue is simply 6097 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6098 // the eventual target type is the same and the pointers have the same 6099 // level of indirection, this must be the issue. 6100 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6101 do { 6102 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6103 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6104 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6105 6106 if (lhptee == rhptee) 6107 return Sema::IncompatibleNestedPointerQualifiers; 6108 } 6109 6110 // General pointer incompatibility takes priority over qualifiers. 6111 return Sema::IncompatiblePointer; 6112 } 6113 if (!S.getLangOpts().CPlusPlus && 6114 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6115 return Sema::IncompatiblePointer; 6116 return ConvTy; 6117 } 6118 6119 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6120 /// block pointer types are compatible or whether a block and normal pointer 6121 /// are compatible. It is more restrict than comparing two function pointer 6122 // types. 6123 static Sema::AssignConvertType 6124 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6125 QualType RHSType) { 6126 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6127 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6128 6129 QualType lhptee, rhptee; 6130 6131 // get the "pointed to" type (ignoring qualifiers at the top level) 6132 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6133 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6134 6135 // In C++, the types have to match exactly. 6136 if (S.getLangOpts().CPlusPlus) 6137 return Sema::IncompatibleBlockPointer; 6138 6139 Sema::AssignConvertType ConvTy = Sema::Compatible; 6140 6141 // For blocks we enforce that qualifiers are identical. 6142 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6143 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6144 6145 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6146 return Sema::IncompatibleBlockPointer; 6147 6148 return ConvTy; 6149 } 6150 6151 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6152 /// for assignment compatibility. 6153 static Sema::AssignConvertType 6154 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6155 QualType RHSType) { 6156 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6157 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6158 6159 if (LHSType->isObjCBuiltinType()) { 6160 // Class is not compatible with ObjC object pointers. 6161 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6162 !RHSType->isObjCQualifiedClassType()) 6163 return Sema::IncompatiblePointer; 6164 return Sema::Compatible; 6165 } 6166 if (RHSType->isObjCBuiltinType()) { 6167 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6168 !LHSType->isObjCQualifiedClassType()) 6169 return Sema::IncompatiblePointer; 6170 return Sema::Compatible; 6171 } 6172 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6173 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6174 6175 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6176 // make an exception for id<P> 6177 !LHSType->isObjCQualifiedIdType()) 6178 return Sema::CompatiblePointerDiscardsQualifiers; 6179 6180 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6181 return Sema::Compatible; 6182 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6183 return Sema::IncompatibleObjCQualifiedId; 6184 return Sema::IncompatiblePointer; 6185 } 6186 6187 Sema::AssignConvertType 6188 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6189 QualType LHSType, QualType RHSType) { 6190 // Fake up an opaque expression. We don't actually care about what 6191 // cast operations are required, so if CheckAssignmentConstraints 6192 // adds casts to this they'll be wasted, but fortunately that doesn't 6193 // usually happen on valid code. 6194 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6195 ExprResult RHSPtr = &RHSExpr; 6196 CastKind K = CK_Invalid; 6197 6198 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6199 } 6200 6201 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6202 /// has code to accommodate several GCC extensions when type checking 6203 /// pointers. Here are some objectionable examples that GCC considers warnings: 6204 /// 6205 /// int a, *pint; 6206 /// short *pshort; 6207 /// struct foo *pfoo; 6208 /// 6209 /// pint = pshort; // warning: assignment from incompatible pointer type 6210 /// a = pint; // warning: assignment makes integer from pointer without a cast 6211 /// pint = a; // warning: assignment makes pointer from integer without a cast 6212 /// pint = pfoo; // warning: assignment from incompatible pointer type 6213 /// 6214 /// As a result, the code for dealing with pointers is more complex than the 6215 /// C99 spec dictates. 6216 /// 6217 /// Sets 'Kind' for any result kind except Incompatible. 6218 Sema::AssignConvertType 6219 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6220 CastKind &Kind) { 6221 QualType RHSType = RHS.get()->getType(); 6222 QualType OrigLHSType = LHSType; 6223 6224 // Get canonical types. We're not formatting these types, just comparing 6225 // them. 6226 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6227 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6228 6229 // Common case: no conversion required. 6230 if (LHSType == RHSType) { 6231 Kind = CK_NoOp; 6232 return Compatible; 6233 } 6234 6235 // If we have an atomic type, try a non-atomic assignment, then just add an 6236 // atomic qualification step. 6237 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6238 Sema::AssignConvertType result = 6239 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6240 if (result != Compatible) 6241 return result; 6242 if (Kind != CK_NoOp) 6243 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 6244 Kind = CK_NonAtomicToAtomic; 6245 return Compatible; 6246 } 6247 6248 // If the left-hand side is a reference type, then we are in a 6249 // (rare!) case where we've allowed the use of references in C, 6250 // e.g., as a parameter type in a built-in function. In this case, 6251 // just make sure that the type referenced is compatible with the 6252 // right-hand side type. The caller is responsible for adjusting 6253 // LHSType so that the resulting expression does not have reference 6254 // type. 6255 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6256 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6257 Kind = CK_LValueBitCast; 6258 return Compatible; 6259 } 6260 return Incompatible; 6261 } 6262 6263 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6264 // to the same ExtVector type. 6265 if (LHSType->isExtVectorType()) { 6266 if (RHSType->isExtVectorType()) 6267 return Incompatible; 6268 if (RHSType->isArithmeticType()) { 6269 // CK_VectorSplat does T -> vector T, so first cast to the 6270 // element type. 6271 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6272 if (elType != RHSType) { 6273 Kind = PrepareScalarCast(RHS, elType); 6274 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 6275 } 6276 Kind = CK_VectorSplat; 6277 return Compatible; 6278 } 6279 } 6280 6281 // Conversions to or from vector type. 6282 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6283 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6284 // Allow assignments of an AltiVec vector type to an equivalent GCC 6285 // vector type and vice versa 6286 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6287 Kind = CK_BitCast; 6288 return Compatible; 6289 } 6290 6291 // If we are allowing lax vector conversions, and LHS and RHS are both 6292 // vectors, the total size only needs to be the same. This is a bitcast; 6293 // no bits are changed but the result type is different. 6294 if (isLaxVectorConversion(RHSType, LHSType)) { 6295 Kind = CK_BitCast; 6296 return IncompatibleVectors; 6297 } 6298 } 6299 return Incompatible; 6300 } 6301 6302 // Arithmetic conversions. 6303 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6304 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6305 Kind = PrepareScalarCast(RHS, LHSType); 6306 return Compatible; 6307 } 6308 6309 // Conversions to normal pointers. 6310 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6311 // U* -> T* 6312 if (isa<PointerType>(RHSType)) { 6313 Kind = CK_BitCast; 6314 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6315 } 6316 6317 // int -> T* 6318 if (RHSType->isIntegerType()) { 6319 Kind = CK_IntegralToPointer; // FIXME: null? 6320 return IntToPointer; 6321 } 6322 6323 // C pointers are not compatible with ObjC object pointers, 6324 // with two exceptions: 6325 if (isa<ObjCObjectPointerType>(RHSType)) { 6326 // - conversions to void* 6327 if (LHSPointer->getPointeeType()->isVoidType()) { 6328 Kind = CK_BitCast; 6329 return Compatible; 6330 } 6331 6332 // - conversions from 'Class' to the redefinition type 6333 if (RHSType->isObjCClassType() && 6334 Context.hasSameType(LHSType, 6335 Context.getObjCClassRedefinitionType())) { 6336 Kind = CK_BitCast; 6337 return Compatible; 6338 } 6339 6340 Kind = CK_BitCast; 6341 return IncompatiblePointer; 6342 } 6343 6344 // U^ -> void* 6345 if (RHSType->getAs<BlockPointerType>()) { 6346 if (LHSPointer->getPointeeType()->isVoidType()) { 6347 Kind = CK_BitCast; 6348 return Compatible; 6349 } 6350 } 6351 6352 return Incompatible; 6353 } 6354 6355 // Conversions to block pointers. 6356 if (isa<BlockPointerType>(LHSType)) { 6357 // U^ -> T^ 6358 if (RHSType->isBlockPointerType()) { 6359 Kind = CK_BitCast; 6360 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6361 } 6362 6363 // int or null -> T^ 6364 if (RHSType->isIntegerType()) { 6365 Kind = CK_IntegralToPointer; // FIXME: null 6366 return IntToBlockPointer; 6367 } 6368 6369 // id -> T^ 6370 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6371 Kind = CK_AnyPointerToBlockPointerCast; 6372 return Compatible; 6373 } 6374 6375 // void* -> T^ 6376 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6377 if (RHSPT->getPointeeType()->isVoidType()) { 6378 Kind = CK_AnyPointerToBlockPointerCast; 6379 return Compatible; 6380 } 6381 6382 return Incompatible; 6383 } 6384 6385 // Conversions to Objective-C pointers. 6386 if (isa<ObjCObjectPointerType>(LHSType)) { 6387 // A* -> B* 6388 if (RHSType->isObjCObjectPointerType()) { 6389 Kind = CK_BitCast; 6390 Sema::AssignConvertType result = 6391 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6392 if (getLangOpts().ObjCAutoRefCount && 6393 result == Compatible && 6394 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6395 result = IncompatibleObjCWeakRef; 6396 return result; 6397 } 6398 6399 // int or null -> A* 6400 if (RHSType->isIntegerType()) { 6401 Kind = CK_IntegralToPointer; // FIXME: null 6402 return IntToPointer; 6403 } 6404 6405 // In general, C pointers are not compatible with ObjC object pointers, 6406 // with two exceptions: 6407 if (isa<PointerType>(RHSType)) { 6408 Kind = CK_CPointerToObjCPointerCast; 6409 6410 // - conversions from 'void*' 6411 if (RHSType->isVoidPointerType()) { 6412 return Compatible; 6413 } 6414 6415 // - conversions to 'Class' from its redefinition type 6416 if (LHSType->isObjCClassType() && 6417 Context.hasSameType(RHSType, 6418 Context.getObjCClassRedefinitionType())) { 6419 return Compatible; 6420 } 6421 6422 return IncompatiblePointer; 6423 } 6424 6425 // T^ -> A* 6426 if (RHSType->isBlockPointerType()) { 6427 maybeExtendBlockObject(*this, RHS); 6428 Kind = CK_BlockPointerToObjCPointerCast; 6429 return Compatible; 6430 } 6431 6432 return Incompatible; 6433 } 6434 6435 // Conversions from pointers that are not covered by the above. 6436 if (isa<PointerType>(RHSType)) { 6437 // T* -> _Bool 6438 if (LHSType == Context.BoolTy) { 6439 Kind = CK_PointerToBoolean; 6440 return Compatible; 6441 } 6442 6443 // T* -> int 6444 if (LHSType->isIntegerType()) { 6445 Kind = CK_PointerToIntegral; 6446 return PointerToInt; 6447 } 6448 6449 return Incompatible; 6450 } 6451 6452 // Conversions from Objective-C pointers that are not covered by the above. 6453 if (isa<ObjCObjectPointerType>(RHSType)) { 6454 // T* -> _Bool 6455 if (LHSType == Context.BoolTy) { 6456 Kind = CK_PointerToBoolean; 6457 return Compatible; 6458 } 6459 6460 // T* -> int 6461 if (LHSType->isIntegerType()) { 6462 Kind = CK_PointerToIntegral; 6463 return PointerToInt; 6464 } 6465 6466 return Incompatible; 6467 } 6468 6469 // struct A -> struct B 6470 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6471 if (Context.typesAreCompatible(LHSType, RHSType)) { 6472 Kind = CK_NoOp; 6473 return Compatible; 6474 } 6475 } 6476 6477 return Incompatible; 6478 } 6479 6480 /// \brief Constructs a transparent union from an expression that is 6481 /// used to initialize the transparent union. 6482 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6483 ExprResult &EResult, QualType UnionType, 6484 FieldDecl *Field) { 6485 // Build an initializer list that designates the appropriate member 6486 // of the transparent union. 6487 Expr *E = EResult.take(); 6488 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6489 E, SourceLocation()); 6490 Initializer->setType(UnionType); 6491 Initializer->setInitializedFieldInUnion(Field); 6492 6493 // Build a compound literal constructing a value of the transparent 6494 // union type from this initializer list. 6495 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6496 EResult = S.Owned( 6497 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6498 VK_RValue, Initializer, false)); 6499 } 6500 6501 Sema::AssignConvertType 6502 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6503 ExprResult &RHS) { 6504 QualType RHSType = RHS.get()->getType(); 6505 6506 // If the ArgType is a Union type, we want to handle a potential 6507 // transparent_union GCC extension. 6508 const RecordType *UT = ArgType->getAsUnionType(); 6509 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6510 return Incompatible; 6511 6512 // The field to initialize within the transparent union. 6513 RecordDecl *UD = UT->getDecl(); 6514 FieldDecl *InitField = 0; 6515 // It's compatible if the expression matches any of the fields. 6516 for (RecordDecl::field_iterator it = UD->field_begin(), 6517 itend = UD->field_end(); 6518 it != itend; ++it) { 6519 if (it->getType()->isPointerType()) { 6520 // If the transparent union contains a pointer type, we allow: 6521 // 1) void pointer 6522 // 2) null pointer constant 6523 if (RHSType->isPointerType()) 6524 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6525 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6526 InitField = *it; 6527 break; 6528 } 6529 6530 if (RHS.get()->isNullPointerConstant(Context, 6531 Expr::NPC_ValueDependentIsNull)) { 6532 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6533 CK_NullToPointer); 6534 InitField = *it; 6535 break; 6536 } 6537 } 6538 6539 CastKind Kind = CK_Invalid; 6540 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6541 == Compatible) { 6542 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6543 InitField = *it; 6544 break; 6545 } 6546 } 6547 6548 if (!InitField) 6549 return Incompatible; 6550 6551 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6552 return Compatible; 6553 } 6554 6555 Sema::AssignConvertType 6556 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6557 bool Diagnose, 6558 bool DiagnoseCFAudited) { 6559 if (getLangOpts().CPlusPlus) { 6560 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6561 // C++ 5.17p3: If the left operand is not of class type, the 6562 // expression is implicitly converted (C++ 4) to the 6563 // cv-unqualified type of the left operand. 6564 ExprResult Res; 6565 if (Diagnose) { 6566 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6567 AA_Assigning); 6568 } else { 6569 ImplicitConversionSequence ICS = 6570 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6571 /*SuppressUserConversions=*/false, 6572 /*AllowExplicit=*/false, 6573 /*InOverloadResolution=*/false, 6574 /*CStyle=*/false, 6575 /*AllowObjCWritebackConversion=*/false); 6576 if (ICS.isFailure()) 6577 return Incompatible; 6578 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6579 ICS, AA_Assigning); 6580 } 6581 if (Res.isInvalid()) 6582 return Incompatible; 6583 Sema::AssignConvertType result = Compatible; 6584 if (getLangOpts().ObjCAutoRefCount && 6585 !CheckObjCARCUnavailableWeakConversion(LHSType, 6586 RHS.get()->getType())) 6587 result = IncompatibleObjCWeakRef; 6588 RHS = Res; 6589 return result; 6590 } 6591 6592 // FIXME: Currently, we fall through and treat C++ classes like C 6593 // structures. 6594 // FIXME: We also fall through for atomics; not sure what should 6595 // happen there, though. 6596 } 6597 6598 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6599 // a null pointer constant. 6600 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 6601 LHSType->isBlockPointerType()) && 6602 RHS.get()->isNullPointerConstant(Context, 6603 Expr::NPC_ValueDependentIsNull)) { 6604 CastKind Kind; 6605 CXXCastPath Path; 6606 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 6607 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path); 6608 return Compatible; 6609 } 6610 6611 // This check seems unnatural, however it is necessary to ensure the proper 6612 // conversion of functions/arrays. If the conversion were done for all 6613 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6614 // expressions that suppress this implicit conversion (&, sizeof). 6615 // 6616 // Suppress this for references: C++ 8.5.3p5. 6617 if (!LHSType->isReferenceType()) { 6618 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6619 if (RHS.isInvalid()) 6620 return Incompatible; 6621 } 6622 6623 CastKind Kind = CK_Invalid; 6624 Sema::AssignConvertType result = 6625 CheckAssignmentConstraints(LHSType, RHS, Kind); 6626 6627 // C99 6.5.16.1p2: The value of the right operand is converted to the 6628 // type of the assignment expression. 6629 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6630 // so that we can use references in built-in functions even in C. 6631 // The getNonReferenceType() call makes sure that the resulting expression 6632 // does not have reference type. 6633 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6634 QualType Ty = LHSType.getNonLValueExprType(Context); 6635 Expr *E = RHS.take(); 6636 if (getLangOpts().ObjCAutoRefCount) 6637 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6638 DiagnoseCFAudited); 6639 if (getLangOpts().ObjC1 && 6640 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 6641 LHSType, E->getType(), E) || 6642 ConversionToObjCStringLiteralCheck(LHSType, E))) { 6643 RHS = Owned(E); 6644 return Compatible; 6645 } 6646 6647 RHS = ImpCastExprToType(E, Ty, Kind); 6648 } 6649 return result; 6650 } 6651 6652 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6653 ExprResult &RHS) { 6654 Diag(Loc, diag::err_typecheck_invalid_operands) 6655 << LHS.get()->getType() << RHS.get()->getType() 6656 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6657 return QualType(); 6658 } 6659 6660 static bool breakDownVectorType(QualType type, uint64_t &len, 6661 QualType &eltType) { 6662 // Vectors are simple. 6663 if (const VectorType *vecType = type->getAs<VectorType>()) { 6664 len = vecType->getNumElements(); 6665 eltType = vecType->getElementType(); 6666 assert(eltType->isScalarType()); 6667 return true; 6668 } 6669 6670 // We allow lax conversion to and from non-vector types, but only if 6671 // they're real types (i.e. non-complex, non-pointer scalar types). 6672 if (!type->isRealType()) return false; 6673 6674 len = 1; 6675 eltType = type; 6676 return true; 6677 } 6678 6679 /// Is this a legal conversion between two known vector types? 6680 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6681 assert(destTy->isVectorType() || srcTy->isVectorType()); 6682 6683 if (!Context.getLangOpts().LaxVectorConversions) 6684 return false; 6685 6686 uint64_t srcLen, destLen; 6687 QualType srcElt, destElt; 6688 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 6689 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 6690 6691 // ASTContext::getTypeSize will return the size rounded up to a 6692 // power of 2, so instead of using that, we need to use the raw 6693 // element size multiplied by the element count. 6694 uint64_t srcEltSize = Context.getTypeSize(srcElt); 6695 uint64_t destEltSize = Context.getTypeSize(destElt); 6696 6697 return (srcLen * srcEltSize == destLen * destEltSize); 6698 } 6699 6700 /// Try to convert a value of non-vector type to a vector type by 6701 /// promoting (and only promoting) the type to the element type of the 6702 /// vector and then performing a vector splat. 6703 /// 6704 /// \param scalar - if non-null, actually perform the conversions 6705 /// \return true if the operation fails (but without diagnosing the failure) 6706 static bool tryVectorPromoteAndSplat(Sema &S, ExprResult *scalar, 6707 QualType scalarTy, 6708 QualType vectorEltTy, 6709 QualType vectorTy) { 6710 // The conversion to apply to the scalar before splatting it, 6711 // if necessary. 6712 CastKind scalarCast = CK_Invalid; 6713 6714 if (vectorEltTy->isIntegralType(S.Context)) { 6715 if (!scalarTy->isIntegralType(S.Context)) return true; 6716 int order = S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy); 6717 if (order < 0) return true; 6718 if (order > 0) scalarCast = CK_IntegralCast; 6719 } else if (vectorEltTy->isRealFloatingType()) { 6720 if (scalarTy->isRealFloatingType()) { 6721 int order = S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy); 6722 if (order < 0) return true; 6723 if (order > 0) scalarCast = CK_FloatingCast; 6724 } else if (scalarTy->isIntegralType(S.Context)) { 6725 scalarCast = CK_IntegralToFloating; 6726 } else { 6727 return true; 6728 } 6729 } else { 6730 return true; 6731 } 6732 6733 // Adjust scalar if desired. 6734 if (scalar) { 6735 if (scalarCast != CK_Invalid) 6736 *scalar = S.ImpCastExprToType(scalar->take(), vectorEltTy, scalarCast); 6737 *scalar = S.ImpCastExprToType(scalar->take(), vectorTy, CK_VectorSplat); 6738 } 6739 return false; 6740 } 6741 6742 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6743 SourceLocation Loc, bool IsCompAssign) { 6744 if (!IsCompAssign) { 6745 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6746 if (LHS.isInvalid()) 6747 return QualType(); 6748 } 6749 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6750 if (RHS.isInvalid()) 6751 return QualType(); 6752 6753 // For conversion purposes, we ignore any qualifiers. 6754 // For example, "const float" and "float" are equivalent. 6755 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 6756 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 6757 6758 // If the vector types are identical, return. 6759 if (Context.hasSameType(LHSType, RHSType)) 6760 return LHSType; 6761 6762 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 6763 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 6764 assert(LHSVecType || RHSVecType); 6765 6766 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 6767 if (LHSVecType && RHSVecType && 6768 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6769 if (isa<ExtVectorType>(LHSVecType)) { 6770 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6771 return LHSType; 6772 } 6773 6774 if (!IsCompAssign) 6775 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6776 return RHSType; 6777 } 6778 6779 // If we're allowing lax vector conversions, only the total (data) size 6780 // needs to be the same. 6781 // FIXME: Should we really be allowing this? 6782 // FIXME: We really just pick the LHS type arbitrarily? 6783 if (isLaxVectorConversion(RHSType, LHSType)) { 6784 QualType resultType = LHSType; 6785 RHS = ImpCastExprToType(RHS.take(), resultType, CK_BitCast); 6786 return resultType; 6787 } 6788 6789 // If there's an ext-vector type and a scalar, try to promote (and 6790 // only promote) and splat the scalar to the vector type. 6791 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 6792 if (!tryVectorPromoteAndSplat(*this, &RHS, RHSType, 6793 LHSVecType->getElementType(), LHSType)) 6794 return LHSType; 6795 } 6796 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 6797 if (!tryVectorPromoteAndSplat(*this, (IsCompAssign ? 0 : &LHS), LHSType, 6798 RHSVecType->getElementType(), RHSType)) 6799 return RHSType; 6800 } 6801 6802 // Okay, the expression is invalid. 6803 6804 // If there's a non-vector, non-real operand, diagnose that. 6805 if ((!RHSVecType && !RHSType->isRealType()) || 6806 (!LHSVecType && !LHSType->isRealType())) { 6807 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 6808 << LHSType << RHSType 6809 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6810 return QualType(); 6811 } 6812 6813 // Otherwise, use the generic diagnostic. 6814 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6815 << LHSType << RHSType 6816 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6817 return QualType(); 6818 } 6819 6820 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6821 // expression. These are mainly cases where the null pointer is used as an 6822 // integer instead of a pointer. 6823 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6824 SourceLocation Loc, bool IsCompare) { 6825 // The canonical way to check for a GNU null is with isNullPointerConstant, 6826 // but we use a bit of a hack here for speed; this is a relatively 6827 // hot path, and isNullPointerConstant is slow. 6828 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6829 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6830 6831 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6832 6833 // Avoid analyzing cases where the result will either be invalid (and 6834 // diagnosed as such) or entirely valid and not something to warn about. 6835 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6836 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6837 return; 6838 6839 // Comparison operations would not make sense with a null pointer no matter 6840 // what the other expression is. 6841 if (!IsCompare) { 6842 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6843 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6844 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6845 return; 6846 } 6847 6848 // The rest of the operations only make sense with a null pointer 6849 // if the other expression is a pointer. 6850 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6851 NonNullType->canDecayToPointerType()) 6852 return; 6853 6854 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6855 << LHSNull /* LHS is NULL */ << NonNullType 6856 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6857 } 6858 6859 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6860 SourceLocation Loc, 6861 bool IsCompAssign, bool IsDiv) { 6862 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6863 6864 if (LHS.get()->getType()->isVectorType() || 6865 RHS.get()->getType()->isVectorType()) 6866 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6867 6868 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6869 if (LHS.isInvalid() || RHS.isInvalid()) 6870 return QualType(); 6871 6872 6873 if (compType.isNull() || !compType->isArithmeticType()) 6874 return InvalidOperands(Loc, LHS, RHS); 6875 6876 // Check for division by zero. 6877 llvm::APSInt RHSValue; 6878 if (IsDiv && !RHS.get()->isValueDependent() && 6879 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6880 DiagRuntimeBehavior(Loc, RHS.get(), 6881 PDiag(diag::warn_division_by_zero) 6882 << RHS.get()->getSourceRange()); 6883 6884 return compType; 6885 } 6886 6887 QualType Sema::CheckRemainderOperands( 6888 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6889 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6890 6891 if (LHS.get()->getType()->isVectorType() || 6892 RHS.get()->getType()->isVectorType()) { 6893 if (LHS.get()->getType()->hasIntegerRepresentation() && 6894 RHS.get()->getType()->hasIntegerRepresentation()) 6895 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6896 return InvalidOperands(Loc, LHS, RHS); 6897 } 6898 6899 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6900 if (LHS.isInvalid() || RHS.isInvalid()) 6901 return QualType(); 6902 6903 if (compType.isNull() || !compType->isIntegerType()) 6904 return InvalidOperands(Loc, LHS, RHS); 6905 6906 // Check for remainder by zero. 6907 llvm::APSInt RHSValue; 6908 if (!RHS.get()->isValueDependent() && 6909 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6910 DiagRuntimeBehavior(Loc, RHS.get(), 6911 PDiag(diag::warn_remainder_by_zero) 6912 << RHS.get()->getSourceRange()); 6913 6914 return compType; 6915 } 6916 6917 /// \brief Diagnose invalid arithmetic on two void pointers. 6918 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6919 Expr *LHSExpr, Expr *RHSExpr) { 6920 S.Diag(Loc, S.getLangOpts().CPlusPlus 6921 ? diag::err_typecheck_pointer_arith_void_type 6922 : diag::ext_gnu_void_ptr) 6923 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6924 << RHSExpr->getSourceRange(); 6925 } 6926 6927 /// \brief Diagnose invalid arithmetic on a void pointer. 6928 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6929 Expr *Pointer) { 6930 S.Diag(Loc, S.getLangOpts().CPlusPlus 6931 ? diag::err_typecheck_pointer_arith_void_type 6932 : diag::ext_gnu_void_ptr) 6933 << 0 /* one pointer */ << Pointer->getSourceRange(); 6934 } 6935 6936 /// \brief Diagnose invalid arithmetic on two function pointers. 6937 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6938 Expr *LHS, Expr *RHS) { 6939 assert(LHS->getType()->isAnyPointerType()); 6940 assert(RHS->getType()->isAnyPointerType()); 6941 S.Diag(Loc, S.getLangOpts().CPlusPlus 6942 ? diag::err_typecheck_pointer_arith_function_type 6943 : diag::ext_gnu_ptr_func_arith) 6944 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6945 // We only show the second type if it differs from the first. 6946 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6947 RHS->getType()) 6948 << RHS->getType()->getPointeeType() 6949 << LHS->getSourceRange() << RHS->getSourceRange(); 6950 } 6951 6952 /// \brief Diagnose invalid arithmetic on a function pointer. 6953 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6954 Expr *Pointer) { 6955 assert(Pointer->getType()->isAnyPointerType()); 6956 S.Diag(Loc, S.getLangOpts().CPlusPlus 6957 ? diag::err_typecheck_pointer_arith_function_type 6958 : diag::ext_gnu_ptr_func_arith) 6959 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6960 << 0 /* one pointer, so only one type */ 6961 << Pointer->getSourceRange(); 6962 } 6963 6964 /// \brief Emit error if Operand is incomplete pointer type 6965 /// 6966 /// \returns True if pointer has incomplete type 6967 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6968 Expr *Operand) { 6969 assert(Operand->getType()->isAnyPointerType() && 6970 !Operand->getType()->isDependentType()); 6971 QualType PointeeTy = Operand->getType()->getPointeeType(); 6972 return S.RequireCompleteType(Loc, PointeeTy, 6973 diag::err_typecheck_arithmetic_incomplete_type, 6974 PointeeTy, Operand->getSourceRange()); 6975 } 6976 6977 /// \brief Check the validity of an arithmetic pointer operand. 6978 /// 6979 /// If the operand has pointer type, this code will check for pointer types 6980 /// which are invalid in arithmetic operations. These will be diagnosed 6981 /// appropriately, including whether or not the use is supported as an 6982 /// extension. 6983 /// 6984 /// \returns True when the operand is valid to use (even if as an extension). 6985 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6986 Expr *Operand) { 6987 if (!Operand->getType()->isAnyPointerType()) return true; 6988 6989 QualType PointeeTy = Operand->getType()->getPointeeType(); 6990 if (PointeeTy->isVoidType()) { 6991 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6992 return !S.getLangOpts().CPlusPlus; 6993 } 6994 if (PointeeTy->isFunctionType()) { 6995 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6996 return !S.getLangOpts().CPlusPlus; 6997 } 6998 6999 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7000 7001 return true; 7002 } 7003 7004 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7005 /// operands. 7006 /// 7007 /// This routine will diagnose any invalid arithmetic on pointer operands much 7008 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7009 /// for emitting a single diagnostic even for operations where both LHS and RHS 7010 /// are (potentially problematic) pointers. 7011 /// 7012 /// \returns True when the operand is valid to use (even if as an extension). 7013 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7014 Expr *LHSExpr, Expr *RHSExpr) { 7015 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7016 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7017 if (!isLHSPointer && !isRHSPointer) return true; 7018 7019 QualType LHSPointeeTy, RHSPointeeTy; 7020 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7021 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7022 7023 // Check for arithmetic on pointers to incomplete types. 7024 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7025 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7026 if (isLHSVoidPtr || isRHSVoidPtr) { 7027 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7028 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7029 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7030 7031 return !S.getLangOpts().CPlusPlus; 7032 } 7033 7034 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7035 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7036 if (isLHSFuncPtr || isRHSFuncPtr) { 7037 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7038 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7039 RHSExpr); 7040 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7041 7042 return !S.getLangOpts().CPlusPlus; 7043 } 7044 7045 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7046 return false; 7047 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7048 return false; 7049 7050 return true; 7051 } 7052 7053 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7054 /// literal. 7055 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7056 Expr *LHSExpr, Expr *RHSExpr) { 7057 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7058 Expr* IndexExpr = RHSExpr; 7059 if (!StrExpr) { 7060 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7061 IndexExpr = LHSExpr; 7062 } 7063 7064 bool IsStringPlusInt = StrExpr && 7065 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7066 if (!IsStringPlusInt) 7067 return; 7068 7069 llvm::APSInt index; 7070 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7071 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7072 if (index.isNonNegative() && 7073 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7074 index.isUnsigned())) 7075 return; 7076 } 7077 7078 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7079 Self.Diag(OpLoc, diag::warn_string_plus_int) 7080 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7081 7082 // Only print a fixit for "str" + int, not for int + "str". 7083 if (IndexExpr == RHSExpr) { 7084 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7085 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7086 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7087 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7088 << FixItHint::CreateInsertion(EndLoc, "]"); 7089 } else 7090 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7091 } 7092 7093 /// \brief Emit a warning when adding a char literal to a string. 7094 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7095 Expr *LHSExpr, Expr *RHSExpr) { 7096 const DeclRefExpr *StringRefExpr = 7097 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts()); 7098 const CharacterLiteral *CharExpr = 7099 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7100 if (!StringRefExpr) { 7101 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts()); 7102 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7103 } 7104 7105 if (!CharExpr || !StringRefExpr) 7106 return; 7107 7108 const QualType StringType = StringRefExpr->getType(); 7109 7110 // Return if not a PointerType. 7111 if (!StringType->isAnyPointerType()) 7112 return; 7113 7114 // Return if not a CharacterType. 7115 if (!StringType->getPointeeType()->isAnyCharacterType()) 7116 return; 7117 7118 ASTContext &Ctx = Self.getASTContext(); 7119 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7120 7121 const QualType CharType = CharExpr->getType(); 7122 if (!CharType->isAnyCharacterType() && 7123 CharType->isIntegerType() && 7124 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7125 Self.Diag(OpLoc, diag::warn_string_plus_char) 7126 << DiagRange << Ctx.CharTy; 7127 } else { 7128 Self.Diag(OpLoc, diag::warn_string_plus_char) 7129 << DiagRange << CharExpr->getType(); 7130 } 7131 7132 // Only print a fixit for str + char, not for char + str. 7133 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7134 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7135 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7136 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7137 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7138 << FixItHint::CreateInsertion(EndLoc, "]"); 7139 } else { 7140 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7141 } 7142 } 7143 7144 /// \brief Emit error when two pointers are incompatible. 7145 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7146 Expr *LHSExpr, Expr *RHSExpr) { 7147 assert(LHSExpr->getType()->isAnyPointerType()); 7148 assert(RHSExpr->getType()->isAnyPointerType()); 7149 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7150 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7151 << RHSExpr->getSourceRange(); 7152 } 7153 7154 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7155 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7156 QualType* CompLHSTy) { 7157 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7158 7159 if (LHS.get()->getType()->isVectorType() || 7160 RHS.get()->getType()->isVectorType()) { 7161 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7162 if (CompLHSTy) *CompLHSTy = compType; 7163 return compType; 7164 } 7165 7166 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7167 if (LHS.isInvalid() || RHS.isInvalid()) 7168 return QualType(); 7169 7170 // Diagnose "string literal" '+' int and string '+' "char literal". 7171 if (Opc == BO_Add) { 7172 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7173 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7174 } 7175 7176 // handle the common case first (both operands are arithmetic). 7177 if (!compType.isNull() && compType->isArithmeticType()) { 7178 if (CompLHSTy) *CompLHSTy = compType; 7179 return compType; 7180 } 7181 7182 // Type-checking. Ultimately the pointer's going to be in PExp; 7183 // note that we bias towards the LHS being the pointer. 7184 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7185 7186 bool isObjCPointer; 7187 if (PExp->getType()->isPointerType()) { 7188 isObjCPointer = false; 7189 } else if (PExp->getType()->isObjCObjectPointerType()) { 7190 isObjCPointer = true; 7191 } else { 7192 std::swap(PExp, IExp); 7193 if (PExp->getType()->isPointerType()) { 7194 isObjCPointer = false; 7195 } else if (PExp->getType()->isObjCObjectPointerType()) { 7196 isObjCPointer = true; 7197 } else { 7198 return InvalidOperands(Loc, LHS, RHS); 7199 } 7200 } 7201 assert(PExp->getType()->isAnyPointerType()); 7202 7203 if (!IExp->getType()->isIntegerType()) 7204 return InvalidOperands(Loc, LHS, RHS); 7205 7206 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7207 return QualType(); 7208 7209 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7210 return QualType(); 7211 7212 // Check array bounds for pointer arithemtic 7213 CheckArrayAccess(PExp, IExp); 7214 7215 if (CompLHSTy) { 7216 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7217 if (LHSTy.isNull()) { 7218 LHSTy = LHS.get()->getType(); 7219 if (LHSTy->isPromotableIntegerType()) 7220 LHSTy = Context.getPromotedIntegerType(LHSTy); 7221 } 7222 *CompLHSTy = LHSTy; 7223 } 7224 7225 return PExp->getType(); 7226 } 7227 7228 // C99 6.5.6 7229 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7230 SourceLocation Loc, 7231 QualType* CompLHSTy) { 7232 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7233 7234 if (LHS.get()->getType()->isVectorType() || 7235 RHS.get()->getType()->isVectorType()) { 7236 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7237 if (CompLHSTy) *CompLHSTy = compType; 7238 return compType; 7239 } 7240 7241 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7242 if (LHS.isInvalid() || RHS.isInvalid()) 7243 return QualType(); 7244 7245 // Enforce type constraints: C99 6.5.6p3. 7246 7247 // Handle the common case first (both operands are arithmetic). 7248 if (!compType.isNull() && compType->isArithmeticType()) { 7249 if (CompLHSTy) *CompLHSTy = compType; 7250 return compType; 7251 } 7252 7253 // Either ptr - int or ptr - ptr. 7254 if (LHS.get()->getType()->isAnyPointerType()) { 7255 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7256 7257 // Diagnose bad cases where we step over interface counts. 7258 if (LHS.get()->getType()->isObjCObjectPointerType() && 7259 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7260 return QualType(); 7261 7262 // The result type of a pointer-int computation is the pointer type. 7263 if (RHS.get()->getType()->isIntegerType()) { 7264 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7265 return QualType(); 7266 7267 // Check array bounds for pointer arithemtic 7268 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 7269 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7270 7271 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7272 return LHS.get()->getType(); 7273 } 7274 7275 // Handle pointer-pointer subtractions. 7276 if (const PointerType *RHSPTy 7277 = RHS.get()->getType()->getAs<PointerType>()) { 7278 QualType rpointee = RHSPTy->getPointeeType(); 7279 7280 if (getLangOpts().CPlusPlus) { 7281 // Pointee types must be the same: C++ [expr.add] 7282 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7283 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7284 } 7285 } else { 7286 // Pointee types must be compatible C99 6.5.6p3 7287 if (!Context.typesAreCompatible( 7288 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7289 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7290 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7291 return QualType(); 7292 } 7293 } 7294 7295 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7296 LHS.get(), RHS.get())) 7297 return QualType(); 7298 7299 // The pointee type may have zero size. As an extension, a structure or 7300 // union may have zero size or an array may have zero length. In this 7301 // case subtraction does not make sense. 7302 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7303 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7304 if (ElementSize.isZero()) { 7305 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7306 << rpointee.getUnqualifiedType() 7307 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7308 } 7309 } 7310 7311 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7312 return Context.getPointerDiffType(); 7313 } 7314 } 7315 7316 return InvalidOperands(Loc, LHS, RHS); 7317 } 7318 7319 static bool isScopedEnumerationType(QualType T) { 7320 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7321 return ET->getDecl()->isScoped(); 7322 return false; 7323 } 7324 7325 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7326 SourceLocation Loc, unsigned Opc, 7327 QualType LHSType) { 7328 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7329 // so skip remaining warnings as we don't want to modify values within Sema. 7330 if (S.getLangOpts().OpenCL) 7331 return; 7332 7333 llvm::APSInt Right; 7334 // Check right/shifter operand 7335 if (RHS.get()->isValueDependent() || 7336 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7337 return; 7338 7339 if (Right.isNegative()) { 7340 S.DiagRuntimeBehavior(Loc, RHS.get(), 7341 S.PDiag(diag::warn_shift_negative) 7342 << RHS.get()->getSourceRange()); 7343 return; 7344 } 7345 llvm::APInt LeftBits(Right.getBitWidth(), 7346 S.Context.getTypeSize(LHS.get()->getType())); 7347 if (Right.uge(LeftBits)) { 7348 S.DiagRuntimeBehavior(Loc, RHS.get(), 7349 S.PDiag(diag::warn_shift_gt_typewidth) 7350 << RHS.get()->getSourceRange()); 7351 return; 7352 } 7353 if (Opc != BO_Shl) 7354 return; 7355 7356 // When left shifting an ICE which is signed, we can check for overflow which 7357 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7358 // integers have defined behavior modulo one more than the maximum value 7359 // representable in the result type, so never warn for those. 7360 llvm::APSInt Left; 7361 if (LHS.get()->isValueDependent() || 7362 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7363 LHSType->hasUnsignedIntegerRepresentation()) 7364 return; 7365 llvm::APInt ResultBits = 7366 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7367 if (LeftBits.uge(ResultBits)) 7368 return; 7369 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7370 Result = Result.shl(Right); 7371 7372 // Print the bit representation of the signed integer as an unsigned 7373 // hexadecimal number. 7374 SmallString<40> HexResult; 7375 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7376 7377 // If we are only missing a sign bit, this is less likely to result in actual 7378 // bugs -- if the result is cast back to an unsigned type, it will have the 7379 // expected value. Thus we place this behind a different warning that can be 7380 // turned off separately if needed. 7381 if (LeftBits == ResultBits - 1) { 7382 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7383 << HexResult.str() << LHSType 7384 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7385 return; 7386 } 7387 7388 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7389 << HexResult.str() << Result.getMinSignedBits() << LHSType 7390 << Left.getBitWidth() << LHS.get()->getSourceRange() 7391 << RHS.get()->getSourceRange(); 7392 } 7393 7394 // C99 6.5.7 7395 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7396 SourceLocation Loc, unsigned Opc, 7397 bool IsCompAssign) { 7398 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7399 7400 // Vector shifts promote their scalar inputs to vector type. 7401 if (LHS.get()->getType()->isVectorType() || 7402 RHS.get()->getType()->isVectorType()) 7403 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7404 7405 // Shifts don't perform usual arithmetic conversions, they just do integer 7406 // promotions on each operand. C99 6.5.7p3 7407 7408 // For the LHS, do usual unary conversions, but then reset them away 7409 // if this is a compound assignment. 7410 ExprResult OldLHS = LHS; 7411 LHS = UsualUnaryConversions(LHS.take()); 7412 if (LHS.isInvalid()) 7413 return QualType(); 7414 QualType LHSType = LHS.get()->getType(); 7415 if (IsCompAssign) LHS = OldLHS; 7416 7417 // The RHS is simpler. 7418 RHS = UsualUnaryConversions(RHS.take()); 7419 if (RHS.isInvalid()) 7420 return QualType(); 7421 QualType RHSType = RHS.get()->getType(); 7422 7423 // C99 6.5.7p2: Each of the operands shall have integer type. 7424 if (!LHSType->hasIntegerRepresentation() || 7425 !RHSType->hasIntegerRepresentation()) 7426 return InvalidOperands(Loc, LHS, RHS); 7427 7428 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7429 // hasIntegerRepresentation() above instead of this. 7430 if (isScopedEnumerationType(LHSType) || 7431 isScopedEnumerationType(RHSType)) { 7432 return InvalidOperands(Loc, LHS, RHS); 7433 } 7434 // Sanity-check shift operands 7435 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7436 7437 // "The type of the result is that of the promoted left operand." 7438 return LHSType; 7439 } 7440 7441 static bool IsWithinTemplateSpecialization(Decl *D) { 7442 if (DeclContext *DC = D->getDeclContext()) { 7443 if (isa<ClassTemplateSpecializationDecl>(DC)) 7444 return true; 7445 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7446 return FD->isFunctionTemplateSpecialization(); 7447 } 7448 return false; 7449 } 7450 7451 /// If two different enums are compared, raise a warning. 7452 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7453 Expr *RHS) { 7454 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7455 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7456 7457 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7458 if (!LHSEnumType) 7459 return; 7460 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7461 if (!RHSEnumType) 7462 return; 7463 7464 // Ignore anonymous enums. 7465 if (!LHSEnumType->getDecl()->getIdentifier()) 7466 return; 7467 if (!RHSEnumType->getDecl()->getIdentifier()) 7468 return; 7469 7470 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7471 return; 7472 7473 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7474 << LHSStrippedType << RHSStrippedType 7475 << LHS->getSourceRange() << RHS->getSourceRange(); 7476 } 7477 7478 /// \brief Diagnose bad pointer comparisons. 7479 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7480 ExprResult &LHS, ExprResult &RHS, 7481 bool IsError) { 7482 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7483 : diag::ext_typecheck_comparison_of_distinct_pointers) 7484 << LHS.get()->getType() << RHS.get()->getType() 7485 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7486 } 7487 7488 /// \brief Returns false if the pointers are converted to a composite type, 7489 /// true otherwise. 7490 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7491 ExprResult &LHS, ExprResult &RHS) { 7492 // C++ [expr.rel]p2: 7493 // [...] Pointer conversions (4.10) and qualification 7494 // conversions (4.4) are performed on pointer operands (or on 7495 // a pointer operand and a null pointer constant) to bring 7496 // them to their composite pointer type. [...] 7497 // 7498 // C++ [expr.eq]p1 uses the same notion for (in)equality 7499 // comparisons of pointers. 7500 7501 // C++ [expr.eq]p2: 7502 // In addition, pointers to members can be compared, or a pointer to 7503 // member and a null pointer constant. Pointer to member conversions 7504 // (4.11) and qualification conversions (4.4) are performed to bring 7505 // them to a common type. If one operand is a null pointer constant, 7506 // the common type is the type of the other operand. Otherwise, the 7507 // common type is a pointer to member type similar (4.4) to the type 7508 // of one of the operands, with a cv-qualification signature (4.4) 7509 // that is the union of the cv-qualification signatures of the operand 7510 // types. 7511 7512 QualType LHSType = LHS.get()->getType(); 7513 QualType RHSType = RHS.get()->getType(); 7514 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7515 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7516 7517 bool NonStandardCompositeType = false; 7518 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7519 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7520 if (T.isNull()) { 7521 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7522 return true; 7523 } 7524 7525 if (NonStandardCompositeType) 7526 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7527 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7528 << RHS.get()->getSourceRange(); 7529 7530 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7531 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7532 return false; 7533 } 7534 7535 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7536 ExprResult &LHS, 7537 ExprResult &RHS, 7538 bool IsError) { 7539 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7540 : diag::ext_typecheck_comparison_of_fptr_to_void) 7541 << LHS.get()->getType() << RHS.get()->getType() 7542 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7543 } 7544 7545 static bool isObjCObjectLiteral(ExprResult &E) { 7546 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7547 case Stmt::ObjCArrayLiteralClass: 7548 case Stmt::ObjCDictionaryLiteralClass: 7549 case Stmt::ObjCStringLiteralClass: 7550 case Stmt::ObjCBoxedExprClass: 7551 return true; 7552 default: 7553 // Note that ObjCBoolLiteral is NOT an object literal! 7554 return false; 7555 } 7556 } 7557 7558 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7559 const ObjCObjectPointerType *Type = 7560 LHS->getType()->getAs<ObjCObjectPointerType>(); 7561 7562 // If this is not actually an Objective-C object, bail out. 7563 if (!Type) 7564 return false; 7565 7566 // Get the LHS object's interface type. 7567 QualType InterfaceType = Type->getPointeeType(); 7568 if (const ObjCObjectType *iQFaceTy = 7569 InterfaceType->getAsObjCQualifiedInterfaceType()) 7570 InterfaceType = iQFaceTy->getBaseType(); 7571 7572 // If the RHS isn't an Objective-C object, bail out. 7573 if (!RHS->getType()->isObjCObjectPointerType()) 7574 return false; 7575 7576 // Try to find the -isEqual: method. 7577 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7578 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7579 InterfaceType, 7580 /*instance=*/true); 7581 if (!Method) { 7582 if (Type->isObjCIdType()) { 7583 // For 'id', just check the global pool. 7584 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7585 /*receiverId=*/true, 7586 /*warn=*/false); 7587 } else { 7588 // Check protocols. 7589 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7590 /*instance=*/true); 7591 } 7592 } 7593 7594 if (!Method) 7595 return false; 7596 7597 QualType T = Method->param_begin()[0]->getType(); 7598 if (!T->isObjCObjectPointerType()) 7599 return false; 7600 7601 QualType R = Method->getReturnType(); 7602 if (!R->isScalarType()) 7603 return false; 7604 7605 return true; 7606 } 7607 7608 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7609 FromE = FromE->IgnoreParenImpCasts(); 7610 switch (FromE->getStmtClass()) { 7611 default: 7612 break; 7613 case Stmt::ObjCStringLiteralClass: 7614 // "string literal" 7615 return LK_String; 7616 case Stmt::ObjCArrayLiteralClass: 7617 // "array literal" 7618 return LK_Array; 7619 case Stmt::ObjCDictionaryLiteralClass: 7620 // "dictionary literal" 7621 return LK_Dictionary; 7622 case Stmt::BlockExprClass: 7623 return LK_Block; 7624 case Stmt::ObjCBoxedExprClass: { 7625 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7626 switch (Inner->getStmtClass()) { 7627 case Stmt::IntegerLiteralClass: 7628 case Stmt::FloatingLiteralClass: 7629 case Stmt::CharacterLiteralClass: 7630 case Stmt::ObjCBoolLiteralExprClass: 7631 case Stmt::CXXBoolLiteralExprClass: 7632 // "numeric literal" 7633 return LK_Numeric; 7634 case Stmt::ImplicitCastExprClass: { 7635 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7636 // Boolean literals can be represented by implicit casts. 7637 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7638 return LK_Numeric; 7639 break; 7640 } 7641 default: 7642 break; 7643 } 7644 return LK_Boxed; 7645 } 7646 } 7647 return LK_None; 7648 } 7649 7650 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7651 ExprResult &LHS, ExprResult &RHS, 7652 BinaryOperator::Opcode Opc){ 7653 Expr *Literal; 7654 Expr *Other; 7655 if (isObjCObjectLiteral(LHS)) { 7656 Literal = LHS.get(); 7657 Other = RHS.get(); 7658 } else { 7659 Literal = RHS.get(); 7660 Other = LHS.get(); 7661 } 7662 7663 // Don't warn on comparisons against nil. 7664 Other = Other->IgnoreParenCasts(); 7665 if (Other->isNullPointerConstant(S.getASTContext(), 7666 Expr::NPC_ValueDependentIsNotNull)) 7667 return; 7668 7669 // This should be kept in sync with warn_objc_literal_comparison. 7670 // LK_String should always be after the other literals, since it has its own 7671 // warning flag. 7672 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7673 assert(LiteralKind != Sema::LK_Block); 7674 if (LiteralKind == Sema::LK_None) { 7675 llvm_unreachable("Unknown Objective-C object literal kind"); 7676 } 7677 7678 if (LiteralKind == Sema::LK_String) 7679 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7680 << Literal->getSourceRange(); 7681 else 7682 S.Diag(Loc, diag::warn_objc_literal_comparison) 7683 << LiteralKind << Literal->getSourceRange(); 7684 7685 if (BinaryOperator::isEqualityOp(Opc) && 7686 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7687 SourceLocation Start = LHS.get()->getLocStart(); 7688 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7689 CharSourceRange OpRange = 7690 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7691 7692 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7693 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7694 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7695 << FixItHint::CreateInsertion(End, "]"); 7696 } 7697 } 7698 7699 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7700 ExprResult &RHS, 7701 SourceLocation Loc, 7702 unsigned OpaqueOpc) { 7703 // This checking requires bools. 7704 if (!S.getLangOpts().Bool) return; 7705 7706 // Check that left hand side is !something. 7707 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7708 if (!UO || UO->getOpcode() != UO_LNot) return; 7709 7710 // Only check if the right hand side is non-bool arithmetic type. 7711 if (RHS.get()->getType()->isBooleanType()) return; 7712 7713 // Make sure that the something in !something is not bool. 7714 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7715 if (SubExpr->getType()->isBooleanType()) return; 7716 7717 // Emit warning. 7718 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7719 << Loc; 7720 7721 // First note suggest !(x < y) 7722 SourceLocation FirstOpen = SubExpr->getLocStart(); 7723 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7724 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7725 if (FirstClose.isInvalid()) 7726 FirstOpen = SourceLocation(); 7727 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7728 << FixItHint::CreateInsertion(FirstOpen, "(") 7729 << FixItHint::CreateInsertion(FirstClose, ")"); 7730 7731 // Second note suggests (!x) < y 7732 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7733 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7734 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7735 if (SecondClose.isInvalid()) 7736 SecondOpen = SourceLocation(); 7737 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7738 << FixItHint::CreateInsertion(SecondOpen, "(") 7739 << FixItHint::CreateInsertion(SecondClose, ")"); 7740 } 7741 7742 // Get the decl for a simple expression: a reference to a variable, 7743 // an implicit C++ field reference, or an implicit ObjC ivar reference. 7744 static ValueDecl *getCompareDecl(Expr *E) { 7745 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7746 return DR->getDecl(); 7747 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7748 if (Ivar->isFreeIvar()) 7749 return Ivar->getDecl(); 7750 } 7751 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7752 if (Mem->isImplicitAccess()) 7753 return Mem->getMemberDecl(); 7754 } 7755 return 0; 7756 } 7757 7758 // C99 6.5.8, C++ [expr.rel] 7759 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7760 SourceLocation Loc, unsigned OpaqueOpc, 7761 bool IsRelational) { 7762 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7763 7764 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7765 7766 // Handle vector comparisons separately. 7767 if (LHS.get()->getType()->isVectorType() || 7768 RHS.get()->getType()->isVectorType()) 7769 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7770 7771 QualType LHSType = LHS.get()->getType(); 7772 QualType RHSType = RHS.get()->getType(); 7773 7774 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7775 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7776 7777 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7778 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7779 7780 if (!LHSType->hasFloatingRepresentation() && 7781 !(LHSType->isBlockPointerType() && IsRelational) && 7782 !LHS.get()->getLocStart().isMacroID() && 7783 !RHS.get()->getLocStart().isMacroID() && 7784 ActiveTemplateInstantiations.empty()) { 7785 // For non-floating point types, check for self-comparisons of the form 7786 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7787 // often indicate logic errors in the program. 7788 // 7789 // NOTE: Don't warn about comparison expressions resulting from macro 7790 // expansion. Also don't warn about comparisons which are only self 7791 // comparisons within a template specialization. The warnings should catch 7792 // obvious cases in the definition of the template anyways. The idea is to 7793 // warn when the typed comparison operator will always evaluate to the same 7794 // result. 7795 ValueDecl *DL = getCompareDecl(LHSStripped); 7796 ValueDecl *DR = getCompareDecl(RHSStripped); 7797 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7798 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7799 << 0 // self- 7800 << (Opc == BO_EQ 7801 || Opc == BO_LE 7802 || Opc == BO_GE)); 7803 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7804 !DL->getType()->isReferenceType() && 7805 !DR->getType()->isReferenceType()) { 7806 // what is it always going to eval to? 7807 char always_evals_to; 7808 switch(Opc) { 7809 case BO_EQ: // e.g. array1 == array2 7810 always_evals_to = 0; // false 7811 break; 7812 case BO_NE: // e.g. array1 != array2 7813 always_evals_to = 1; // true 7814 break; 7815 default: 7816 // best we can say is 'a constant' 7817 always_evals_to = 2; // e.g. array1 <= array2 7818 break; 7819 } 7820 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7821 << 1 // array 7822 << always_evals_to); 7823 } 7824 7825 if (isa<CastExpr>(LHSStripped)) 7826 LHSStripped = LHSStripped->IgnoreParenCasts(); 7827 if (isa<CastExpr>(RHSStripped)) 7828 RHSStripped = RHSStripped->IgnoreParenCasts(); 7829 7830 // Warn about comparisons against a string constant (unless the other 7831 // operand is null), the user probably wants strcmp. 7832 Expr *literalString = 0; 7833 Expr *literalStringStripped = 0; 7834 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7835 !RHSStripped->isNullPointerConstant(Context, 7836 Expr::NPC_ValueDependentIsNull)) { 7837 literalString = LHS.get(); 7838 literalStringStripped = LHSStripped; 7839 } else if ((isa<StringLiteral>(RHSStripped) || 7840 isa<ObjCEncodeExpr>(RHSStripped)) && 7841 !LHSStripped->isNullPointerConstant(Context, 7842 Expr::NPC_ValueDependentIsNull)) { 7843 literalString = RHS.get(); 7844 literalStringStripped = RHSStripped; 7845 } 7846 7847 if (literalString) { 7848 DiagRuntimeBehavior(Loc, 0, 7849 PDiag(diag::warn_stringcompare) 7850 << isa<ObjCEncodeExpr>(literalStringStripped) 7851 << literalString->getSourceRange()); 7852 } 7853 } 7854 7855 // C99 6.5.8p3 / C99 6.5.9p4 7856 UsualArithmeticConversions(LHS, RHS); 7857 if (LHS.isInvalid() || RHS.isInvalid()) 7858 return QualType(); 7859 7860 LHSType = LHS.get()->getType(); 7861 RHSType = RHS.get()->getType(); 7862 7863 // The result of comparisons is 'bool' in C++, 'int' in C. 7864 QualType ResultTy = Context.getLogicalOperationType(); 7865 7866 if (IsRelational) { 7867 if (LHSType->isRealType() && RHSType->isRealType()) 7868 return ResultTy; 7869 } else { 7870 // Check for comparisons of floating point operands using != and ==. 7871 if (LHSType->hasFloatingRepresentation()) 7872 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7873 7874 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7875 return ResultTy; 7876 } 7877 7878 const Expr::NullPointerConstantKind LHSNullKind = 7879 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7880 const Expr::NullPointerConstantKind RHSNullKind = 7881 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7882 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 7883 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 7884 7885 if (!IsRelational && LHSIsNull != RHSIsNull) { 7886 bool IsEquality = Opc == BO_EQ; 7887 if (RHSIsNull) 7888 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 7889 RHS.get()->getSourceRange()); 7890 else 7891 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 7892 LHS.get()->getSourceRange()); 7893 } 7894 7895 // All of the following pointer-related warnings are GCC extensions, except 7896 // when handling null pointer constants. 7897 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7898 QualType LCanPointeeTy = 7899 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7900 QualType RCanPointeeTy = 7901 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7902 7903 if (getLangOpts().CPlusPlus) { 7904 if (LCanPointeeTy == RCanPointeeTy) 7905 return ResultTy; 7906 if (!IsRelational && 7907 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7908 // Valid unless comparison between non-null pointer and function pointer 7909 // This is a gcc extension compatibility comparison. 7910 // In a SFINAE context, we treat this as a hard error to maintain 7911 // conformance with the C++ standard. 7912 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7913 && !LHSIsNull && !RHSIsNull) { 7914 diagnoseFunctionPointerToVoidComparison( 7915 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7916 7917 if (isSFINAEContext()) 7918 return QualType(); 7919 7920 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7921 return ResultTy; 7922 } 7923 } 7924 7925 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7926 return QualType(); 7927 else 7928 return ResultTy; 7929 } 7930 // C99 6.5.9p2 and C99 6.5.8p2 7931 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7932 RCanPointeeTy.getUnqualifiedType())) { 7933 // Valid unless a relational comparison of function pointers 7934 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7935 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7936 << LHSType << RHSType << LHS.get()->getSourceRange() 7937 << RHS.get()->getSourceRange(); 7938 } 7939 } else if (!IsRelational && 7940 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7941 // Valid unless comparison between non-null pointer and function pointer 7942 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7943 && !LHSIsNull && !RHSIsNull) 7944 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7945 /*isError*/false); 7946 } else { 7947 // Invalid 7948 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7949 } 7950 if (LCanPointeeTy != RCanPointeeTy) { 7951 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 7952 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 7953 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 7954 : CK_BitCast; 7955 if (LHSIsNull && !RHSIsNull) 7956 LHS = ImpCastExprToType(LHS.take(), RHSType, Kind); 7957 else 7958 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind); 7959 } 7960 return ResultTy; 7961 } 7962 7963 if (getLangOpts().CPlusPlus) { 7964 // Comparison of nullptr_t with itself. 7965 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7966 return ResultTy; 7967 7968 // Comparison of pointers with null pointer constants and equality 7969 // comparisons of member pointers to null pointer constants. 7970 if (RHSIsNull && 7971 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7972 (!IsRelational && 7973 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7974 RHS = ImpCastExprToType(RHS.take(), LHSType, 7975 LHSType->isMemberPointerType() 7976 ? CK_NullToMemberPointer 7977 : CK_NullToPointer); 7978 return ResultTy; 7979 } 7980 if (LHSIsNull && 7981 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7982 (!IsRelational && 7983 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7984 LHS = ImpCastExprToType(LHS.take(), RHSType, 7985 RHSType->isMemberPointerType() 7986 ? CK_NullToMemberPointer 7987 : CK_NullToPointer); 7988 return ResultTy; 7989 } 7990 7991 // Comparison of member pointers. 7992 if (!IsRelational && 7993 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7994 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7995 return QualType(); 7996 else 7997 return ResultTy; 7998 } 7999 8000 // Handle scoped enumeration types specifically, since they don't promote 8001 // to integers. 8002 if (LHS.get()->getType()->isEnumeralType() && 8003 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8004 RHS.get()->getType())) 8005 return ResultTy; 8006 } 8007 8008 // Handle block pointer types. 8009 if (!IsRelational && LHSType->isBlockPointerType() && 8010 RHSType->isBlockPointerType()) { 8011 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8012 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8013 8014 if (!LHSIsNull && !RHSIsNull && 8015 !Context.typesAreCompatible(lpointee, rpointee)) { 8016 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8017 << LHSType << RHSType << LHS.get()->getSourceRange() 8018 << RHS.get()->getSourceRange(); 8019 } 8020 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 8021 return ResultTy; 8022 } 8023 8024 // Allow block pointers to be compared with null pointer constants. 8025 if (!IsRelational 8026 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8027 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8028 if (!LHSIsNull && !RHSIsNull) { 8029 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8030 ->getPointeeType()->isVoidType()) 8031 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8032 ->getPointeeType()->isVoidType()))) 8033 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8034 << LHSType << RHSType << LHS.get()->getSourceRange() 8035 << RHS.get()->getSourceRange(); 8036 } 8037 if (LHSIsNull && !RHSIsNull) 8038 LHS = ImpCastExprToType(LHS.take(), RHSType, 8039 RHSType->isPointerType() ? CK_BitCast 8040 : CK_AnyPointerToBlockPointerCast); 8041 else 8042 RHS = ImpCastExprToType(RHS.take(), LHSType, 8043 LHSType->isPointerType() ? CK_BitCast 8044 : CK_AnyPointerToBlockPointerCast); 8045 return ResultTy; 8046 } 8047 8048 if (LHSType->isObjCObjectPointerType() || 8049 RHSType->isObjCObjectPointerType()) { 8050 const PointerType *LPT = LHSType->getAs<PointerType>(); 8051 const PointerType *RPT = RHSType->getAs<PointerType>(); 8052 if (LPT || RPT) { 8053 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8054 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8055 8056 if (!LPtrToVoid && !RPtrToVoid && 8057 !Context.typesAreCompatible(LHSType, RHSType)) { 8058 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8059 /*isError*/false); 8060 } 8061 if (LHSIsNull && !RHSIsNull) { 8062 Expr *E = LHS.take(); 8063 if (getLangOpts().ObjCAutoRefCount) 8064 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8065 LHS = ImpCastExprToType(E, RHSType, 8066 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8067 } 8068 else { 8069 Expr *E = RHS.take(); 8070 if (getLangOpts().ObjCAutoRefCount) 8071 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion); 8072 RHS = ImpCastExprToType(E, LHSType, 8073 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8074 } 8075 return ResultTy; 8076 } 8077 if (LHSType->isObjCObjectPointerType() && 8078 RHSType->isObjCObjectPointerType()) { 8079 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8080 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8081 /*isError*/false); 8082 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8083 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8084 8085 if (LHSIsNull && !RHSIsNull) 8086 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 8087 else 8088 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 8089 return ResultTy; 8090 } 8091 } 8092 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8093 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8094 unsigned DiagID = 0; 8095 bool isError = false; 8096 if (LangOpts.DebuggerSupport) { 8097 // Under a debugger, allow the comparison of pointers to integers, 8098 // since users tend to want to compare addresses. 8099 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8100 (RHSIsNull && RHSType->isIntegerType())) { 8101 if (IsRelational && !getLangOpts().CPlusPlus) 8102 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8103 } else if (IsRelational && !getLangOpts().CPlusPlus) 8104 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8105 else if (getLangOpts().CPlusPlus) { 8106 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8107 isError = true; 8108 } else 8109 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8110 8111 if (DiagID) { 8112 Diag(Loc, DiagID) 8113 << LHSType << RHSType << LHS.get()->getSourceRange() 8114 << RHS.get()->getSourceRange(); 8115 if (isError) 8116 return QualType(); 8117 } 8118 8119 if (LHSType->isIntegerType()) 8120 LHS = ImpCastExprToType(LHS.take(), RHSType, 8121 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8122 else 8123 RHS = ImpCastExprToType(RHS.take(), LHSType, 8124 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8125 return ResultTy; 8126 } 8127 8128 // Handle block pointers. 8129 if (!IsRelational && RHSIsNull 8130 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8131 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 8132 return ResultTy; 8133 } 8134 if (!IsRelational && LHSIsNull 8135 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8136 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 8137 return ResultTy; 8138 } 8139 8140 return InvalidOperands(Loc, LHS, RHS); 8141 } 8142 8143 8144 // Return a signed type that is of identical size and number of elements. 8145 // For floating point vectors, return an integer type of identical size 8146 // and number of elements. 8147 QualType Sema::GetSignedVectorType(QualType V) { 8148 const VectorType *VTy = V->getAs<VectorType>(); 8149 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8150 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8151 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8152 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8153 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8154 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8155 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8156 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8157 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8158 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8159 "Unhandled vector element size in vector compare"); 8160 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8161 } 8162 8163 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 8164 /// operates on extended vector types. Instead of producing an IntTy result, 8165 /// like a scalar comparison, a vector comparison produces a vector of integer 8166 /// types. 8167 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8168 SourceLocation Loc, 8169 bool IsRelational) { 8170 // Check to make sure we're operating on vectors of the same type and width, 8171 // Allowing one side to be a scalar of element type. 8172 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8173 if (vType.isNull()) 8174 return vType; 8175 8176 QualType LHSType = LHS.get()->getType(); 8177 8178 // If AltiVec, the comparison results in a numeric type, i.e. 8179 // bool for C++, int for C 8180 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8181 return Context.getLogicalOperationType(); 8182 8183 // For non-floating point types, check for self-comparisons of the form 8184 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8185 // often indicate logic errors in the program. 8186 if (!LHSType->hasFloatingRepresentation() && 8187 ActiveTemplateInstantiations.empty()) { 8188 if (DeclRefExpr* DRL 8189 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8190 if (DeclRefExpr* DRR 8191 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8192 if (DRL->getDecl() == DRR->getDecl()) 8193 DiagRuntimeBehavior(Loc, 0, 8194 PDiag(diag::warn_comparison_always) 8195 << 0 // self- 8196 << 2 // "a constant" 8197 ); 8198 } 8199 8200 // Check for comparisons of floating point operands using != and ==. 8201 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8202 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8203 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8204 } 8205 8206 // Return a signed type for the vector. 8207 return GetSignedVectorType(LHSType); 8208 } 8209 8210 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8211 SourceLocation Loc) { 8212 // Ensure that either both operands are of the same vector type, or 8213 // one operand is of a vector type and the other is of its element type. 8214 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8215 if (vType.isNull()) 8216 return InvalidOperands(Loc, LHS, RHS); 8217 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8218 vType->hasFloatingRepresentation()) 8219 return InvalidOperands(Loc, LHS, RHS); 8220 8221 return GetSignedVectorType(LHS.get()->getType()); 8222 } 8223 8224 inline QualType Sema::CheckBitwiseOperands( 8225 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8226 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8227 8228 if (LHS.get()->getType()->isVectorType() || 8229 RHS.get()->getType()->isVectorType()) { 8230 if (LHS.get()->getType()->hasIntegerRepresentation() && 8231 RHS.get()->getType()->hasIntegerRepresentation()) 8232 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8233 8234 return InvalidOperands(Loc, LHS, RHS); 8235 } 8236 8237 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 8238 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8239 IsCompAssign); 8240 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8241 return QualType(); 8242 LHS = LHSResult.take(); 8243 RHS = RHSResult.take(); 8244 8245 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8246 return compType; 8247 return InvalidOperands(Loc, LHS, RHS); 8248 } 8249 8250 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8251 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8252 8253 // Check vector operands differently. 8254 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8255 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8256 8257 // Diagnose cases where the user write a logical and/or but probably meant a 8258 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8259 // is a constant. 8260 if (LHS.get()->getType()->isIntegerType() && 8261 !LHS.get()->getType()->isBooleanType() && 8262 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8263 // Don't warn in macros or template instantiations. 8264 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8265 // If the RHS can be constant folded, and if it constant folds to something 8266 // that isn't 0 or 1 (which indicate a potential logical operation that 8267 // happened to fold to true/false) then warn. 8268 // Parens on the RHS are ignored. 8269 llvm::APSInt Result; 8270 if (RHS.get()->EvaluateAsInt(Result, Context)) 8271 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 8272 (Result != 0 && Result != 1)) { 8273 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8274 << RHS.get()->getSourceRange() 8275 << (Opc == BO_LAnd ? "&&" : "||"); 8276 // Suggest replacing the logical operator with the bitwise version 8277 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8278 << (Opc == BO_LAnd ? "&" : "|") 8279 << FixItHint::CreateReplacement(SourceRange( 8280 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8281 getLangOpts())), 8282 Opc == BO_LAnd ? "&" : "|"); 8283 if (Opc == BO_LAnd) 8284 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8285 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8286 << FixItHint::CreateRemoval( 8287 SourceRange( 8288 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8289 0, getSourceManager(), 8290 getLangOpts()), 8291 RHS.get()->getLocEnd())); 8292 } 8293 } 8294 8295 if (!Context.getLangOpts().CPlusPlus) { 8296 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8297 // not operate on the built-in scalar and vector float types. 8298 if (Context.getLangOpts().OpenCL && 8299 Context.getLangOpts().OpenCLVersion < 120) { 8300 if (LHS.get()->getType()->isFloatingType() || 8301 RHS.get()->getType()->isFloatingType()) 8302 return InvalidOperands(Loc, LHS, RHS); 8303 } 8304 8305 LHS = UsualUnaryConversions(LHS.take()); 8306 if (LHS.isInvalid()) 8307 return QualType(); 8308 8309 RHS = UsualUnaryConversions(RHS.take()); 8310 if (RHS.isInvalid()) 8311 return QualType(); 8312 8313 if (!LHS.get()->getType()->isScalarType() || 8314 !RHS.get()->getType()->isScalarType()) 8315 return InvalidOperands(Loc, LHS, RHS); 8316 8317 return Context.IntTy; 8318 } 8319 8320 // The following is safe because we only use this method for 8321 // non-overloadable operands. 8322 8323 // C++ [expr.log.and]p1 8324 // C++ [expr.log.or]p1 8325 // The operands are both contextually converted to type bool. 8326 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8327 if (LHSRes.isInvalid()) 8328 return InvalidOperands(Loc, LHS, RHS); 8329 LHS = LHSRes; 8330 8331 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8332 if (RHSRes.isInvalid()) 8333 return InvalidOperands(Loc, LHS, RHS); 8334 RHS = RHSRes; 8335 8336 // C++ [expr.log.and]p2 8337 // C++ [expr.log.or]p2 8338 // The result is a bool. 8339 return Context.BoolTy; 8340 } 8341 8342 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8343 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8344 if (!ME) return false; 8345 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8346 ObjCMessageExpr *Base = 8347 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8348 if (!Base) return false; 8349 return Base->getMethodDecl() != 0; 8350 } 8351 8352 /// Is the given expression (which must be 'const') a reference to a 8353 /// variable which was originally non-const, but which has become 8354 /// 'const' due to being captured within a block? 8355 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8356 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8357 assert(E->isLValue() && E->getType().isConstQualified()); 8358 E = E->IgnoreParens(); 8359 8360 // Must be a reference to a declaration from an enclosing scope. 8361 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8362 if (!DRE) return NCCK_None; 8363 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8364 8365 // The declaration must be a variable which is not declared 'const'. 8366 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8367 if (!var) return NCCK_None; 8368 if (var->getType().isConstQualified()) return NCCK_None; 8369 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8370 8371 // Decide whether the first capture was for a block or a lambda. 8372 DeclContext *DC = S.CurContext, *Prev = 0; 8373 while (DC != var->getDeclContext()) { 8374 Prev = DC; 8375 DC = DC->getParent(); 8376 } 8377 // Unless we have an init-capture, we've gone one step too far. 8378 if (!var->isInitCapture()) 8379 DC = Prev; 8380 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8381 } 8382 8383 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8384 /// emit an error and return true. If so, return false. 8385 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8386 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8387 SourceLocation OrigLoc = Loc; 8388 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8389 &Loc); 8390 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8391 IsLV = Expr::MLV_InvalidMessageExpression; 8392 if (IsLV == Expr::MLV_Valid) 8393 return false; 8394 8395 unsigned Diag = 0; 8396 bool NeedType = false; 8397 switch (IsLV) { // C99 6.5.16p2 8398 case Expr::MLV_ConstQualified: 8399 Diag = diag::err_typecheck_assign_const; 8400 8401 // Use a specialized diagnostic when we're assigning to an object 8402 // from an enclosing function or block. 8403 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8404 if (NCCK == NCCK_Block) 8405 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8406 else 8407 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8408 break; 8409 } 8410 8411 // In ARC, use some specialized diagnostics for occasions where we 8412 // infer 'const'. These are always pseudo-strong variables. 8413 if (S.getLangOpts().ObjCAutoRefCount) { 8414 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8415 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8416 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8417 8418 // Use the normal diagnostic if it's pseudo-__strong but the 8419 // user actually wrote 'const'. 8420 if (var->isARCPseudoStrong() && 8421 (!var->getTypeSourceInfo() || 8422 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8423 // There are two pseudo-strong cases: 8424 // - self 8425 ObjCMethodDecl *method = S.getCurMethodDecl(); 8426 if (method && var == method->getSelfDecl()) 8427 Diag = method->isClassMethod() 8428 ? diag::err_typecheck_arc_assign_self_class_method 8429 : diag::err_typecheck_arc_assign_self; 8430 8431 // - fast enumeration variables 8432 else 8433 Diag = diag::err_typecheck_arr_assign_enumeration; 8434 8435 SourceRange Assign; 8436 if (Loc != OrigLoc) 8437 Assign = SourceRange(OrigLoc, OrigLoc); 8438 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8439 // We need to preserve the AST regardless, so migration tool 8440 // can do its job. 8441 return false; 8442 } 8443 } 8444 } 8445 8446 break; 8447 case Expr::MLV_ArrayType: 8448 case Expr::MLV_ArrayTemporary: 8449 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8450 NeedType = true; 8451 break; 8452 case Expr::MLV_NotObjectType: 8453 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8454 NeedType = true; 8455 break; 8456 case Expr::MLV_LValueCast: 8457 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8458 break; 8459 case Expr::MLV_Valid: 8460 llvm_unreachable("did not take early return for MLV_Valid"); 8461 case Expr::MLV_InvalidExpression: 8462 case Expr::MLV_MemberFunction: 8463 case Expr::MLV_ClassTemporary: 8464 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8465 break; 8466 case Expr::MLV_IncompleteType: 8467 case Expr::MLV_IncompleteVoidType: 8468 return S.RequireCompleteType(Loc, E->getType(), 8469 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8470 case Expr::MLV_DuplicateVectorComponents: 8471 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8472 break; 8473 case Expr::MLV_NoSetterProperty: 8474 llvm_unreachable("readonly properties should be processed differently"); 8475 case Expr::MLV_InvalidMessageExpression: 8476 Diag = diag::error_readonly_message_assignment; 8477 break; 8478 case Expr::MLV_SubObjCPropertySetting: 8479 Diag = diag::error_no_subobject_property_setting; 8480 break; 8481 } 8482 8483 SourceRange Assign; 8484 if (Loc != OrigLoc) 8485 Assign = SourceRange(OrigLoc, OrigLoc); 8486 if (NeedType) 8487 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8488 else 8489 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8490 return true; 8491 } 8492 8493 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8494 SourceLocation Loc, 8495 Sema &Sema) { 8496 // C / C++ fields 8497 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8498 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8499 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8500 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8501 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8502 } 8503 8504 // Objective-C instance variables 8505 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8506 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8507 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8508 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8509 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8510 if (RL && RR && RL->getDecl() == RR->getDecl()) 8511 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8512 } 8513 } 8514 8515 // C99 6.5.16.1 8516 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8517 SourceLocation Loc, 8518 QualType CompoundType) { 8519 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8520 8521 // Verify that LHS is a modifiable lvalue, and emit error if not. 8522 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8523 return QualType(); 8524 8525 QualType LHSType = LHSExpr->getType(); 8526 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8527 CompoundType; 8528 AssignConvertType ConvTy; 8529 if (CompoundType.isNull()) { 8530 Expr *RHSCheck = RHS.get(); 8531 8532 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8533 8534 QualType LHSTy(LHSType); 8535 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8536 if (RHS.isInvalid()) 8537 return QualType(); 8538 // Special case of NSObject attributes on c-style pointer types. 8539 if (ConvTy == IncompatiblePointer && 8540 ((Context.isObjCNSObjectType(LHSType) && 8541 RHSType->isObjCObjectPointerType()) || 8542 (Context.isObjCNSObjectType(RHSType) && 8543 LHSType->isObjCObjectPointerType()))) 8544 ConvTy = Compatible; 8545 8546 if (ConvTy == Compatible && 8547 LHSType->isObjCObjectType()) 8548 Diag(Loc, diag::err_objc_object_assignment) 8549 << LHSType; 8550 8551 // If the RHS is a unary plus or minus, check to see if they = and + are 8552 // right next to each other. If so, the user may have typo'd "x =+ 4" 8553 // instead of "x += 4". 8554 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8555 RHSCheck = ICE->getSubExpr(); 8556 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8557 if ((UO->getOpcode() == UO_Plus || 8558 UO->getOpcode() == UO_Minus) && 8559 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8560 // Only if the two operators are exactly adjacent. 8561 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8562 // And there is a space or other character before the subexpr of the 8563 // unary +/-. We don't want to warn on "x=-1". 8564 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8565 UO->getSubExpr()->getLocStart().isFileID()) { 8566 Diag(Loc, diag::warn_not_compound_assign) 8567 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8568 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8569 } 8570 } 8571 8572 if (ConvTy == Compatible) { 8573 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8574 // Warn about retain cycles where a block captures the LHS, but 8575 // not if the LHS is a simple variable into which the block is 8576 // being stored...unless that variable can be captured by reference! 8577 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8578 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8579 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8580 checkRetainCycles(LHSExpr, RHS.get()); 8581 8582 // It is safe to assign a weak reference into a strong variable. 8583 // Although this code can still have problems: 8584 // id x = self.weakProp; 8585 // id y = self.weakProp; 8586 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8587 // paths through the function. This should be revisited if 8588 // -Wrepeated-use-of-weak is made flow-sensitive. 8589 DiagnosticsEngine::Level Level = 8590 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8591 RHS.get()->getLocStart()); 8592 if (Level != DiagnosticsEngine::Ignored) 8593 getCurFunction()->markSafeWeakUse(RHS.get()); 8594 8595 } else if (getLangOpts().ObjCAutoRefCount) { 8596 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8597 } 8598 } 8599 } else { 8600 // Compound assignment "x += y" 8601 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8602 } 8603 8604 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8605 RHS.get(), AA_Assigning)) 8606 return QualType(); 8607 8608 CheckForNullPointerDereference(*this, LHSExpr); 8609 8610 // C99 6.5.16p3: The type of an assignment expression is the type of the 8611 // left operand unless the left operand has qualified type, in which case 8612 // it is the unqualified version of the type of the left operand. 8613 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8614 // is converted to the type of the assignment expression (above). 8615 // C++ 5.17p1: the type of the assignment expression is that of its left 8616 // operand. 8617 return (getLangOpts().CPlusPlus 8618 ? LHSType : LHSType.getUnqualifiedType()); 8619 } 8620 8621 // C99 6.5.17 8622 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8623 SourceLocation Loc) { 8624 LHS = S.CheckPlaceholderExpr(LHS.take()); 8625 RHS = S.CheckPlaceholderExpr(RHS.take()); 8626 if (LHS.isInvalid() || RHS.isInvalid()) 8627 return QualType(); 8628 8629 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8630 // operands, but not unary promotions. 8631 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8632 8633 // So we treat the LHS as a ignored value, and in C++ we allow the 8634 // containing site to determine what should be done with the RHS. 8635 LHS = S.IgnoredValueConversions(LHS.take()); 8636 if (LHS.isInvalid()) 8637 return QualType(); 8638 8639 S.DiagnoseUnusedExprResult(LHS.get()); 8640 8641 if (!S.getLangOpts().CPlusPlus) { 8642 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8643 if (RHS.isInvalid()) 8644 return QualType(); 8645 if (!RHS.get()->getType()->isVoidType()) 8646 S.RequireCompleteType(Loc, RHS.get()->getType(), 8647 diag::err_incomplete_type); 8648 } 8649 8650 return RHS.get()->getType(); 8651 } 8652 8653 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8654 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8655 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8656 ExprValueKind &VK, 8657 SourceLocation OpLoc, 8658 bool IsInc, bool IsPrefix) { 8659 if (Op->isTypeDependent()) 8660 return S.Context.DependentTy; 8661 8662 QualType ResType = Op->getType(); 8663 // Atomic types can be used for increment / decrement where the non-atomic 8664 // versions can, so ignore the _Atomic() specifier for the purpose of 8665 // checking. 8666 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8667 ResType = ResAtomicType->getValueType(); 8668 8669 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8670 8671 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8672 // Decrement of bool is not allowed. 8673 if (!IsInc) { 8674 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8675 return QualType(); 8676 } 8677 // Increment of bool sets it to true, but is deprecated. 8678 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8679 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8680 // Error on enum increments and decrements in C++ mode 8681 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8682 return QualType(); 8683 } else if (ResType->isRealType()) { 8684 // OK! 8685 } else if (ResType->isPointerType()) { 8686 // C99 6.5.2.4p2, 6.5.6p2 8687 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8688 return QualType(); 8689 } else if (ResType->isObjCObjectPointerType()) { 8690 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8691 // Otherwise, we just need a complete type. 8692 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8693 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8694 return QualType(); 8695 } else if (ResType->isAnyComplexType()) { 8696 // C99 does not support ++/-- on complex types, we allow as an extension. 8697 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8698 << ResType << Op->getSourceRange(); 8699 } else if (ResType->isPlaceholderType()) { 8700 ExprResult PR = S.CheckPlaceholderExpr(Op); 8701 if (PR.isInvalid()) return QualType(); 8702 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8703 IsInc, IsPrefix); 8704 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8705 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8706 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8707 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8708 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8709 } else { 8710 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8711 << ResType << int(IsInc) << Op->getSourceRange(); 8712 return QualType(); 8713 } 8714 // At this point, we know we have a real, complex or pointer type. 8715 // Now make sure the operand is a modifiable lvalue. 8716 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8717 return QualType(); 8718 // In C++, a prefix increment is the same type as the operand. Otherwise 8719 // (in C or with postfix), the increment is the unqualified type of the 8720 // operand. 8721 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8722 VK = VK_LValue; 8723 return ResType; 8724 } else { 8725 VK = VK_RValue; 8726 return ResType.getUnqualifiedType(); 8727 } 8728 } 8729 8730 8731 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8732 /// This routine allows us to typecheck complex/recursive expressions 8733 /// where the declaration is needed for type checking. We only need to 8734 /// handle cases when the expression references a function designator 8735 /// or is an lvalue. Here are some examples: 8736 /// - &(x) => x 8737 /// - &*****f => f for f a function designator. 8738 /// - &s.xx => s 8739 /// - &s.zz[1].yy -> s, if zz is an array 8740 /// - *(x + 1) -> x, if x is an array 8741 /// - &"123"[2] -> 0 8742 /// - & __real__ x -> x 8743 static ValueDecl *getPrimaryDecl(Expr *E) { 8744 switch (E->getStmtClass()) { 8745 case Stmt::DeclRefExprClass: 8746 return cast<DeclRefExpr>(E)->getDecl(); 8747 case Stmt::MemberExprClass: 8748 // If this is an arrow operator, the address is an offset from 8749 // the base's value, so the object the base refers to is 8750 // irrelevant. 8751 if (cast<MemberExpr>(E)->isArrow()) 8752 return 0; 8753 // Otherwise, the expression refers to a part of the base 8754 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8755 case Stmt::ArraySubscriptExprClass: { 8756 // FIXME: This code shouldn't be necessary! We should catch the implicit 8757 // promotion of register arrays earlier. 8758 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8759 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8760 if (ICE->getSubExpr()->getType()->isArrayType()) 8761 return getPrimaryDecl(ICE->getSubExpr()); 8762 } 8763 return 0; 8764 } 8765 case Stmt::UnaryOperatorClass: { 8766 UnaryOperator *UO = cast<UnaryOperator>(E); 8767 8768 switch(UO->getOpcode()) { 8769 case UO_Real: 8770 case UO_Imag: 8771 case UO_Extension: 8772 return getPrimaryDecl(UO->getSubExpr()); 8773 default: 8774 return 0; 8775 } 8776 } 8777 case Stmt::ParenExprClass: 8778 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8779 case Stmt::ImplicitCastExprClass: 8780 // If the result of an implicit cast is an l-value, we care about 8781 // the sub-expression; otherwise, the result here doesn't matter. 8782 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8783 default: 8784 return 0; 8785 } 8786 } 8787 8788 namespace { 8789 enum { 8790 AO_Bit_Field = 0, 8791 AO_Vector_Element = 1, 8792 AO_Property_Expansion = 2, 8793 AO_Register_Variable = 3, 8794 AO_No_Error = 4 8795 }; 8796 } 8797 /// \brief Diagnose invalid operand for address of operations. 8798 /// 8799 /// \param Type The type of operand which cannot have its address taken. 8800 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8801 Expr *E, unsigned Type) { 8802 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8803 } 8804 8805 /// CheckAddressOfOperand - The operand of & must be either a function 8806 /// designator or an lvalue designating an object. If it is an lvalue, the 8807 /// object cannot be declared with storage class register or be a bit field. 8808 /// Note: The usual conversions are *not* applied to the operand of the & 8809 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8810 /// In C++, the operand might be an overloaded function name, in which case 8811 /// we allow the '&' but retain the overloaded-function type. 8812 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8813 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8814 if (PTy->getKind() == BuiltinType::Overload) { 8815 Expr *E = OrigOp.get()->IgnoreParens(); 8816 if (!isa<OverloadExpr>(E)) { 8817 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8818 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8819 << OrigOp.get()->getSourceRange(); 8820 return QualType(); 8821 } 8822 8823 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8824 if (isa<UnresolvedMemberExpr>(Ovl)) 8825 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8826 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8827 << OrigOp.get()->getSourceRange(); 8828 return QualType(); 8829 } 8830 8831 return Context.OverloadTy; 8832 } 8833 8834 if (PTy->getKind() == BuiltinType::UnknownAny) 8835 return Context.UnknownAnyTy; 8836 8837 if (PTy->getKind() == BuiltinType::BoundMember) { 8838 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8839 << OrigOp.get()->getSourceRange(); 8840 return QualType(); 8841 } 8842 8843 OrigOp = CheckPlaceholderExpr(OrigOp.take()); 8844 if (OrigOp.isInvalid()) return QualType(); 8845 } 8846 8847 if (OrigOp.get()->isTypeDependent()) 8848 return Context.DependentTy; 8849 8850 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8851 8852 // Make sure to ignore parentheses in subsequent checks 8853 Expr *op = OrigOp.get()->IgnoreParens(); 8854 8855 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 8856 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 8857 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 8858 return QualType(); 8859 } 8860 8861 if (getLangOpts().C99) { 8862 // Implement C99-only parts of addressof rules. 8863 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8864 if (uOp->getOpcode() == UO_Deref) 8865 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8866 // (assuming the deref expression is valid). 8867 return uOp->getSubExpr()->getType(); 8868 } 8869 // Technically, there should be a check for array subscript 8870 // expressions here, but the result of one is always an lvalue anyway. 8871 } 8872 ValueDecl *dcl = getPrimaryDecl(op); 8873 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8874 unsigned AddressOfError = AO_No_Error; 8875 8876 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8877 bool sfinae = (bool)isSFINAEContext(); 8878 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8879 : diag::ext_typecheck_addrof_temporary) 8880 << op->getType() << op->getSourceRange(); 8881 if (sfinae) 8882 return QualType(); 8883 // Materialize the temporary as an lvalue so that we can take its address. 8884 OrigOp = op = new (Context) 8885 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8886 } else if (isa<ObjCSelectorExpr>(op)) { 8887 return Context.getPointerType(op->getType()); 8888 } else if (lval == Expr::LV_MemberFunction) { 8889 // If it's an instance method, make a member pointer. 8890 // The expression must have exactly the form &A::foo. 8891 8892 // If the underlying expression isn't a decl ref, give up. 8893 if (!isa<DeclRefExpr>(op)) { 8894 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8895 << OrigOp.get()->getSourceRange(); 8896 return QualType(); 8897 } 8898 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8899 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8900 8901 // The id-expression was parenthesized. 8902 if (OrigOp.get() != DRE) { 8903 Diag(OpLoc, diag::err_parens_pointer_member_function) 8904 << OrigOp.get()->getSourceRange(); 8905 8906 // The method was named without a qualifier. 8907 } else if (!DRE->getQualifier()) { 8908 if (MD->getParent()->getName().empty()) 8909 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8910 << op->getSourceRange(); 8911 else { 8912 SmallString<32> Str; 8913 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8914 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8915 << op->getSourceRange() 8916 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8917 } 8918 } 8919 8920 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 8921 if (isa<CXXDestructorDecl>(MD)) 8922 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 8923 8924 QualType MPTy = Context.getMemberPointerType( 8925 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8926 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8927 RequireCompleteType(OpLoc, MPTy, 0); 8928 return MPTy; 8929 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8930 // C99 6.5.3.2p1 8931 // The operand must be either an l-value or a function designator 8932 if (!op->getType()->isFunctionType()) { 8933 // Use a special diagnostic for loads from property references. 8934 if (isa<PseudoObjectExpr>(op)) { 8935 AddressOfError = AO_Property_Expansion; 8936 } else { 8937 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8938 << op->getType() << op->getSourceRange(); 8939 return QualType(); 8940 } 8941 } 8942 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8943 // The operand cannot be a bit-field 8944 AddressOfError = AO_Bit_Field; 8945 } else if (op->getObjectKind() == OK_VectorComponent) { 8946 // The operand cannot be an element of a vector 8947 AddressOfError = AO_Vector_Element; 8948 } else if (dcl) { // C99 6.5.3.2p1 8949 // We have an lvalue with a decl. Make sure the decl is not declared 8950 // with the register storage-class specifier. 8951 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8952 // in C++ it is not error to take address of a register 8953 // variable (c++03 7.1.1P3) 8954 if (vd->getStorageClass() == SC_Register && 8955 !getLangOpts().CPlusPlus) { 8956 AddressOfError = AO_Register_Variable; 8957 } 8958 } else if (isa<FunctionTemplateDecl>(dcl)) { 8959 return Context.OverloadTy; 8960 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8961 // Okay: we can take the address of a field. 8962 // Could be a pointer to member, though, if there is an explicit 8963 // scope qualifier for the class. 8964 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8965 DeclContext *Ctx = dcl->getDeclContext(); 8966 if (Ctx && Ctx->isRecord()) { 8967 if (dcl->getType()->isReferenceType()) { 8968 Diag(OpLoc, 8969 diag::err_cannot_form_pointer_to_member_of_reference_type) 8970 << dcl->getDeclName() << dcl->getType(); 8971 return QualType(); 8972 } 8973 8974 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8975 Ctx = Ctx->getParent(); 8976 8977 QualType MPTy = Context.getMemberPointerType( 8978 op->getType(), 8979 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8980 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8981 RequireCompleteType(OpLoc, MPTy, 0); 8982 return MPTy; 8983 } 8984 } 8985 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8986 llvm_unreachable("Unknown/unexpected decl type"); 8987 } 8988 8989 if (AddressOfError != AO_No_Error) { 8990 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 8991 return QualType(); 8992 } 8993 8994 if (lval == Expr::LV_IncompleteVoidType) { 8995 // Taking the address of a void variable is technically illegal, but we 8996 // allow it in cases which are otherwise valid. 8997 // Example: "extern void x; void* y = &x;". 8998 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8999 } 9000 9001 // If the operand has type "type", the result has type "pointer to type". 9002 if (op->getType()->isObjCObjectType()) 9003 return Context.getObjCObjectPointerType(op->getType()); 9004 return Context.getPointerType(op->getType()); 9005 } 9006 9007 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 9008 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 9009 SourceLocation OpLoc) { 9010 if (Op->isTypeDependent()) 9011 return S.Context.DependentTy; 9012 9013 ExprResult ConvResult = S.UsualUnaryConversions(Op); 9014 if (ConvResult.isInvalid()) 9015 return QualType(); 9016 Op = ConvResult.take(); 9017 QualType OpTy = Op->getType(); 9018 QualType Result; 9019 9020 if (isa<CXXReinterpretCastExpr>(Op)) { 9021 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 9022 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 9023 Op->getSourceRange()); 9024 } 9025 9026 // Note that per both C89 and C99, indirection is always legal, even if OpTy 9027 // is an incomplete type or void. It would be possible to warn about 9028 // dereferencing a void pointer, but it's completely well-defined, and such a 9029 // warning is unlikely to catch any mistakes. 9030 if (const PointerType *PT = OpTy->getAs<PointerType>()) 9031 Result = PT->getPointeeType(); 9032 else if (const ObjCObjectPointerType *OPT = 9033 OpTy->getAs<ObjCObjectPointerType>()) 9034 Result = OPT->getPointeeType(); 9035 else { 9036 ExprResult PR = S.CheckPlaceholderExpr(Op); 9037 if (PR.isInvalid()) return QualType(); 9038 if (PR.take() != Op) 9039 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 9040 } 9041 9042 if (Result.isNull()) { 9043 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 9044 << OpTy << Op->getSourceRange(); 9045 return QualType(); 9046 } 9047 9048 // Dereferences are usually l-values... 9049 VK = VK_LValue; 9050 9051 // ...except that certain expressions are never l-values in C. 9052 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 9053 VK = VK_RValue; 9054 9055 return Result; 9056 } 9057 9058 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 9059 tok::TokenKind Kind) { 9060 BinaryOperatorKind Opc; 9061 switch (Kind) { 9062 default: llvm_unreachable("Unknown binop!"); 9063 case tok::periodstar: Opc = BO_PtrMemD; break; 9064 case tok::arrowstar: Opc = BO_PtrMemI; break; 9065 case tok::star: Opc = BO_Mul; break; 9066 case tok::slash: Opc = BO_Div; break; 9067 case tok::percent: Opc = BO_Rem; break; 9068 case tok::plus: Opc = BO_Add; break; 9069 case tok::minus: Opc = BO_Sub; break; 9070 case tok::lessless: Opc = BO_Shl; break; 9071 case tok::greatergreater: Opc = BO_Shr; break; 9072 case tok::lessequal: Opc = BO_LE; break; 9073 case tok::less: Opc = BO_LT; break; 9074 case tok::greaterequal: Opc = BO_GE; break; 9075 case tok::greater: Opc = BO_GT; break; 9076 case tok::exclaimequal: Opc = BO_NE; break; 9077 case tok::equalequal: Opc = BO_EQ; break; 9078 case tok::amp: Opc = BO_And; break; 9079 case tok::caret: Opc = BO_Xor; break; 9080 case tok::pipe: Opc = BO_Or; break; 9081 case tok::ampamp: Opc = BO_LAnd; break; 9082 case tok::pipepipe: Opc = BO_LOr; break; 9083 case tok::equal: Opc = BO_Assign; break; 9084 case tok::starequal: Opc = BO_MulAssign; break; 9085 case tok::slashequal: Opc = BO_DivAssign; break; 9086 case tok::percentequal: Opc = BO_RemAssign; break; 9087 case tok::plusequal: Opc = BO_AddAssign; break; 9088 case tok::minusequal: Opc = BO_SubAssign; break; 9089 case tok::lesslessequal: Opc = BO_ShlAssign; break; 9090 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 9091 case tok::ampequal: Opc = BO_AndAssign; break; 9092 case tok::caretequal: Opc = BO_XorAssign; break; 9093 case tok::pipeequal: Opc = BO_OrAssign; break; 9094 case tok::comma: Opc = BO_Comma; break; 9095 } 9096 return Opc; 9097 } 9098 9099 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 9100 tok::TokenKind Kind) { 9101 UnaryOperatorKind Opc; 9102 switch (Kind) { 9103 default: llvm_unreachable("Unknown unary op!"); 9104 case tok::plusplus: Opc = UO_PreInc; break; 9105 case tok::minusminus: Opc = UO_PreDec; break; 9106 case tok::amp: Opc = UO_AddrOf; break; 9107 case tok::star: Opc = UO_Deref; break; 9108 case tok::plus: Opc = UO_Plus; break; 9109 case tok::minus: Opc = UO_Minus; break; 9110 case tok::tilde: Opc = UO_Not; break; 9111 case tok::exclaim: Opc = UO_LNot; break; 9112 case tok::kw___real: Opc = UO_Real; break; 9113 case tok::kw___imag: Opc = UO_Imag; break; 9114 case tok::kw___extension__: Opc = UO_Extension; break; 9115 } 9116 return Opc; 9117 } 9118 9119 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 9120 /// This warning is only emitted for builtin assignment operations. It is also 9121 /// suppressed in the event of macro expansions. 9122 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 9123 SourceLocation OpLoc) { 9124 if (!S.ActiveTemplateInstantiations.empty()) 9125 return; 9126 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 9127 return; 9128 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 9129 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 9130 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 9131 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 9132 if (!LHSDeclRef || !RHSDeclRef || 9133 LHSDeclRef->getLocation().isMacroID() || 9134 RHSDeclRef->getLocation().isMacroID()) 9135 return; 9136 const ValueDecl *LHSDecl = 9137 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 9138 const ValueDecl *RHSDecl = 9139 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 9140 if (LHSDecl != RHSDecl) 9141 return; 9142 if (LHSDecl->getType().isVolatileQualified()) 9143 return; 9144 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9145 if (RefTy->getPointeeType().isVolatileQualified()) 9146 return; 9147 9148 S.Diag(OpLoc, diag::warn_self_assignment) 9149 << LHSDeclRef->getType() 9150 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9151 } 9152 9153 /// Check if a bitwise-& is performed on an Objective-C pointer. This 9154 /// is usually indicative of introspection within the Objective-C pointer. 9155 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9156 SourceLocation OpLoc) { 9157 if (!S.getLangOpts().ObjC1) 9158 return; 9159 9160 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 9161 const Expr *LHS = L.get(); 9162 const Expr *RHS = R.get(); 9163 9164 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9165 ObjCPointerExpr = LHS; 9166 OtherExpr = RHS; 9167 } 9168 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9169 ObjCPointerExpr = RHS; 9170 OtherExpr = LHS; 9171 } 9172 9173 // This warning is deliberately made very specific to reduce false 9174 // positives with logic that uses '&' for hashing. This logic mainly 9175 // looks for code trying to introspect into tagged pointers, which 9176 // code should generally never do. 9177 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9178 unsigned Diag = diag::warn_objc_pointer_masking; 9179 // Determine if we are introspecting the result of performSelectorXXX. 9180 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9181 // Special case messages to -performSelector and friends, which 9182 // can return non-pointer values boxed in a pointer value. 9183 // Some clients may wish to silence warnings in this subcase. 9184 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9185 Selector S = ME->getSelector(); 9186 StringRef SelArg0 = S.getNameForSlot(0); 9187 if (SelArg0.startswith("performSelector")) 9188 Diag = diag::warn_objc_pointer_masking_performSelector; 9189 } 9190 9191 S.Diag(OpLoc, Diag) 9192 << ObjCPointerExpr->getSourceRange(); 9193 } 9194 } 9195 9196 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 9197 /// operator @p Opc at location @c TokLoc. This routine only supports 9198 /// built-in operations; ActOnBinOp handles overloaded operators. 9199 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9200 BinaryOperatorKind Opc, 9201 Expr *LHSExpr, Expr *RHSExpr) { 9202 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 9203 // The syntax only allows initializer lists on the RHS of assignment, 9204 // so we don't need to worry about accepting invalid code for 9205 // non-assignment operators. 9206 // C++11 5.17p9: 9207 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 9208 // of x = {} is x = T(). 9209 InitializationKind Kind = 9210 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 9211 InitializedEntity Entity = 9212 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 9213 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 9214 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 9215 if (Init.isInvalid()) 9216 return Init; 9217 RHSExpr = Init.take(); 9218 } 9219 9220 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 9221 QualType ResultTy; // Result type of the binary operator. 9222 // The following two variables are used for compound assignment operators 9223 QualType CompLHSTy; // Type of LHS after promotions for computation 9224 QualType CompResultTy; // Type of computation result 9225 ExprValueKind VK = VK_RValue; 9226 ExprObjectKind OK = OK_Ordinary; 9227 9228 switch (Opc) { 9229 case BO_Assign: 9230 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9231 if (getLangOpts().CPlusPlus && 9232 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9233 VK = LHS.get()->getValueKind(); 9234 OK = LHS.get()->getObjectKind(); 9235 } 9236 if (!ResultTy.isNull()) 9237 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9238 break; 9239 case BO_PtrMemD: 9240 case BO_PtrMemI: 9241 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9242 Opc == BO_PtrMemI); 9243 break; 9244 case BO_Mul: 9245 case BO_Div: 9246 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9247 Opc == BO_Div); 9248 break; 9249 case BO_Rem: 9250 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9251 break; 9252 case BO_Add: 9253 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9254 break; 9255 case BO_Sub: 9256 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9257 break; 9258 case BO_Shl: 9259 case BO_Shr: 9260 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9261 break; 9262 case BO_LE: 9263 case BO_LT: 9264 case BO_GE: 9265 case BO_GT: 9266 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9267 break; 9268 case BO_EQ: 9269 case BO_NE: 9270 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9271 break; 9272 case BO_And: 9273 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9274 case BO_Xor: 9275 case BO_Or: 9276 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9277 break; 9278 case BO_LAnd: 9279 case BO_LOr: 9280 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9281 break; 9282 case BO_MulAssign: 9283 case BO_DivAssign: 9284 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9285 Opc == BO_DivAssign); 9286 CompLHSTy = CompResultTy; 9287 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9288 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9289 break; 9290 case BO_RemAssign: 9291 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9292 CompLHSTy = CompResultTy; 9293 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9294 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9295 break; 9296 case BO_AddAssign: 9297 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9298 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9299 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9300 break; 9301 case BO_SubAssign: 9302 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9303 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9304 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9305 break; 9306 case BO_ShlAssign: 9307 case BO_ShrAssign: 9308 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9309 CompLHSTy = CompResultTy; 9310 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9311 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9312 break; 9313 case BO_AndAssign: 9314 case BO_XorAssign: 9315 case BO_OrAssign: 9316 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9317 CompLHSTy = CompResultTy; 9318 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9319 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9320 break; 9321 case BO_Comma: 9322 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9323 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9324 VK = RHS.get()->getValueKind(); 9325 OK = RHS.get()->getObjectKind(); 9326 } 9327 break; 9328 } 9329 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9330 return ExprError(); 9331 9332 // Check for array bounds violations for both sides of the BinaryOperator 9333 CheckArrayAccess(LHS.get()); 9334 CheckArrayAccess(RHS.get()); 9335 9336 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9337 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9338 &Context.Idents.get("object_setClass"), 9339 SourceLocation(), LookupOrdinaryName); 9340 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9341 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9342 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9343 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9344 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9345 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9346 } 9347 else 9348 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9349 } 9350 else if (const ObjCIvarRefExpr *OIRE = 9351 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9352 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9353 9354 if (CompResultTy.isNull()) 9355 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 9356 ResultTy, VK, OK, OpLoc, 9357 FPFeatures.fp_contract)); 9358 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9359 OK_ObjCProperty) { 9360 VK = VK_LValue; 9361 OK = LHS.get()->getObjectKind(); 9362 } 9363 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 9364 ResultTy, VK, OK, CompLHSTy, 9365 CompResultTy, OpLoc, 9366 FPFeatures.fp_contract)); 9367 } 9368 9369 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9370 /// operators are mixed in a way that suggests that the programmer forgot that 9371 /// comparison operators have higher precedence. The most typical example of 9372 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9373 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9374 SourceLocation OpLoc, Expr *LHSExpr, 9375 Expr *RHSExpr) { 9376 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9377 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9378 9379 // Check that one of the sides is a comparison operator. 9380 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9381 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9382 if (!isLeftComp && !isRightComp) 9383 return; 9384 9385 // Bitwise operations are sometimes used as eager logical ops. 9386 // Don't diagnose this. 9387 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9388 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9389 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9390 return; 9391 9392 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9393 OpLoc) 9394 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9395 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9396 SourceRange ParensRange = isLeftComp ? 9397 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9398 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9399 9400 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9401 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9402 SuggestParentheses(Self, OpLoc, 9403 Self.PDiag(diag::note_precedence_silence) << OpStr, 9404 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9405 SuggestParentheses(Self, OpLoc, 9406 Self.PDiag(diag::note_precedence_bitwise_first) 9407 << BinaryOperator::getOpcodeStr(Opc), 9408 ParensRange); 9409 } 9410 9411 /// \brief It accepts a '&' expr that is inside a '|' one. 9412 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9413 /// in parentheses. 9414 static void 9415 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9416 BinaryOperator *Bop) { 9417 assert(Bop->getOpcode() == BO_And); 9418 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9419 << Bop->getSourceRange() << OpLoc; 9420 SuggestParentheses(Self, Bop->getOperatorLoc(), 9421 Self.PDiag(diag::note_precedence_silence) 9422 << Bop->getOpcodeStr(), 9423 Bop->getSourceRange()); 9424 } 9425 9426 /// \brief It accepts a '&&' expr that is inside a '||' one. 9427 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9428 /// in parentheses. 9429 static void 9430 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9431 BinaryOperator *Bop) { 9432 assert(Bop->getOpcode() == BO_LAnd); 9433 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9434 << Bop->getSourceRange() << OpLoc; 9435 SuggestParentheses(Self, Bop->getOperatorLoc(), 9436 Self.PDiag(diag::note_precedence_silence) 9437 << Bop->getOpcodeStr(), 9438 Bop->getSourceRange()); 9439 } 9440 9441 /// \brief Returns true if the given expression can be evaluated as a constant 9442 /// 'true'. 9443 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9444 bool Res; 9445 return !E->isValueDependent() && 9446 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9447 } 9448 9449 /// \brief Returns true if the given expression can be evaluated as a constant 9450 /// 'false'. 9451 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9452 bool Res; 9453 return !E->isValueDependent() && 9454 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9455 } 9456 9457 /// \brief Look for '&&' in the left hand of a '||' expr. 9458 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9459 Expr *LHSExpr, Expr *RHSExpr) { 9460 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9461 if (Bop->getOpcode() == BO_LAnd) { 9462 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9463 if (EvaluatesAsFalse(S, RHSExpr)) 9464 return; 9465 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9466 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9467 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9468 } else if (Bop->getOpcode() == BO_LOr) { 9469 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9470 // If it's "a || b && 1 || c" we didn't warn earlier for 9471 // "a || b && 1", but warn now. 9472 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9473 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9474 } 9475 } 9476 } 9477 } 9478 9479 /// \brief Look for '&&' in the right hand of a '||' expr. 9480 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9481 Expr *LHSExpr, Expr *RHSExpr) { 9482 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9483 if (Bop->getOpcode() == BO_LAnd) { 9484 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9485 if (EvaluatesAsFalse(S, LHSExpr)) 9486 return; 9487 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9488 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9489 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9490 } 9491 } 9492 } 9493 9494 /// \brief Look for '&' in the left or right hand of a '|' expr. 9495 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9496 Expr *OrArg) { 9497 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9498 if (Bop->getOpcode() == BO_And) 9499 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9500 } 9501 } 9502 9503 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9504 Expr *SubExpr, StringRef Shift) { 9505 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9506 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9507 StringRef Op = Bop->getOpcodeStr(); 9508 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9509 << Bop->getSourceRange() << OpLoc << Shift << Op; 9510 SuggestParentheses(S, Bop->getOperatorLoc(), 9511 S.PDiag(diag::note_precedence_silence) << Op, 9512 Bop->getSourceRange()); 9513 } 9514 } 9515 } 9516 9517 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9518 Expr *LHSExpr, Expr *RHSExpr) { 9519 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9520 if (!OCE) 9521 return; 9522 9523 FunctionDecl *FD = OCE->getDirectCallee(); 9524 if (!FD || !FD->isOverloadedOperator()) 9525 return; 9526 9527 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9528 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9529 return; 9530 9531 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9532 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9533 << (Kind == OO_LessLess); 9534 SuggestParentheses(S, OCE->getOperatorLoc(), 9535 S.PDiag(diag::note_precedence_silence) 9536 << (Kind == OO_LessLess ? "<<" : ">>"), 9537 OCE->getSourceRange()); 9538 SuggestParentheses(S, OpLoc, 9539 S.PDiag(diag::note_evaluate_comparison_first), 9540 SourceRange(OCE->getArg(1)->getLocStart(), 9541 RHSExpr->getLocEnd())); 9542 } 9543 9544 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9545 /// precedence. 9546 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9547 SourceLocation OpLoc, Expr *LHSExpr, 9548 Expr *RHSExpr){ 9549 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9550 if (BinaryOperator::isBitwiseOp(Opc)) 9551 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9552 9553 // Diagnose "arg1 & arg2 | arg3" 9554 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9555 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9556 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9557 } 9558 9559 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9560 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9561 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9562 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9563 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9564 } 9565 9566 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9567 || Opc == BO_Shr) { 9568 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9569 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9570 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9571 } 9572 9573 // Warn on overloaded shift operators and comparisons, such as: 9574 // cout << 5 == 4; 9575 if (BinaryOperator::isComparisonOp(Opc)) 9576 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9577 } 9578 9579 // Binary Operators. 'Tok' is the token for the operator. 9580 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9581 tok::TokenKind Kind, 9582 Expr *LHSExpr, Expr *RHSExpr) { 9583 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9584 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9585 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9586 9587 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9588 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9589 9590 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9591 } 9592 9593 /// Build an overloaded binary operator expression in the given scope. 9594 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9595 BinaryOperatorKind Opc, 9596 Expr *LHS, Expr *RHS) { 9597 // Find all of the overloaded operators visible from this 9598 // point. We perform both an operator-name lookup from the local 9599 // scope and an argument-dependent lookup based on the types of 9600 // the arguments. 9601 UnresolvedSet<16> Functions; 9602 OverloadedOperatorKind OverOp 9603 = BinaryOperator::getOverloadedOperator(Opc); 9604 if (Sc && OverOp != OO_None) 9605 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9606 RHS->getType(), Functions); 9607 9608 // Build the (potentially-overloaded, potentially-dependent) 9609 // binary operation. 9610 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9611 } 9612 9613 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9614 BinaryOperatorKind Opc, 9615 Expr *LHSExpr, Expr *RHSExpr) { 9616 // We want to end up calling one of checkPseudoObjectAssignment 9617 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9618 // both expressions are overloadable or either is type-dependent), 9619 // or CreateBuiltinBinOp (in any other case). We also want to get 9620 // any placeholder types out of the way. 9621 9622 // Handle pseudo-objects in the LHS. 9623 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9624 // Assignments with a pseudo-object l-value need special analysis. 9625 if (pty->getKind() == BuiltinType::PseudoObject && 9626 BinaryOperator::isAssignmentOp(Opc)) 9627 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9628 9629 // Don't resolve overloads if the other type is overloadable. 9630 if (pty->getKind() == BuiltinType::Overload) { 9631 // We can't actually test that if we still have a placeholder, 9632 // though. Fortunately, none of the exceptions we see in that 9633 // code below are valid when the LHS is an overload set. Note 9634 // that an overload set can be dependently-typed, but it never 9635 // instantiates to having an overloadable type. 9636 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9637 if (resolvedRHS.isInvalid()) return ExprError(); 9638 RHSExpr = resolvedRHS.take(); 9639 9640 if (RHSExpr->isTypeDependent() || 9641 RHSExpr->getType()->isOverloadableType()) 9642 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9643 } 9644 9645 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9646 if (LHS.isInvalid()) return ExprError(); 9647 LHSExpr = LHS.take(); 9648 } 9649 9650 // Handle pseudo-objects in the RHS. 9651 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9652 // An overload in the RHS can potentially be resolved by the type 9653 // being assigned to. 9654 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9655 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9656 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9657 9658 if (LHSExpr->getType()->isOverloadableType()) 9659 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9660 9661 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9662 } 9663 9664 // Don't resolve overloads if the other type is overloadable. 9665 if (pty->getKind() == BuiltinType::Overload && 9666 LHSExpr->getType()->isOverloadableType()) 9667 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9668 9669 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9670 if (!resolvedRHS.isUsable()) return ExprError(); 9671 RHSExpr = resolvedRHS.take(); 9672 } 9673 9674 if (getLangOpts().CPlusPlus) { 9675 // If either expression is type-dependent, always build an 9676 // overloaded op. 9677 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9678 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9679 9680 // Otherwise, build an overloaded op if either expression has an 9681 // overloadable type. 9682 if (LHSExpr->getType()->isOverloadableType() || 9683 RHSExpr->getType()->isOverloadableType()) 9684 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9685 } 9686 9687 // Build a built-in binary operation. 9688 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9689 } 9690 9691 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9692 UnaryOperatorKind Opc, 9693 Expr *InputExpr) { 9694 ExprResult Input = Owned(InputExpr); 9695 ExprValueKind VK = VK_RValue; 9696 ExprObjectKind OK = OK_Ordinary; 9697 QualType resultType; 9698 switch (Opc) { 9699 case UO_PreInc: 9700 case UO_PreDec: 9701 case UO_PostInc: 9702 case UO_PostDec: 9703 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9704 Opc == UO_PreInc || 9705 Opc == UO_PostInc, 9706 Opc == UO_PreInc || 9707 Opc == UO_PreDec); 9708 break; 9709 case UO_AddrOf: 9710 resultType = CheckAddressOfOperand(Input, OpLoc); 9711 break; 9712 case UO_Deref: { 9713 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9714 if (Input.isInvalid()) return ExprError(); 9715 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9716 break; 9717 } 9718 case UO_Plus: 9719 case UO_Minus: 9720 Input = UsualUnaryConversions(Input.take()); 9721 if (Input.isInvalid()) return ExprError(); 9722 resultType = Input.get()->getType(); 9723 if (resultType->isDependentType()) 9724 break; 9725 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9726 resultType->isVectorType()) 9727 break; 9728 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9729 Opc == UO_Plus && 9730 resultType->isPointerType()) 9731 break; 9732 9733 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9734 << resultType << Input.get()->getSourceRange()); 9735 9736 case UO_Not: // bitwise complement 9737 Input = UsualUnaryConversions(Input.take()); 9738 if (Input.isInvalid()) 9739 return ExprError(); 9740 resultType = Input.get()->getType(); 9741 if (resultType->isDependentType()) 9742 break; 9743 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9744 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9745 // C99 does not support '~' for complex conjugation. 9746 Diag(OpLoc, diag::ext_integer_complement_complex) 9747 << resultType << Input.get()->getSourceRange(); 9748 else if (resultType->hasIntegerRepresentation()) 9749 break; 9750 else if (resultType->isExtVectorType()) { 9751 if (Context.getLangOpts().OpenCL) { 9752 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9753 // on vector float types. 9754 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9755 if (!T->isIntegerType()) 9756 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9757 << resultType << Input.get()->getSourceRange()); 9758 } 9759 break; 9760 } else { 9761 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9762 << resultType << Input.get()->getSourceRange()); 9763 } 9764 break; 9765 9766 case UO_LNot: // logical negation 9767 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9768 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9769 if (Input.isInvalid()) return ExprError(); 9770 resultType = Input.get()->getType(); 9771 9772 // Though we still have to promote half FP to float... 9773 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9774 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9775 resultType = Context.FloatTy; 9776 } 9777 9778 if (resultType->isDependentType()) 9779 break; 9780 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 9781 // C99 6.5.3.3p1: ok, fallthrough; 9782 if (Context.getLangOpts().CPlusPlus) { 9783 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9784 // operand contextually converted to bool. 9785 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9786 ScalarTypeToBooleanCastKind(resultType)); 9787 } else if (Context.getLangOpts().OpenCL && 9788 Context.getLangOpts().OpenCLVersion < 120) { 9789 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9790 // operate on scalar float types. 9791 if (!resultType->isIntegerType()) 9792 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9793 << resultType << Input.get()->getSourceRange()); 9794 } 9795 } else if (resultType->isExtVectorType()) { 9796 if (Context.getLangOpts().OpenCL && 9797 Context.getLangOpts().OpenCLVersion < 120) { 9798 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9799 // operate on vector float types. 9800 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9801 if (!T->isIntegerType()) 9802 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9803 << resultType << Input.get()->getSourceRange()); 9804 } 9805 // Vector logical not returns the signed variant of the operand type. 9806 resultType = GetSignedVectorType(resultType); 9807 break; 9808 } else { 9809 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9810 << resultType << Input.get()->getSourceRange()); 9811 } 9812 9813 // LNot always has type int. C99 6.5.3.3p5. 9814 // In C++, it's bool. C++ 5.3.1p8 9815 resultType = Context.getLogicalOperationType(); 9816 break; 9817 case UO_Real: 9818 case UO_Imag: 9819 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9820 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9821 // complex l-values to ordinary l-values and all other values to r-values. 9822 if (Input.isInvalid()) return ExprError(); 9823 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9824 if (Input.get()->getValueKind() != VK_RValue && 9825 Input.get()->getObjectKind() == OK_Ordinary) 9826 VK = Input.get()->getValueKind(); 9827 } else if (!getLangOpts().CPlusPlus) { 9828 // In C, a volatile scalar is read by __imag. In C++, it is not. 9829 Input = DefaultLvalueConversion(Input.take()); 9830 } 9831 break; 9832 case UO_Extension: 9833 resultType = Input.get()->getType(); 9834 VK = Input.get()->getValueKind(); 9835 OK = Input.get()->getObjectKind(); 9836 break; 9837 } 9838 if (resultType.isNull() || Input.isInvalid()) 9839 return ExprError(); 9840 9841 // Check for array bounds violations in the operand of the UnaryOperator, 9842 // except for the '*' and '&' operators that have to be handled specially 9843 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9844 // that are explicitly defined as valid by the standard). 9845 if (Opc != UO_AddrOf && Opc != UO_Deref) 9846 CheckArrayAccess(Input.get()); 9847 9848 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9849 VK, OK, OpLoc)); 9850 } 9851 9852 /// \brief Determine whether the given expression is a qualified member 9853 /// access expression, of a form that could be turned into a pointer to member 9854 /// with the address-of operator. 9855 static bool isQualifiedMemberAccess(Expr *E) { 9856 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9857 if (!DRE->getQualifier()) 9858 return false; 9859 9860 ValueDecl *VD = DRE->getDecl(); 9861 if (!VD->isCXXClassMember()) 9862 return false; 9863 9864 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9865 return true; 9866 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9867 return Method->isInstance(); 9868 9869 return false; 9870 } 9871 9872 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9873 if (!ULE->getQualifier()) 9874 return false; 9875 9876 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9877 DEnd = ULE->decls_end(); 9878 D != DEnd; ++D) { 9879 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9880 if (Method->isInstance()) 9881 return true; 9882 } else { 9883 // Overload set does not contain methods. 9884 break; 9885 } 9886 } 9887 9888 return false; 9889 } 9890 9891 return false; 9892 } 9893 9894 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9895 UnaryOperatorKind Opc, Expr *Input) { 9896 // First things first: handle placeholders so that the 9897 // overloaded-operator check considers the right type. 9898 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9899 // Increment and decrement of pseudo-object references. 9900 if (pty->getKind() == BuiltinType::PseudoObject && 9901 UnaryOperator::isIncrementDecrementOp(Opc)) 9902 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9903 9904 // extension is always a builtin operator. 9905 if (Opc == UO_Extension) 9906 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9907 9908 // & gets special logic for several kinds of placeholder. 9909 // The builtin code knows what to do. 9910 if (Opc == UO_AddrOf && 9911 (pty->getKind() == BuiltinType::Overload || 9912 pty->getKind() == BuiltinType::UnknownAny || 9913 pty->getKind() == BuiltinType::BoundMember)) 9914 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9915 9916 // Anything else needs to be handled now. 9917 ExprResult Result = CheckPlaceholderExpr(Input); 9918 if (Result.isInvalid()) return ExprError(); 9919 Input = Result.take(); 9920 } 9921 9922 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9923 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9924 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9925 // Find all of the overloaded operators visible from this 9926 // point. We perform both an operator-name lookup from the local 9927 // scope and an argument-dependent lookup based on the types of 9928 // the arguments. 9929 UnresolvedSet<16> Functions; 9930 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9931 if (S && OverOp != OO_None) 9932 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9933 Functions); 9934 9935 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9936 } 9937 9938 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9939 } 9940 9941 // Unary Operators. 'Tok' is the token for the operator. 9942 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9943 tok::TokenKind Op, Expr *Input) { 9944 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9945 } 9946 9947 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9948 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9949 LabelDecl *TheDecl) { 9950 TheDecl->markUsed(Context); 9951 // Create the AST node. The address of a label always has type 'void*'. 9952 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9953 Context.getPointerType(Context.VoidTy))); 9954 } 9955 9956 /// Given the last statement in a statement-expression, check whether 9957 /// the result is a producing expression (like a call to an 9958 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9959 /// release out of the full-expression. Otherwise, return null. 9960 /// Cannot fail. 9961 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9962 // Should always be wrapped with one of these. 9963 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9964 if (!cleanups) return 0; 9965 9966 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9967 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9968 return 0; 9969 9970 // Splice out the cast. This shouldn't modify any interesting 9971 // features of the statement. 9972 Expr *producer = cast->getSubExpr(); 9973 assert(producer->getType() == cast->getType()); 9974 assert(producer->getValueKind() == cast->getValueKind()); 9975 cleanups->setSubExpr(producer); 9976 return cleanups; 9977 } 9978 9979 void Sema::ActOnStartStmtExpr() { 9980 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9981 } 9982 9983 void Sema::ActOnStmtExprError() { 9984 // Note that function is also called by TreeTransform when leaving a 9985 // StmtExpr scope without rebuilding anything. 9986 9987 DiscardCleanupsInEvaluationContext(); 9988 PopExpressionEvaluationContext(); 9989 } 9990 9991 ExprResult 9992 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9993 SourceLocation RPLoc) { // "({..})" 9994 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9995 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9996 9997 if (hasAnyUnrecoverableErrorsInThisFunction()) 9998 DiscardCleanupsInEvaluationContext(); 9999 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 10000 PopExpressionEvaluationContext(); 10001 10002 bool isFileScope 10003 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 10004 if (isFileScope) 10005 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 10006 10007 // FIXME: there are a variety of strange constraints to enforce here, for 10008 // example, it is not possible to goto into a stmt expression apparently. 10009 // More semantic analysis is needed. 10010 10011 // If there are sub-stmts in the compound stmt, take the type of the last one 10012 // as the type of the stmtexpr. 10013 QualType Ty = Context.VoidTy; 10014 bool StmtExprMayBindToTemp = false; 10015 if (!Compound->body_empty()) { 10016 Stmt *LastStmt = Compound->body_back(); 10017 LabelStmt *LastLabelStmt = 0; 10018 // If LastStmt is a label, skip down through into the body. 10019 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 10020 LastLabelStmt = Label; 10021 LastStmt = Label->getSubStmt(); 10022 } 10023 10024 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 10025 // Do function/array conversion on the last expression, but not 10026 // lvalue-to-rvalue. However, initialize an unqualified type. 10027 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 10028 if (LastExpr.isInvalid()) 10029 return ExprError(); 10030 Ty = LastExpr.get()->getType().getUnqualifiedType(); 10031 10032 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 10033 // In ARC, if the final expression ends in a consume, splice 10034 // the consume out and bind it later. In the alternate case 10035 // (when dealing with a retainable type), the result 10036 // initialization will create a produce. In both cases the 10037 // result will be +1, and we'll need to balance that out with 10038 // a bind. 10039 if (Expr *rebuiltLastStmt 10040 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 10041 LastExpr = rebuiltLastStmt; 10042 } else { 10043 LastExpr = PerformCopyInitialization( 10044 InitializedEntity::InitializeResult(LPLoc, 10045 Ty, 10046 false), 10047 SourceLocation(), 10048 LastExpr); 10049 } 10050 10051 if (LastExpr.isInvalid()) 10052 return ExprError(); 10053 if (LastExpr.get() != 0) { 10054 if (!LastLabelStmt) 10055 Compound->setLastStmt(LastExpr.take()); 10056 else 10057 LastLabelStmt->setSubStmt(LastExpr.take()); 10058 StmtExprMayBindToTemp = true; 10059 } 10060 } 10061 } 10062 } 10063 10064 // FIXME: Check that expression type is complete/non-abstract; statement 10065 // expressions are not lvalues. 10066 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 10067 if (StmtExprMayBindToTemp) 10068 return MaybeBindToTemporary(ResStmtExpr); 10069 return Owned(ResStmtExpr); 10070 } 10071 10072 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 10073 TypeSourceInfo *TInfo, 10074 OffsetOfComponent *CompPtr, 10075 unsigned NumComponents, 10076 SourceLocation RParenLoc) { 10077 QualType ArgTy = TInfo->getType(); 10078 bool Dependent = ArgTy->isDependentType(); 10079 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 10080 10081 // We must have at least one component that refers to the type, and the first 10082 // one is known to be a field designator. Verify that the ArgTy represents 10083 // a struct/union/class. 10084 if (!Dependent && !ArgTy->isRecordType()) 10085 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 10086 << ArgTy << TypeRange); 10087 10088 // Type must be complete per C99 7.17p3 because a declaring a variable 10089 // with an incomplete type would be ill-formed. 10090 if (!Dependent 10091 && RequireCompleteType(BuiltinLoc, ArgTy, 10092 diag::err_offsetof_incomplete_type, TypeRange)) 10093 return ExprError(); 10094 10095 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 10096 // GCC extension, diagnose them. 10097 // FIXME: This diagnostic isn't actually visible because the location is in 10098 // a system header! 10099 if (NumComponents != 1) 10100 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 10101 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 10102 10103 bool DidWarnAboutNonPOD = false; 10104 QualType CurrentType = ArgTy; 10105 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 10106 SmallVector<OffsetOfNode, 4> Comps; 10107 SmallVector<Expr*, 4> Exprs; 10108 for (unsigned i = 0; i != NumComponents; ++i) { 10109 const OffsetOfComponent &OC = CompPtr[i]; 10110 if (OC.isBrackets) { 10111 // Offset of an array sub-field. TODO: Should we allow vector elements? 10112 if (!CurrentType->isDependentType()) { 10113 const ArrayType *AT = Context.getAsArrayType(CurrentType); 10114 if(!AT) 10115 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 10116 << CurrentType); 10117 CurrentType = AT->getElementType(); 10118 } else 10119 CurrentType = Context.DependentTy; 10120 10121 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 10122 if (IdxRval.isInvalid()) 10123 return ExprError(); 10124 Expr *Idx = IdxRval.take(); 10125 10126 // The expression must be an integral expression. 10127 // FIXME: An integral constant expression? 10128 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 10129 !Idx->getType()->isIntegerType()) 10130 return ExprError(Diag(Idx->getLocStart(), 10131 diag::err_typecheck_subscript_not_integer) 10132 << Idx->getSourceRange()); 10133 10134 // Record this array index. 10135 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 10136 Exprs.push_back(Idx); 10137 continue; 10138 } 10139 10140 // Offset of a field. 10141 if (CurrentType->isDependentType()) { 10142 // We have the offset of a field, but we can't look into the dependent 10143 // type. Just record the identifier of the field. 10144 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10145 CurrentType = Context.DependentTy; 10146 continue; 10147 } 10148 10149 // We need to have a complete type to look into. 10150 if (RequireCompleteType(OC.LocStart, CurrentType, 10151 diag::err_offsetof_incomplete_type)) 10152 return ExprError(); 10153 10154 // Look for the designated field. 10155 const RecordType *RC = CurrentType->getAs<RecordType>(); 10156 if (!RC) 10157 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10158 << CurrentType); 10159 RecordDecl *RD = RC->getDecl(); 10160 10161 // C++ [lib.support.types]p5: 10162 // The macro offsetof accepts a restricted set of type arguments in this 10163 // International Standard. type shall be a POD structure or a POD union 10164 // (clause 9). 10165 // C++11 [support.types]p4: 10166 // If type is not a standard-layout class (Clause 9), the results are 10167 // undefined. 10168 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10169 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10170 unsigned DiagID = 10171 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 10172 : diag::warn_offsetof_non_pod_type; 10173 10174 if (!IsSafe && !DidWarnAboutNonPOD && 10175 DiagRuntimeBehavior(BuiltinLoc, 0, 10176 PDiag(DiagID) 10177 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10178 << CurrentType)) 10179 DidWarnAboutNonPOD = true; 10180 } 10181 10182 // Look for the field. 10183 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10184 LookupQualifiedName(R, RD); 10185 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 10186 IndirectFieldDecl *IndirectMemberDecl = 0; 10187 if (!MemberDecl) { 10188 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 10189 MemberDecl = IndirectMemberDecl->getAnonField(); 10190 } 10191 10192 if (!MemberDecl) 10193 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 10194 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 10195 OC.LocEnd)); 10196 10197 // C99 7.17p3: 10198 // (If the specified member is a bit-field, the behavior is undefined.) 10199 // 10200 // We diagnose this as an error. 10201 if (MemberDecl->isBitField()) { 10202 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 10203 << MemberDecl->getDeclName() 10204 << SourceRange(BuiltinLoc, RParenLoc); 10205 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 10206 return ExprError(); 10207 } 10208 10209 RecordDecl *Parent = MemberDecl->getParent(); 10210 if (IndirectMemberDecl) 10211 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 10212 10213 // If the member was found in a base class, introduce OffsetOfNodes for 10214 // the base class indirections. 10215 CXXBasePaths Paths; 10216 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 10217 if (Paths.getDetectedVirtual()) { 10218 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 10219 << MemberDecl->getDeclName() 10220 << SourceRange(BuiltinLoc, RParenLoc); 10221 return ExprError(); 10222 } 10223 10224 CXXBasePath &Path = Paths.front(); 10225 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10226 B != BEnd; ++B) 10227 Comps.push_back(OffsetOfNode(B->Base)); 10228 } 10229 10230 if (IndirectMemberDecl) { 10231 for (IndirectFieldDecl::chain_iterator FI = 10232 IndirectMemberDecl->chain_begin(), 10233 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 10234 assert(isa<FieldDecl>(*FI)); 10235 Comps.push_back(OffsetOfNode(OC.LocStart, 10236 cast<FieldDecl>(*FI), OC.LocEnd)); 10237 } 10238 } else 10239 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10240 10241 CurrentType = MemberDecl->getType().getNonReferenceType(); 10242 } 10243 10244 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 10245 TInfo, Comps, Exprs, RParenLoc)); 10246 } 10247 10248 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10249 SourceLocation BuiltinLoc, 10250 SourceLocation TypeLoc, 10251 ParsedType ParsedArgTy, 10252 OffsetOfComponent *CompPtr, 10253 unsigned NumComponents, 10254 SourceLocation RParenLoc) { 10255 10256 TypeSourceInfo *ArgTInfo; 10257 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10258 if (ArgTy.isNull()) 10259 return ExprError(); 10260 10261 if (!ArgTInfo) 10262 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10263 10264 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10265 RParenLoc); 10266 } 10267 10268 10269 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10270 Expr *CondExpr, 10271 Expr *LHSExpr, Expr *RHSExpr, 10272 SourceLocation RPLoc) { 10273 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10274 10275 ExprValueKind VK = VK_RValue; 10276 ExprObjectKind OK = OK_Ordinary; 10277 QualType resType; 10278 bool ValueDependent = false; 10279 bool CondIsTrue = false; 10280 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10281 resType = Context.DependentTy; 10282 ValueDependent = true; 10283 } else { 10284 // The conditional expression is required to be a constant expression. 10285 llvm::APSInt condEval(32); 10286 ExprResult CondICE 10287 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10288 diag::err_typecheck_choose_expr_requires_constant, false); 10289 if (CondICE.isInvalid()) 10290 return ExprError(); 10291 CondExpr = CondICE.take(); 10292 CondIsTrue = condEval.getZExtValue(); 10293 10294 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10295 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10296 10297 resType = ActiveExpr->getType(); 10298 ValueDependent = ActiveExpr->isValueDependent(); 10299 VK = ActiveExpr->getValueKind(); 10300 OK = ActiveExpr->getObjectKind(); 10301 } 10302 10303 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 10304 resType, VK, OK, RPLoc, CondIsTrue, 10305 resType->isDependentType(), 10306 ValueDependent)); 10307 } 10308 10309 //===----------------------------------------------------------------------===// 10310 // Clang Extensions. 10311 //===----------------------------------------------------------------------===// 10312 10313 /// ActOnBlockStart - This callback is invoked when a block literal is started. 10314 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10315 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10316 10317 if (LangOpts.CPlusPlus) { 10318 Decl *ManglingContextDecl; 10319 if (MangleNumberingContext *MCtx = 10320 getCurrentMangleNumberContext(Block->getDeclContext(), 10321 ManglingContextDecl)) { 10322 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10323 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10324 } 10325 } 10326 10327 PushBlockScope(CurScope, Block); 10328 CurContext->addDecl(Block); 10329 if (CurScope) 10330 PushDeclContext(CurScope, Block); 10331 else 10332 CurContext = Block; 10333 10334 getCurBlock()->HasImplicitReturnType = true; 10335 10336 // Enter a new evaluation context to insulate the block from any 10337 // cleanups from the enclosing full-expression. 10338 PushExpressionEvaluationContext(PotentiallyEvaluated); 10339 } 10340 10341 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10342 Scope *CurScope) { 10343 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 10344 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10345 BlockScopeInfo *CurBlock = getCurBlock(); 10346 10347 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10348 QualType T = Sig->getType(); 10349 10350 // FIXME: We should allow unexpanded parameter packs here, but that would, 10351 // in turn, make the block expression contain unexpanded parameter packs. 10352 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10353 // Drop the parameters. 10354 FunctionProtoType::ExtProtoInfo EPI; 10355 EPI.HasTrailingReturn = false; 10356 EPI.TypeQuals |= DeclSpec::TQ_const; 10357 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10358 Sig = Context.getTrivialTypeSourceInfo(T); 10359 } 10360 10361 // GetTypeForDeclarator always produces a function type for a block 10362 // literal signature. Furthermore, it is always a FunctionProtoType 10363 // unless the function was written with a typedef. 10364 assert(T->isFunctionType() && 10365 "GetTypeForDeclarator made a non-function block signature"); 10366 10367 // Look for an explicit signature in that function type. 10368 FunctionProtoTypeLoc ExplicitSignature; 10369 10370 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10371 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10372 10373 // Check whether that explicit signature was synthesized by 10374 // GetTypeForDeclarator. If so, don't save that as part of the 10375 // written signature. 10376 if (ExplicitSignature.getLocalRangeBegin() == 10377 ExplicitSignature.getLocalRangeEnd()) { 10378 // This would be much cheaper if we stored TypeLocs instead of 10379 // TypeSourceInfos. 10380 TypeLoc Result = ExplicitSignature.getReturnLoc(); 10381 unsigned Size = Result.getFullDataSize(); 10382 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10383 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10384 10385 ExplicitSignature = FunctionProtoTypeLoc(); 10386 } 10387 } 10388 10389 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10390 CurBlock->FunctionType = T; 10391 10392 const FunctionType *Fn = T->getAs<FunctionType>(); 10393 QualType RetTy = Fn->getReturnType(); 10394 bool isVariadic = 10395 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10396 10397 CurBlock->TheDecl->setIsVariadic(isVariadic); 10398 10399 // Context.DependentTy is used as a placeholder for a missing block 10400 // return type. TODO: what should we do with declarators like: 10401 // ^ * { ... } 10402 // If the answer is "apply template argument deduction".... 10403 if (RetTy != Context.DependentTy) { 10404 CurBlock->ReturnType = RetTy; 10405 CurBlock->TheDecl->setBlockMissingReturnType(false); 10406 CurBlock->HasImplicitReturnType = false; 10407 } 10408 10409 // Push block parameters from the declarator if we had them. 10410 SmallVector<ParmVarDecl*, 8> Params; 10411 if (ExplicitSignature) { 10412 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 10413 ParmVarDecl *Param = ExplicitSignature.getParam(I); 10414 if (Param->getIdentifier() == 0 && 10415 !Param->isImplicit() && 10416 !Param->isInvalidDecl() && 10417 !getLangOpts().CPlusPlus) 10418 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10419 Params.push_back(Param); 10420 } 10421 10422 // Fake up parameter variables if we have a typedef, like 10423 // ^ fntype { ... } 10424 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10425 for (FunctionProtoType::param_type_iterator I = Fn->param_type_begin(), 10426 E = Fn->param_type_end(); 10427 I != E; ++I) { 10428 ParmVarDecl *Param = 10429 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 10430 ParamInfo.getLocStart(), 10431 *I); 10432 Params.push_back(Param); 10433 } 10434 } 10435 10436 // Set the parameters on the block decl. 10437 if (!Params.empty()) { 10438 CurBlock->TheDecl->setParams(Params); 10439 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10440 CurBlock->TheDecl->param_end(), 10441 /*CheckParameterNames=*/false); 10442 } 10443 10444 // Finally we can process decl attributes. 10445 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10446 10447 // Put the parameter variables in scope. 10448 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 10449 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 10450 (*AI)->setOwningFunction(CurBlock->TheDecl); 10451 10452 // If this has an identifier, add it to the scope stack. 10453 if ((*AI)->getIdentifier()) { 10454 CheckShadow(CurBlock->TheScope, *AI); 10455 10456 PushOnScopeChains(*AI, CurBlock->TheScope); 10457 } 10458 } 10459 } 10460 10461 /// ActOnBlockError - If there is an error parsing a block, this callback 10462 /// is invoked to pop the information about the block from the action impl. 10463 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10464 // Leave the expression-evaluation context. 10465 DiscardCleanupsInEvaluationContext(); 10466 PopExpressionEvaluationContext(); 10467 10468 // Pop off CurBlock, handle nested blocks. 10469 PopDeclContext(); 10470 PopFunctionScopeInfo(); 10471 } 10472 10473 /// ActOnBlockStmtExpr - This is called when the body of a block statement 10474 /// literal was successfully completed. ^(int x){...} 10475 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10476 Stmt *Body, Scope *CurScope) { 10477 // If blocks are disabled, emit an error. 10478 if (!LangOpts.Blocks) 10479 Diag(CaretLoc, diag::err_blocks_disable); 10480 10481 // Leave the expression-evaluation context. 10482 if (hasAnyUnrecoverableErrorsInThisFunction()) 10483 DiscardCleanupsInEvaluationContext(); 10484 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10485 PopExpressionEvaluationContext(); 10486 10487 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10488 10489 if (BSI->HasImplicitReturnType) 10490 deduceClosureReturnType(*BSI); 10491 10492 PopDeclContext(); 10493 10494 QualType RetTy = Context.VoidTy; 10495 if (!BSI->ReturnType.isNull()) 10496 RetTy = BSI->ReturnType; 10497 10498 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 10499 QualType BlockTy; 10500 10501 // Set the captured variables on the block. 10502 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10503 SmallVector<BlockDecl::Capture, 4> Captures; 10504 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10505 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10506 if (Cap.isThisCapture()) 10507 continue; 10508 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10509 Cap.isNested(), Cap.getInitExpr()); 10510 Captures.push_back(NewCap); 10511 } 10512 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10513 BSI->CXXThisCaptureIndex != 0); 10514 10515 // If the user wrote a function type in some form, try to use that. 10516 if (!BSI->FunctionType.isNull()) { 10517 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10518 10519 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10520 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10521 10522 // Turn protoless block types into nullary block types. 10523 if (isa<FunctionNoProtoType>(FTy)) { 10524 FunctionProtoType::ExtProtoInfo EPI; 10525 EPI.ExtInfo = Ext; 10526 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10527 10528 // Otherwise, if we don't need to change anything about the function type, 10529 // preserve its sugar structure. 10530 } else if (FTy->getReturnType() == RetTy && 10531 (!NoReturn || FTy->getNoReturnAttr())) { 10532 BlockTy = BSI->FunctionType; 10533 10534 // Otherwise, make the minimal modifications to the function type. 10535 } else { 10536 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10537 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10538 EPI.TypeQuals = 0; // FIXME: silently? 10539 EPI.ExtInfo = Ext; 10540 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 10541 } 10542 10543 // If we don't have a function type, just build one from nothing. 10544 } else { 10545 FunctionProtoType::ExtProtoInfo EPI; 10546 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10547 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10548 } 10549 10550 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10551 BSI->TheDecl->param_end()); 10552 BlockTy = Context.getBlockPointerType(BlockTy); 10553 10554 // If needed, diagnose invalid gotos and switches in the block. 10555 if (getCurFunction()->NeedsScopeChecking() && 10556 !hasAnyUnrecoverableErrorsInThisFunction() && 10557 !PP.isCodeCompletionEnabled()) 10558 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10559 10560 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10561 10562 // Try to apply the named return value optimization. We have to check again 10563 // if we can do this, though, because blocks keep return statements around 10564 // to deduce an implicit return type. 10565 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10566 !BSI->TheDecl->isDependentContext()) 10567 computeNRVO(Body, getCurBlock()); 10568 10569 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10570 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10571 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10572 10573 // If the block isn't obviously global, i.e. it captures anything at 10574 // all, then we need to do a few things in the surrounding context: 10575 if (Result->getBlockDecl()->hasCaptures()) { 10576 // First, this expression has a new cleanup object. 10577 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10578 ExprNeedsCleanups = true; 10579 10580 // It also gets a branch-protected scope if any of the captured 10581 // variables needs destruction. 10582 for (BlockDecl::capture_const_iterator 10583 ci = Result->getBlockDecl()->capture_begin(), 10584 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10585 const VarDecl *var = ci->getVariable(); 10586 if (var->getType().isDestructedType() != QualType::DK_none) { 10587 getCurFunction()->setHasBranchProtectedScope(); 10588 break; 10589 } 10590 } 10591 } 10592 10593 return Owned(Result); 10594 } 10595 10596 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10597 Expr *E, ParsedType Ty, 10598 SourceLocation RPLoc) { 10599 TypeSourceInfo *TInfo; 10600 GetTypeFromParser(Ty, &TInfo); 10601 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10602 } 10603 10604 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10605 Expr *E, TypeSourceInfo *TInfo, 10606 SourceLocation RPLoc) { 10607 Expr *OrigExpr = E; 10608 10609 // Get the va_list type 10610 QualType VaListType = Context.getBuiltinVaListType(); 10611 if (VaListType->isArrayType()) { 10612 // Deal with implicit array decay; for example, on x86-64, 10613 // va_list is an array, but it's supposed to decay to 10614 // a pointer for va_arg. 10615 VaListType = Context.getArrayDecayedType(VaListType); 10616 // Make sure the input expression also decays appropriately. 10617 ExprResult Result = UsualUnaryConversions(E); 10618 if (Result.isInvalid()) 10619 return ExprError(); 10620 E = Result.take(); 10621 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10622 // If va_list is a record type and we are compiling in C++ mode, 10623 // check the argument using reference binding. 10624 InitializedEntity Entity 10625 = InitializedEntity::InitializeParameter(Context, 10626 Context.getLValueReferenceType(VaListType), false); 10627 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10628 if (Init.isInvalid()) 10629 return ExprError(); 10630 E = Init.takeAs<Expr>(); 10631 } else { 10632 // Otherwise, the va_list argument must be an l-value because 10633 // it is modified by va_arg. 10634 if (!E->isTypeDependent() && 10635 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10636 return ExprError(); 10637 } 10638 10639 if (!E->isTypeDependent() && 10640 !Context.hasSameType(VaListType, E->getType())) { 10641 return ExprError(Diag(E->getLocStart(), 10642 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10643 << OrigExpr->getType() << E->getSourceRange()); 10644 } 10645 10646 if (!TInfo->getType()->isDependentType()) { 10647 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10648 diag::err_second_parameter_to_va_arg_incomplete, 10649 TInfo->getTypeLoc())) 10650 return ExprError(); 10651 10652 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10653 TInfo->getType(), 10654 diag::err_second_parameter_to_va_arg_abstract, 10655 TInfo->getTypeLoc())) 10656 return ExprError(); 10657 10658 if (!TInfo->getType().isPODType(Context)) { 10659 Diag(TInfo->getTypeLoc().getBeginLoc(), 10660 TInfo->getType()->isObjCLifetimeType() 10661 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10662 : diag::warn_second_parameter_to_va_arg_not_pod) 10663 << TInfo->getType() 10664 << TInfo->getTypeLoc().getSourceRange(); 10665 } 10666 10667 // Check for va_arg where arguments of the given type will be promoted 10668 // (i.e. this va_arg is guaranteed to have undefined behavior). 10669 QualType PromoteType; 10670 if (TInfo->getType()->isPromotableIntegerType()) { 10671 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10672 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10673 PromoteType = QualType(); 10674 } 10675 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10676 PromoteType = Context.DoubleTy; 10677 if (!PromoteType.isNull()) 10678 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10679 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10680 << TInfo->getType() 10681 << PromoteType 10682 << TInfo->getTypeLoc().getSourceRange()); 10683 } 10684 10685 QualType T = TInfo->getType().getNonLValueExprType(Context); 10686 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10687 } 10688 10689 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10690 // The type of __null will be int or long, depending on the size of 10691 // pointers on the target. 10692 QualType Ty; 10693 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10694 if (pw == Context.getTargetInfo().getIntWidth()) 10695 Ty = Context.IntTy; 10696 else if (pw == Context.getTargetInfo().getLongWidth()) 10697 Ty = Context.LongTy; 10698 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10699 Ty = Context.LongLongTy; 10700 else { 10701 llvm_unreachable("I don't know size of pointer!"); 10702 } 10703 10704 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10705 } 10706 10707 bool 10708 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 10709 if (!getLangOpts().ObjC1) 10710 return false; 10711 10712 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10713 if (!PT) 10714 return false; 10715 10716 if (!PT->isObjCIdType()) { 10717 // Check if the destination is the 'NSString' interface. 10718 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10719 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10720 return false; 10721 } 10722 10723 // Ignore any parens, implicit casts (should only be 10724 // array-to-pointer decays), and not-so-opaque values. The last is 10725 // important for making this trigger for property assignments. 10726 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 10727 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10728 if (OV->getSourceExpr()) 10729 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10730 10731 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10732 if (!SL || !SL->isAscii()) 10733 return false; 10734 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 10735 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10736 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).take(); 10737 return true; 10738 } 10739 10740 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10741 SourceLocation Loc, 10742 QualType DstType, QualType SrcType, 10743 Expr *SrcExpr, AssignmentAction Action, 10744 bool *Complained) { 10745 if (Complained) 10746 *Complained = false; 10747 10748 // Decode the result (notice that AST's are still created for extensions). 10749 bool CheckInferredResultType = false; 10750 bool isInvalid = false; 10751 unsigned DiagKind = 0; 10752 FixItHint Hint; 10753 ConversionFixItGenerator ConvHints; 10754 bool MayHaveConvFixit = false; 10755 bool MayHaveFunctionDiff = false; 10756 10757 switch (ConvTy) { 10758 case Compatible: 10759 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10760 return false; 10761 10762 case PointerToInt: 10763 DiagKind = diag::ext_typecheck_convert_pointer_int; 10764 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10765 MayHaveConvFixit = true; 10766 break; 10767 case IntToPointer: 10768 DiagKind = diag::ext_typecheck_convert_int_pointer; 10769 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10770 MayHaveConvFixit = true; 10771 break; 10772 case IncompatiblePointer: 10773 DiagKind = 10774 (Action == AA_Passing_CFAudited ? 10775 diag::err_arc_typecheck_convert_incompatible_pointer : 10776 diag::ext_typecheck_convert_incompatible_pointer); 10777 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10778 SrcType->isObjCObjectPointerType(); 10779 if (Hint.isNull() && !CheckInferredResultType) { 10780 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10781 } 10782 else if (CheckInferredResultType) { 10783 SrcType = SrcType.getUnqualifiedType(); 10784 DstType = DstType.getUnqualifiedType(); 10785 } 10786 MayHaveConvFixit = true; 10787 break; 10788 case IncompatiblePointerSign: 10789 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10790 break; 10791 case FunctionVoidPointer: 10792 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10793 break; 10794 case IncompatiblePointerDiscardsQualifiers: { 10795 // Perform array-to-pointer decay if necessary. 10796 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10797 10798 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10799 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10800 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10801 DiagKind = diag::err_typecheck_incompatible_address_space; 10802 break; 10803 10804 10805 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10806 DiagKind = diag::err_typecheck_incompatible_ownership; 10807 break; 10808 } 10809 10810 llvm_unreachable("unknown error case for discarding qualifiers!"); 10811 // fallthrough 10812 } 10813 case CompatiblePointerDiscardsQualifiers: 10814 // If the qualifiers lost were because we were applying the 10815 // (deprecated) C++ conversion from a string literal to a char* 10816 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10817 // Ideally, this check would be performed in 10818 // checkPointerTypesForAssignment. However, that would require a 10819 // bit of refactoring (so that the second argument is an 10820 // expression, rather than a type), which should be done as part 10821 // of a larger effort to fix checkPointerTypesForAssignment for 10822 // C++ semantics. 10823 if (getLangOpts().CPlusPlus && 10824 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10825 return false; 10826 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10827 break; 10828 case IncompatibleNestedPointerQualifiers: 10829 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10830 break; 10831 case IntToBlockPointer: 10832 DiagKind = diag::err_int_to_block_pointer; 10833 break; 10834 case IncompatibleBlockPointer: 10835 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10836 break; 10837 case IncompatibleObjCQualifiedId: 10838 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10839 // it can give a more specific diagnostic. 10840 DiagKind = diag::warn_incompatible_qualified_id; 10841 break; 10842 case IncompatibleVectors: 10843 DiagKind = diag::warn_incompatible_vectors; 10844 break; 10845 case IncompatibleObjCWeakRef: 10846 DiagKind = diag::err_arc_weak_unavailable_assign; 10847 break; 10848 case Incompatible: 10849 DiagKind = diag::err_typecheck_convert_incompatible; 10850 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10851 MayHaveConvFixit = true; 10852 isInvalid = true; 10853 MayHaveFunctionDiff = true; 10854 break; 10855 } 10856 10857 QualType FirstType, SecondType; 10858 switch (Action) { 10859 case AA_Assigning: 10860 case AA_Initializing: 10861 // The destination type comes first. 10862 FirstType = DstType; 10863 SecondType = SrcType; 10864 break; 10865 10866 case AA_Returning: 10867 case AA_Passing: 10868 case AA_Passing_CFAudited: 10869 case AA_Converting: 10870 case AA_Sending: 10871 case AA_Casting: 10872 // The source type comes first. 10873 FirstType = SrcType; 10874 SecondType = DstType; 10875 break; 10876 } 10877 10878 PartialDiagnostic FDiag = PDiag(DiagKind); 10879 if (Action == AA_Passing_CFAudited) 10880 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 10881 else 10882 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10883 10884 // If we can fix the conversion, suggest the FixIts. 10885 assert(ConvHints.isNull() || Hint.isNull()); 10886 if (!ConvHints.isNull()) { 10887 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10888 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10889 FDiag << *HI; 10890 } else { 10891 FDiag << Hint; 10892 } 10893 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10894 10895 if (MayHaveFunctionDiff) 10896 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10897 10898 Diag(Loc, FDiag); 10899 10900 if (SecondType == Context.OverloadTy) 10901 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10902 FirstType); 10903 10904 if (CheckInferredResultType) 10905 EmitRelatedResultTypeNote(SrcExpr); 10906 10907 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10908 EmitRelatedResultTypeNoteForReturn(DstType); 10909 10910 if (Complained) 10911 *Complained = true; 10912 return isInvalid; 10913 } 10914 10915 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10916 llvm::APSInt *Result) { 10917 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10918 public: 10919 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10920 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10921 } 10922 } Diagnoser; 10923 10924 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10925 } 10926 10927 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10928 llvm::APSInt *Result, 10929 unsigned DiagID, 10930 bool AllowFold) { 10931 class IDDiagnoser : public VerifyICEDiagnoser { 10932 unsigned DiagID; 10933 10934 public: 10935 IDDiagnoser(unsigned DiagID) 10936 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10937 10938 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10939 S.Diag(Loc, DiagID) << SR; 10940 } 10941 } Diagnoser(DiagID); 10942 10943 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10944 } 10945 10946 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10947 SourceRange SR) { 10948 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10949 } 10950 10951 ExprResult 10952 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10953 VerifyICEDiagnoser &Diagnoser, 10954 bool AllowFold) { 10955 SourceLocation DiagLoc = E->getLocStart(); 10956 10957 if (getLangOpts().CPlusPlus11) { 10958 // C++11 [expr.const]p5: 10959 // If an expression of literal class type is used in a context where an 10960 // integral constant expression is required, then that class type shall 10961 // have a single non-explicit conversion function to an integral or 10962 // unscoped enumeration type 10963 ExprResult Converted; 10964 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10965 public: 10966 CXX11ConvertDiagnoser(bool Silent) 10967 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10968 Silent, true) {} 10969 10970 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10971 QualType T) { 10972 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10973 } 10974 10975 virtual SemaDiagnosticBuilder diagnoseIncomplete( 10976 Sema &S, SourceLocation Loc, QualType T) { 10977 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10978 } 10979 10980 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 10981 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10982 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10983 } 10984 10985 virtual SemaDiagnosticBuilder noteExplicitConv( 10986 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10987 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10988 << ConvTy->isEnumeralType() << ConvTy; 10989 } 10990 10991 virtual SemaDiagnosticBuilder diagnoseAmbiguous( 10992 Sema &S, SourceLocation Loc, QualType T) { 10993 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10994 } 10995 10996 virtual SemaDiagnosticBuilder noteAmbiguous( 10997 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10998 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10999 << ConvTy->isEnumeralType() << ConvTy; 11000 } 11001 11002 virtual SemaDiagnosticBuilder diagnoseConversion( 11003 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 11004 llvm_unreachable("conversion functions are permitted"); 11005 } 11006 } ConvertDiagnoser(Diagnoser.Suppress); 11007 11008 Converted = PerformContextualImplicitConversion(DiagLoc, E, 11009 ConvertDiagnoser); 11010 if (Converted.isInvalid()) 11011 return Converted; 11012 E = Converted.take(); 11013 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 11014 return ExprError(); 11015 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11016 // An ICE must be of integral or unscoped enumeration type. 11017 if (!Diagnoser.Suppress) 11018 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11019 return ExprError(); 11020 } 11021 11022 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 11023 // in the non-ICE case. 11024 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 11025 if (Result) 11026 *Result = E->EvaluateKnownConstInt(Context); 11027 return Owned(E); 11028 } 11029 11030 Expr::EvalResult EvalResult; 11031 SmallVector<PartialDiagnosticAt, 8> Notes; 11032 EvalResult.Diag = &Notes; 11033 11034 // Try to evaluate the expression, and produce diagnostics explaining why it's 11035 // not a constant expression as a side-effect. 11036 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 11037 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 11038 11039 // In C++11, we can rely on diagnostics being produced for any expression 11040 // which is not a constant expression. If no diagnostics were produced, then 11041 // this is a constant expression. 11042 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 11043 if (Result) 11044 *Result = EvalResult.Val.getInt(); 11045 return Owned(E); 11046 } 11047 11048 // If our only note is the usual "invalid subexpression" note, just point 11049 // the caret at its location rather than producing an essentially 11050 // redundant note. 11051 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11052 diag::note_invalid_subexpr_in_const_expr) { 11053 DiagLoc = Notes[0].first; 11054 Notes.clear(); 11055 } 11056 11057 if (!Folded || !AllowFold) { 11058 if (!Diagnoser.Suppress) { 11059 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11060 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11061 Diag(Notes[I].first, Notes[I].second); 11062 } 11063 11064 return ExprError(); 11065 } 11066 11067 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 11068 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11069 Diag(Notes[I].first, Notes[I].second); 11070 11071 if (Result) 11072 *Result = EvalResult.Val.getInt(); 11073 return Owned(E); 11074 } 11075 11076 namespace { 11077 // Handle the case where we conclude a expression which we speculatively 11078 // considered to be unevaluated is actually evaluated. 11079 class TransformToPE : public TreeTransform<TransformToPE> { 11080 typedef TreeTransform<TransformToPE> BaseTransform; 11081 11082 public: 11083 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 11084 11085 // Make sure we redo semantic analysis 11086 bool AlwaysRebuild() { return true; } 11087 11088 // Make sure we handle LabelStmts correctly. 11089 // FIXME: This does the right thing, but maybe we need a more general 11090 // fix to TreeTransform? 11091 StmtResult TransformLabelStmt(LabelStmt *S) { 11092 S->getDecl()->setStmt(0); 11093 return BaseTransform::TransformLabelStmt(S); 11094 } 11095 11096 // We need to special-case DeclRefExprs referring to FieldDecls which 11097 // are not part of a member pointer formation; normal TreeTransforming 11098 // doesn't catch this case because of the way we represent them in the AST. 11099 // FIXME: This is a bit ugly; is it really the best way to handle this 11100 // case? 11101 // 11102 // Error on DeclRefExprs referring to FieldDecls. 11103 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 11104 if (isa<FieldDecl>(E->getDecl()) && 11105 !SemaRef.isUnevaluatedContext()) 11106 return SemaRef.Diag(E->getLocation(), 11107 diag::err_invalid_non_static_member_use) 11108 << E->getDecl() << E->getSourceRange(); 11109 11110 return BaseTransform::TransformDeclRefExpr(E); 11111 } 11112 11113 // Exception: filter out member pointer formation 11114 ExprResult TransformUnaryOperator(UnaryOperator *E) { 11115 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 11116 return E; 11117 11118 return BaseTransform::TransformUnaryOperator(E); 11119 } 11120 11121 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11122 // Lambdas never need to be transformed. 11123 return E; 11124 } 11125 }; 11126 } 11127 11128 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 11129 assert(isUnevaluatedContext() && 11130 "Should only transform unevaluated expressions"); 11131 ExprEvalContexts.back().Context = 11132 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 11133 if (isUnevaluatedContext()) 11134 return E; 11135 return TransformToPE(*this).TransformExpr(E); 11136 } 11137 11138 void 11139 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11140 Decl *LambdaContextDecl, 11141 bool IsDecltype) { 11142 ExprEvalContexts.push_back( 11143 ExpressionEvaluationContextRecord(NewContext, 11144 ExprCleanupObjects.size(), 11145 ExprNeedsCleanups, 11146 LambdaContextDecl, 11147 IsDecltype)); 11148 ExprNeedsCleanups = false; 11149 if (!MaybeODRUseExprs.empty()) 11150 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11151 } 11152 11153 void 11154 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11155 ReuseLambdaContextDecl_t, 11156 bool IsDecltype) { 11157 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11158 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11159 } 11160 11161 void Sema::PopExpressionEvaluationContext() { 11162 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11163 11164 if (!Rec.Lambdas.empty()) { 11165 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11166 unsigned D; 11167 if (Rec.isUnevaluated()) { 11168 // C++11 [expr.prim.lambda]p2: 11169 // A lambda-expression shall not appear in an unevaluated operand 11170 // (Clause 5). 11171 D = diag::err_lambda_unevaluated_operand; 11172 } else { 11173 // C++1y [expr.const]p2: 11174 // A conditional-expression e is a core constant expression unless the 11175 // evaluation of e, following the rules of the abstract machine, would 11176 // evaluate [...] a lambda-expression. 11177 D = diag::err_lambda_in_constant_expression; 11178 } 11179 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 11180 Diag(Rec.Lambdas[I]->getLocStart(), D); 11181 } else { 11182 // Mark the capture expressions odr-used. This was deferred 11183 // during lambda expression creation. 11184 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 11185 LambdaExpr *Lambda = Rec.Lambdas[I]; 11186 for (LambdaExpr::capture_init_iterator 11187 C = Lambda->capture_init_begin(), 11188 CEnd = Lambda->capture_init_end(); 11189 C != CEnd; ++C) { 11190 MarkDeclarationsReferencedInExpr(*C); 11191 } 11192 } 11193 } 11194 } 11195 11196 // When are coming out of an unevaluated context, clear out any 11197 // temporaries that we may have created as part of the evaluation of 11198 // the expression in that context: they aren't relevant because they 11199 // will never be constructed. 11200 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11201 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 11202 ExprCleanupObjects.end()); 11203 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 11204 CleanupVarDeclMarking(); 11205 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 11206 // Otherwise, merge the contexts together. 11207 } else { 11208 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 11209 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 11210 Rec.SavedMaybeODRUseExprs.end()); 11211 } 11212 11213 // Pop the current expression evaluation context off the stack. 11214 ExprEvalContexts.pop_back(); 11215 } 11216 11217 void Sema::DiscardCleanupsInEvaluationContext() { 11218 ExprCleanupObjects.erase( 11219 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 11220 ExprCleanupObjects.end()); 11221 ExprNeedsCleanups = false; 11222 MaybeODRUseExprs.clear(); 11223 } 11224 11225 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 11226 if (!E->getType()->isVariablyModifiedType()) 11227 return E; 11228 return TransformToPotentiallyEvaluated(E); 11229 } 11230 11231 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11232 // Do not mark anything as "used" within a dependent context; wait for 11233 // an instantiation. 11234 if (SemaRef.CurContext->isDependentContext()) 11235 return false; 11236 11237 switch (SemaRef.ExprEvalContexts.back().Context) { 11238 case Sema::Unevaluated: 11239 case Sema::UnevaluatedAbstract: 11240 // We are in an expression that is not potentially evaluated; do nothing. 11241 // (Depending on how you read the standard, we actually do need to do 11242 // something here for null pointer constants, but the standard's 11243 // definition of a null pointer constant is completely crazy.) 11244 return false; 11245 11246 case Sema::ConstantEvaluated: 11247 case Sema::PotentiallyEvaluated: 11248 // We are in a potentially evaluated expression (or a constant-expression 11249 // in C++03); we need to do implicit template instantiation, implicitly 11250 // define class members, and mark most declarations as used. 11251 return true; 11252 11253 case Sema::PotentiallyEvaluatedIfUsed: 11254 // Referenced declarations will only be used if the construct in the 11255 // containing expression is used. 11256 return false; 11257 } 11258 llvm_unreachable("Invalid context"); 11259 } 11260 11261 /// \brief Mark a function referenced, and check whether it is odr-used 11262 /// (C++ [basic.def.odr]p2, C99 6.9p3) 11263 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 11264 assert(Func && "No function?"); 11265 11266 Func->setReferenced(); 11267 11268 // C++11 [basic.def.odr]p3: 11269 // A function whose name appears as a potentially-evaluated expression is 11270 // odr-used if it is the unique lookup result or the selected member of a 11271 // set of overloaded functions [...]. 11272 // 11273 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11274 // can just check that here. Skip the rest of this function if we've already 11275 // marked the function as used. 11276 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11277 // C++11 [temp.inst]p3: 11278 // Unless a function template specialization has been explicitly 11279 // instantiated or explicitly specialized, the function template 11280 // specialization is implicitly instantiated when the specialization is 11281 // referenced in a context that requires a function definition to exist. 11282 // 11283 // We consider constexpr function templates to be referenced in a context 11284 // that requires a definition to exist whenever they are referenced. 11285 // 11286 // FIXME: This instantiates constexpr functions too frequently. If this is 11287 // really an unevaluated context (and we're not just in the definition of a 11288 // function template or overload resolution or other cases which we 11289 // incorrectly consider to be unevaluated contexts), and we're not in a 11290 // subexpression which we actually need to evaluate (for instance, a 11291 // template argument, array bound or an expression in a braced-init-list), 11292 // we are not permitted to instantiate this constexpr function definition. 11293 // 11294 // FIXME: This also implicitly defines special members too frequently. They 11295 // are only supposed to be implicitly defined if they are odr-used, but they 11296 // are not odr-used from constant expressions in unevaluated contexts. 11297 // However, they cannot be referenced if they are deleted, and they are 11298 // deleted whenever the implicit definition of the special member would 11299 // fail. 11300 if (!Func->isConstexpr() || Func->getBody()) 11301 return; 11302 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11303 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11304 return; 11305 } 11306 11307 // Note that this declaration has been used. 11308 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11309 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 11310 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11311 if (Constructor->isDefaultConstructor()) { 11312 if (Constructor->isTrivial()) 11313 return; 11314 DefineImplicitDefaultConstructor(Loc, Constructor); 11315 } else if (Constructor->isCopyConstructor()) { 11316 DefineImplicitCopyConstructor(Loc, Constructor); 11317 } else if (Constructor->isMoveConstructor()) { 11318 DefineImplicitMoveConstructor(Loc, Constructor); 11319 } 11320 } else if (Constructor->getInheritedConstructor()) { 11321 DefineInheritingConstructor(Loc, Constructor); 11322 } 11323 11324 MarkVTableUsed(Loc, Constructor->getParent()); 11325 } else if (CXXDestructorDecl *Destructor = 11326 dyn_cast<CXXDestructorDecl>(Func)) { 11327 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 11328 if (Destructor->isDefaulted() && !Destructor->isDeleted()) 11329 DefineImplicitDestructor(Loc, Destructor); 11330 if (Destructor->isVirtual()) 11331 MarkVTableUsed(Loc, Destructor->getParent()); 11332 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11333 if (MethodDecl->isOverloadedOperator() && 11334 MethodDecl->getOverloadedOperator() == OO_Equal) { 11335 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 11336 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 11337 if (MethodDecl->isCopyAssignmentOperator()) 11338 DefineImplicitCopyAssignment(Loc, MethodDecl); 11339 else 11340 DefineImplicitMoveAssignment(Loc, MethodDecl); 11341 } 11342 } else if (isa<CXXConversionDecl>(MethodDecl) && 11343 MethodDecl->getParent()->isLambda()) { 11344 CXXConversionDecl *Conversion = 11345 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 11346 if (Conversion->isLambdaToBlockPointerConversion()) 11347 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11348 else 11349 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11350 } else if (MethodDecl->isVirtual()) 11351 MarkVTableUsed(Loc, MethodDecl->getParent()); 11352 } 11353 11354 // Recursive functions should be marked when used from another function. 11355 // FIXME: Is this really right? 11356 if (CurContext == Func) return; 11357 11358 // Resolve the exception specification for any function which is 11359 // used: CodeGen will need it. 11360 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11361 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11362 ResolveExceptionSpec(Loc, FPT); 11363 11364 // Implicit instantiation of function templates and member functions of 11365 // class templates. 11366 if (Func->isImplicitlyInstantiable()) { 11367 bool AlreadyInstantiated = false; 11368 SourceLocation PointOfInstantiation = Loc; 11369 if (FunctionTemplateSpecializationInfo *SpecInfo 11370 = Func->getTemplateSpecializationInfo()) { 11371 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11372 SpecInfo->setPointOfInstantiation(Loc); 11373 else if (SpecInfo->getTemplateSpecializationKind() 11374 == TSK_ImplicitInstantiation) { 11375 AlreadyInstantiated = true; 11376 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11377 } 11378 } else if (MemberSpecializationInfo *MSInfo 11379 = Func->getMemberSpecializationInfo()) { 11380 if (MSInfo->getPointOfInstantiation().isInvalid()) 11381 MSInfo->setPointOfInstantiation(Loc); 11382 else if (MSInfo->getTemplateSpecializationKind() 11383 == TSK_ImplicitInstantiation) { 11384 AlreadyInstantiated = true; 11385 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11386 } 11387 } 11388 11389 if (!AlreadyInstantiated || Func->isConstexpr()) { 11390 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11391 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11392 ActiveTemplateInstantiations.size()) 11393 PendingLocalImplicitInstantiations.push_back( 11394 std::make_pair(Func, PointOfInstantiation)); 11395 else if (Func->isConstexpr()) 11396 // Do not defer instantiations of constexpr functions, to avoid the 11397 // expression evaluator needing to call back into Sema if it sees a 11398 // call to such a function. 11399 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11400 else { 11401 PendingInstantiations.push_back(std::make_pair(Func, 11402 PointOfInstantiation)); 11403 // Notify the consumer that a function was implicitly instantiated. 11404 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11405 } 11406 } 11407 } else { 11408 // Walk redefinitions, as some of them may be instantiable. 11409 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 11410 e(Func->redecls_end()); i != e; ++i) { 11411 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11412 MarkFunctionReferenced(Loc, *i); 11413 } 11414 } 11415 11416 // Keep track of used but undefined functions. 11417 if (!Func->isDefined()) { 11418 if (mightHaveNonExternalLinkage(Func)) 11419 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11420 else if (Func->getMostRecentDecl()->isInlined() && 11421 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11422 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11423 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11424 } 11425 11426 // Normally the most current decl is marked used while processing the use and 11427 // any subsequent decls are marked used by decl merging. This fails with 11428 // template instantiation since marking can happen at the end of the file 11429 // and, because of the two phase lookup, this function is called with at 11430 // decl in the middle of a decl chain. We loop to maintain the invariant 11431 // that once a decl is used, all decls after it are also used. 11432 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11433 F->markUsed(Context); 11434 if (F == Func) 11435 break; 11436 } 11437 } 11438 11439 static void 11440 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11441 VarDecl *var, DeclContext *DC) { 11442 DeclContext *VarDC = var->getDeclContext(); 11443 11444 // If the parameter still belongs to the translation unit, then 11445 // we're actually just using one parameter in the declaration of 11446 // the next. 11447 if (isa<ParmVarDecl>(var) && 11448 isa<TranslationUnitDecl>(VarDC)) 11449 return; 11450 11451 // For C code, don't diagnose about capture if we're not actually in code 11452 // right now; it's impossible to write a non-constant expression outside of 11453 // function context, so we'll get other (more useful) diagnostics later. 11454 // 11455 // For C++, things get a bit more nasty... it would be nice to suppress this 11456 // diagnostic for certain cases like using a local variable in an array bound 11457 // for a member of a local class, but the correct predicate is not obvious. 11458 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11459 return; 11460 11461 if (isa<CXXMethodDecl>(VarDC) && 11462 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11463 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11464 << var->getIdentifier(); 11465 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11466 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11467 << var->getIdentifier() << fn->getDeclName(); 11468 } else if (isa<BlockDecl>(VarDC)) { 11469 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11470 << var->getIdentifier(); 11471 } else { 11472 // FIXME: Is there any other context where a local variable can be 11473 // declared? 11474 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11475 << var->getIdentifier(); 11476 } 11477 11478 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 11479 << var->getIdentifier(); 11480 11481 // FIXME: Add additional diagnostic info about class etc. which prevents 11482 // capture. 11483 } 11484 11485 11486 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11487 bool &SubCapturesAreNested, 11488 QualType &CaptureType, 11489 QualType &DeclRefType) { 11490 // Check whether we've already captured it. 11491 if (CSI->CaptureMap.count(Var)) { 11492 // If we found a capture, any subcaptures are nested. 11493 SubCapturesAreNested = true; 11494 11495 // Retrieve the capture type for this variable. 11496 CaptureType = CSI->getCapture(Var).getCaptureType(); 11497 11498 // Compute the type of an expression that refers to this variable. 11499 DeclRefType = CaptureType.getNonReferenceType(); 11500 11501 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11502 if (Cap.isCopyCapture() && 11503 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11504 DeclRefType.addConst(); 11505 return true; 11506 } 11507 return false; 11508 } 11509 11510 // Only block literals, captured statements, and lambda expressions can 11511 // capture; other scopes don't work. 11512 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11513 SourceLocation Loc, 11514 const bool Diagnose, Sema &S) { 11515 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 11516 return getLambdaAwareParentOfDeclContext(DC); 11517 else { 11518 if (Diagnose) 11519 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11520 } 11521 return 0; 11522 } 11523 11524 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11525 // certain types of variables (unnamed, variably modified types etc.) 11526 // so check for eligibility. 11527 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11528 SourceLocation Loc, 11529 const bool Diagnose, Sema &S) { 11530 11531 bool IsBlock = isa<BlockScopeInfo>(CSI); 11532 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11533 11534 // Lambdas are not allowed to capture unnamed variables 11535 // (e.g. anonymous unions). 11536 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11537 // assuming that's the intent. 11538 if (IsLambda && !Var->getDeclName()) { 11539 if (Diagnose) { 11540 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11541 S.Diag(Var->getLocation(), diag::note_declared_at); 11542 } 11543 return false; 11544 } 11545 11546 // Prohibit variably-modified types; they're difficult to deal with. 11547 if (Var->getType()->isVariablyModifiedType()) { 11548 if (Diagnose) { 11549 if (IsBlock) 11550 S.Diag(Loc, diag::err_ref_vm_type); 11551 else 11552 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11553 S.Diag(Var->getLocation(), diag::note_previous_decl) 11554 << Var->getDeclName(); 11555 } 11556 return false; 11557 } 11558 // Prohibit structs with flexible array members too. 11559 // We cannot capture what is in the tail end of the struct. 11560 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11561 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11562 if (Diagnose) { 11563 if (IsBlock) 11564 S.Diag(Loc, diag::err_ref_flexarray_type); 11565 else 11566 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11567 << Var->getDeclName(); 11568 S.Diag(Var->getLocation(), diag::note_previous_decl) 11569 << Var->getDeclName(); 11570 } 11571 return false; 11572 } 11573 } 11574 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11575 // Lambdas and captured statements are not allowed to capture __block 11576 // variables; they don't support the expected semantics. 11577 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11578 if (Diagnose) { 11579 S.Diag(Loc, diag::err_capture_block_variable) 11580 << Var->getDeclName() << !IsLambda; 11581 S.Diag(Var->getLocation(), diag::note_previous_decl) 11582 << Var->getDeclName(); 11583 } 11584 return false; 11585 } 11586 11587 return true; 11588 } 11589 11590 // Returns true if the capture by block was successful. 11591 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11592 SourceLocation Loc, 11593 const bool BuildAndDiagnose, 11594 QualType &CaptureType, 11595 QualType &DeclRefType, 11596 const bool Nested, 11597 Sema &S) { 11598 Expr *CopyExpr = 0; 11599 bool ByRef = false; 11600 11601 // Blocks are not allowed to capture arrays. 11602 if (CaptureType->isArrayType()) { 11603 if (BuildAndDiagnose) { 11604 S.Diag(Loc, diag::err_ref_array_type); 11605 S.Diag(Var->getLocation(), diag::note_previous_decl) 11606 << Var->getDeclName(); 11607 } 11608 return false; 11609 } 11610 11611 // Forbid the block-capture of autoreleasing variables. 11612 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11613 if (BuildAndDiagnose) { 11614 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11615 << /*block*/ 0; 11616 S.Diag(Var->getLocation(), diag::note_previous_decl) 11617 << Var->getDeclName(); 11618 } 11619 return false; 11620 } 11621 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11622 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11623 // Block capture by reference does not change the capture or 11624 // declaration reference types. 11625 ByRef = true; 11626 } else { 11627 // Block capture by copy introduces 'const'. 11628 CaptureType = CaptureType.getNonReferenceType().withConst(); 11629 DeclRefType = CaptureType; 11630 11631 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11632 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11633 // The capture logic needs the destructor, so make sure we mark it. 11634 // Usually this is unnecessary because most local variables have 11635 // their destructors marked at declaration time, but parameters are 11636 // an exception because it's technically only the call site that 11637 // actually requires the destructor. 11638 if (isa<ParmVarDecl>(Var)) 11639 S.FinalizeVarWithDestructor(Var, Record); 11640 11641 // Enter a new evaluation context to insulate the copy 11642 // full-expression. 11643 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11644 11645 // According to the blocks spec, the capture of a variable from 11646 // the stack requires a const copy constructor. This is not true 11647 // of the copy/move done to move a __block variable to the heap. 11648 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11649 DeclRefType.withConst(), 11650 VK_LValue, Loc); 11651 11652 ExprResult Result 11653 = S.PerformCopyInitialization( 11654 InitializedEntity::InitializeBlock(Var->getLocation(), 11655 CaptureType, false), 11656 Loc, S.Owned(DeclRef)); 11657 11658 // Build a full-expression copy expression if initialization 11659 // succeeded and used a non-trivial constructor. Recover from 11660 // errors by pretending that the copy isn't necessary. 11661 if (!Result.isInvalid() && 11662 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11663 ->isTrivial()) { 11664 Result = S.MaybeCreateExprWithCleanups(Result); 11665 CopyExpr = Result.take(); 11666 } 11667 } 11668 } 11669 } 11670 11671 // Actually capture the variable. 11672 if (BuildAndDiagnose) 11673 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11674 SourceLocation(), CaptureType, CopyExpr); 11675 11676 return true; 11677 11678 } 11679 11680 11681 /// \brief Capture the given variable in the captured region. 11682 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11683 VarDecl *Var, 11684 SourceLocation Loc, 11685 const bool BuildAndDiagnose, 11686 QualType &CaptureType, 11687 QualType &DeclRefType, 11688 const bool RefersToEnclosingLocal, 11689 Sema &S) { 11690 11691 // By default, capture variables by reference. 11692 bool ByRef = true; 11693 // Using an LValue reference type is consistent with Lambdas (see below). 11694 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11695 Expr *CopyExpr = 0; 11696 if (BuildAndDiagnose) { 11697 // The current implementation assumes that all variables are captured 11698 // by references. Since there is no capture by copy, no expression evaluation 11699 // will be needed. 11700 // 11701 RecordDecl *RD = RSI->TheRecordDecl; 11702 11703 FieldDecl *Field 11704 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType, 11705 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11706 0, false, ICIS_NoInit); 11707 Field->setImplicit(true); 11708 Field->setAccess(AS_private); 11709 RD->addDecl(Field); 11710 11711 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11712 DeclRefType, VK_LValue, Loc); 11713 Var->setReferenced(true); 11714 Var->markUsed(S.Context); 11715 } 11716 11717 // Actually capture the variable. 11718 if (BuildAndDiagnose) 11719 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11720 SourceLocation(), CaptureType, CopyExpr); 11721 11722 11723 return true; 11724 } 11725 11726 /// \brief Create a field within the lambda class for the variable 11727 /// being captured. Handle Array captures. 11728 static ExprResult addAsFieldToClosureType(Sema &S, 11729 LambdaScopeInfo *LSI, 11730 VarDecl *Var, QualType FieldType, 11731 QualType DeclRefType, 11732 SourceLocation Loc, 11733 bool RefersToEnclosingLocal) { 11734 CXXRecordDecl *Lambda = LSI->Lambda; 11735 11736 // Build the non-static data member. 11737 FieldDecl *Field 11738 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11739 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11740 0, false, ICIS_NoInit); 11741 Field->setImplicit(true); 11742 Field->setAccess(AS_private); 11743 Lambda->addDecl(Field); 11744 11745 // C++11 [expr.prim.lambda]p21: 11746 // When the lambda-expression is evaluated, the entities that 11747 // are captured by copy are used to direct-initialize each 11748 // corresponding non-static data member of the resulting closure 11749 // object. (For array members, the array elements are 11750 // direct-initialized in increasing subscript order.) These 11751 // initializations are performed in the (unspecified) order in 11752 // which the non-static data members are declared. 11753 11754 // Introduce a new evaluation context for the initialization, so 11755 // that temporaries introduced as part of the capture are retained 11756 // to be re-"exported" from the lambda expression itself. 11757 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11758 11759 // C++ [expr.prim.labda]p12: 11760 // An entity captured by a lambda-expression is odr-used (3.2) in 11761 // the scope containing the lambda-expression. 11762 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11763 DeclRefType, VK_LValue, Loc); 11764 Var->setReferenced(true); 11765 Var->markUsed(S.Context); 11766 11767 // When the field has array type, create index variables for each 11768 // dimension of the array. We use these index variables to subscript 11769 // the source array, and other clients (e.g., CodeGen) will perform 11770 // the necessary iteration with these index variables. 11771 SmallVector<VarDecl *, 4> IndexVariables; 11772 QualType BaseType = FieldType; 11773 QualType SizeType = S.Context.getSizeType(); 11774 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11775 while (const ConstantArrayType *Array 11776 = S.Context.getAsConstantArrayType(BaseType)) { 11777 // Create the iteration variable for this array index. 11778 IdentifierInfo *IterationVarName = 0; 11779 { 11780 SmallString<8> Str; 11781 llvm::raw_svector_ostream OS(Str); 11782 OS << "__i" << IndexVariables.size(); 11783 IterationVarName = &S.Context.Idents.get(OS.str()); 11784 } 11785 VarDecl *IterationVar 11786 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11787 IterationVarName, SizeType, 11788 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11789 SC_None); 11790 IndexVariables.push_back(IterationVar); 11791 LSI->ArrayIndexVars.push_back(IterationVar); 11792 11793 // Create a reference to the iteration variable. 11794 ExprResult IterationVarRef 11795 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11796 assert(!IterationVarRef.isInvalid() && 11797 "Reference to invented variable cannot fail!"); 11798 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11799 assert(!IterationVarRef.isInvalid() && 11800 "Conversion of invented variable cannot fail!"); 11801 11802 // Subscript the array with this iteration variable. 11803 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11804 Ref, Loc, IterationVarRef.take(), Loc); 11805 if (Subscript.isInvalid()) { 11806 S.CleanupVarDeclMarking(); 11807 S.DiscardCleanupsInEvaluationContext(); 11808 return ExprError(); 11809 } 11810 11811 Ref = Subscript.take(); 11812 BaseType = Array->getElementType(); 11813 } 11814 11815 // Construct the entity that we will be initializing. For an array, this 11816 // will be first element in the array, which may require several levels 11817 // of array-subscript entities. 11818 SmallVector<InitializedEntity, 4> Entities; 11819 Entities.reserve(1 + IndexVariables.size()); 11820 Entities.push_back( 11821 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(), 11822 Field->getType(), Loc)); 11823 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11824 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11825 0, 11826 Entities.back())); 11827 11828 InitializationKind InitKind 11829 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11830 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11831 ExprResult Result(true); 11832 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11833 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11834 11835 // If this initialization requires any cleanups (e.g., due to a 11836 // default argument to a copy constructor), note that for the 11837 // lambda. 11838 if (S.ExprNeedsCleanups) 11839 LSI->ExprNeedsCleanups = true; 11840 11841 // Exit the expression evaluation context used for the capture. 11842 S.CleanupVarDeclMarking(); 11843 S.DiscardCleanupsInEvaluationContext(); 11844 return Result; 11845 } 11846 11847 11848 11849 /// \brief Capture the given variable in the lambda. 11850 static bool captureInLambda(LambdaScopeInfo *LSI, 11851 VarDecl *Var, 11852 SourceLocation Loc, 11853 const bool BuildAndDiagnose, 11854 QualType &CaptureType, 11855 QualType &DeclRefType, 11856 const bool RefersToEnclosingLocal, 11857 const Sema::TryCaptureKind Kind, 11858 SourceLocation EllipsisLoc, 11859 const bool IsTopScope, 11860 Sema &S) { 11861 11862 // Determine whether we are capturing by reference or by value. 11863 bool ByRef = false; 11864 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11865 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11866 } else { 11867 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11868 } 11869 11870 // Compute the type of the field that will capture this variable. 11871 if (ByRef) { 11872 // C++11 [expr.prim.lambda]p15: 11873 // An entity is captured by reference if it is implicitly or 11874 // explicitly captured but not captured by copy. It is 11875 // unspecified whether additional unnamed non-static data 11876 // members are declared in the closure type for entities 11877 // captured by reference. 11878 // 11879 // FIXME: It is not clear whether we want to build an lvalue reference 11880 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11881 // to do the former, while EDG does the latter. Core issue 1249 will 11882 // clarify, but for now we follow GCC because it's a more permissive and 11883 // easily defensible position. 11884 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11885 } else { 11886 // C++11 [expr.prim.lambda]p14: 11887 // For each entity captured by copy, an unnamed non-static 11888 // data member is declared in the closure type. The 11889 // declaration order of these members is unspecified. The type 11890 // of such a data member is the type of the corresponding 11891 // captured entity if the entity is not a reference to an 11892 // object, or the referenced type otherwise. [Note: If the 11893 // captured entity is a reference to a function, the 11894 // corresponding data member is also a reference to a 11895 // function. - end note ] 11896 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11897 if (!RefType->getPointeeType()->isFunctionType()) 11898 CaptureType = RefType->getPointeeType(); 11899 } 11900 11901 // Forbid the lambda copy-capture of autoreleasing variables. 11902 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11903 if (BuildAndDiagnose) { 11904 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11905 S.Diag(Var->getLocation(), diag::note_previous_decl) 11906 << Var->getDeclName(); 11907 } 11908 return false; 11909 } 11910 11911 // Make sure that by-copy captures are of a complete and non-abstract type. 11912 if (BuildAndDiagnose) { 11913 if (!CaptureType->isDependentType() && 11914 S.RequireCompleteType(Loc, CaptureType, 11915 diag::err_capture_of_incomplete_type, 11916 Var->getDeclName())) 11917 return false; 11918 11919 if (S.RequireNonAbstractType(Loc, CaptureType, 11920 diag::err_capture_of_abstract_type)) 11921 return false; 11922 } 11923 } 11924 11925 // Capture this variable in the lambda. 11926 Expr *CopyExpr = 0; 11927 if (BuildAndDiagnose) { 11928 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 11929 CaptureType, DeclRefType, Loc, 11930 RefersToEnclosingLocal); 11931 if (!Result.isInvalid()) 11932 CopyExpr = Result.take(); 11933 } 11934 11935 // Compute the type of a reference to this captured variable. 11936 if (ByRef) 11937 DeclRefType = CaptureType.getNonReferenceType(); 11938 else { 11939 // C++ [expr.prim.lambda]p5: 11940 // The closure type for a lambda-expression has a public inline 11941 // function call operator [...]. This function call operator is 11942 // declared const (9.3.1) if and only if the lambda-expression’s 11943 // parameter-declaration-clause is not followed by mutable. 11944 DeclRefType = CaptureType.getNonReferenceType(); 11945 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11946 DeclRefType.addConst(); 11947 } 11948 11949 // Add the capture. 11950 if (BuildAndDiagnose) 11951 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 11952 Loc, EllipsisLoc, CaptureType, CopyExpr); 11953 11954 return true; 11955 } 11956 11957 11958 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 11959 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11960 bool BuildAndDiagnose, 11961 QualType &CaptureType, 11962 QualType &DeclRefType, 11963 const unsigned *const FunctionScopeIndexToStopAt) { 11964 bool Nested = false; 11965 11966 DeclContext *DC = CurContext; 11967 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 11968 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 11969 // We need to sync up the Declaration Context with the 11970 // FunctionScopeIndexToStopAt 11971 if (FunctionScopeIndexToStopAt) { 11972 unsigned FSIndex = FunctionScopes.size() - 1; 11973 while (FSIndex != MaxFunctionScopesIndex) { 11974 DC = getLambdaAwareParentOfDeclContext(DC); 11975 --FSIndex; 11976 } 11977 } 11978 11979 11980 // If the variable is declared in the current context (and is not an 11981 // init-capture), there is no need to capture it. 11982 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 11983 if (!Var->hasLocalStorage()) return true; 11984 11985 // Walk up the stack to determine whether we can capture the variable, 11986 // performing the "simple" checks that don't depend on type. We stop when 11987 // we've either hit the declared scope of the variable or find an existing 11988 // capture of that variable. We start from the innermost capturing-entity 11989 // (the DC) and ensure that all intervening capturing-entities 11990 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 11991 // declcontext can either capture the variable or have already captured 11992 // the variable. 11993 CaptureType = Var->getType(); 11994 DeclRefType = CaptureType.getNonReferenceType(); 11995 bool Explicit = (Kind != TryCapture_Implicit); 11996 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 11997 do { 11998 // Only block literals, captured statements, and lambda expressions can 11999 // capture; other scopes don't work. 12000 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 12001 ExprLoc, 12002 BuildAndDiagnose, 12003 *this); 12004 if (!ParentDC) return true; 12005 12006 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 12007 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 12008 12009 12010 // Check whether we've already captured it. 12011 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 12012 DeclRefType)) 12013 break; 12014 // If we are instantiating a generic lambda call operator body, 12015 // we do not want to capture new variables. What was captured 12016 // during either a lambdas transformation or initial parsing 12017 // should be used. 12018 if (isGenericLambdaCallOperatorSpecialization(DC)) { 12019 if (BuildAndDiagnose) { 12020 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12021 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 12022 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12023 Diag(Var->getLocation(), diag::note_previous_decl) 12024 << Var->getDeclName(); 12025 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 12026 } else 12027 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 12028 } 12029 return true; 12030 } 12031 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12032 // certain types of variables (unnamed, variably modified types etc.) 12033 // so check for eligibility. 12034 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 12035 return true; 12036 12037 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 12038 // No capture-default, and this is not an explicit capture 12039 // so cannot capture this variable. 12040 if (BuildAndDiagnose) { 12041 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12042 Diag(Var->getLocation(), diag::note_previous_decl) 12043 << Var->getDeclName(); 12044 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 12045 diag::note_lambda_decl); 12046 // FIXME: If we error out because an outer lambda can not implicitly 12047 // capture a variable that an inner lambda explicitly captures, we 12048 // should have the inner lambda do the explicit capture - because 12049 // it makes for cleaner diagnostics later. This would purely be done 12050 // so that the diagnostic does not misleadingly claim that a variable 12051 // can not be captured by a lambda implicitly even though it is captured 12052 // explicitly. Suggestion: 12053 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 12054 // at the function head 12055 // - cache the StartingDeclContext - this must be a lambda 12056 // - captureInLambda in the innermost lambda the variable. 12057 } 12058 return true; 12059 } 12060 12061 FunctionScopesIndex--; 12062 DC = ParentDC; 12063 Explicit = false; 12064 } while (!Var->getDeclContext()->Equals(DC)); 12065 12066 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 12067 // computing the type of the capture at each step, checking type-specific 12068 // requirements, and adding captures if requested. 12069 // If the variable had already been captured previously, we start capturing 12070 // at the lambda nested within that one. 12071 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 12072 ++I) { 12073 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 12074 12075 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 12076 if (!captureInBlock(BSI, Var, ExprLoc, 12077 BuildAndDiagnose, CaptureType, 12078 DeclRefType, Nested, *this)) 12079 return true; 12080 Nested = true; 12081 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 12082 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 12083 BuildAndDiagnose, CaptureType, 12084 DeclRefType, Nested, *this)) 12085 return true; 12086 Nested = true; 12087 } else { 12088 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12089 if (!captureInLambda(LSI, Var, ExprLoc, 12090 BuildAndDiagnose, CaptureType, 12091 DeclRefType, Nested, Kind, EllipsisLoc, 12092 /*IsTopScope*/I == N - 1, *this)) 12093 return true; 12094 Nested = true; 12095 } 12096 } 12097 return false; 12098 } 12099 12100 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 12101 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 12102 QualType CaptureType; 12103 QualType DeclRefType; 12104 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 12105 /*BuildAndDiagnose=*/true, CaptureType, 12106 DeclRefType, 0); 12107 } 12108 12109 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 12110 QualType CaptureType; 12111 QualType DeclRefType; 12112 12113 // Determine whether we can capture this variable. 12114 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 12115 /*BuildAndDiagnose=*/false, CaptureType, 12116 DeclRefType, 0)) 12117 return QualType(); 12118 12119 return DeclRefType; 12120 } 12121 12122 12123 12124 // If either the type of the variable or the initializer is dependent, 12125 // return false. Otherwise, determine whether the variable is a constant 12126 // expression. Use this if you need to know if a variable that might or 12127 // might not be dependent is truly a constant expression. 12128 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 12129 ASTContext &Context) { 12130 12131 if (Var->getType()->isDependentType()) 12132 return false; 12133 const VarDecl *DefVD = 0; 12134 Var->getAnyInitializer(DefVD); 12135 if (!DefVD) 12136 return false; 12137 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 12138 Expr *Init = cast<Expr>(Eval->Value); 12139 if (Init->isValueDependent()) 12140 return false; 12141 return IsVariableAConstantExpression(Var, Context); 12142 } 12143 12144 12145 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 12146 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 12147 // an object that satisfies the requirements for appearing in a 12148 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 12149 // is immediately applied." This function handles the lvalue-to-rvalue 12150 // conversion part. 12151 MaybeODRUseExprs.erase(E->IgnoreParens()); 12152 12153 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 12154 // to a variable that is a constant expression, and if so, identify it as 12155 // a reference to a variable that does not involve an odr-use of that 12156 // variable. 12157 if (LambdaScopeInfo *LSI = getCurLambda()) { 12158 Expr *SansParensExpr = E->IgnoreParens(); 12159 VarDecl *Var = 0; 12160 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 12161 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 12162 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 12163 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 12164 12165 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 12166 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 12167 } 12168 } 12169 12170 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 12171 if (!Res.isUsable()) 12172 return Res; 12173 12174 // If a constant-expression is a reference to a variable where we delay 12175 // deciding whether it is an odr-use, just assume we will apply the 12176 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 12177 // (a non-type template argument), we have special handling anyway. 12178 UpdateMarkingForLValueToRValue(Res.get()); 12179 return Res; 12180 } 12181 12182 void Sema::CleanupVarDeclMarking() { 12183 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 12184 e = MaybeODRUseExprs.end(); 12185 i != e; ++i) { 12186 VarDecl *Var; 12187 SourceLocation Loc; 12188 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 12189 Var = cast<VarDecl>(DRE->getDecl()); 12190 Loc = DRE->getLocation(); 12191 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 12192 Var = cast<VarDecl>(ME->getMemberDecl()); 12193 Loc = ME->getMemberLoc(); 12194 } else { 12195 llvm_unreachable("Unexpcted expression"); 12196 } 12197 12198 MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0); 12199 } 12200 12201 MaybeODRUseExprs.clear(); 12202 } 12203 12204 12205 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 12206 VarDecl *Var, Expr *E) { 12207 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 12208 "Invalid Expr argument to DoMarkVarDeclReferenced"); 12209 Var->setReferenced(); 12210 12211 // If the context is not potentially evaluated, this is not an odr-use and 12212 // does not trigger instantiation. 12213 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 12214 if (SemaRef.isUnevaluatedContext()) 12215 return; 12216 12217 // If we don't yet know whether this context is going to end up being an 12218 // evaluated context, and we're referencing a variable from an enclosing 12219 // scope, add a potential capture. 12220 // 12221 // FIXME: Is this necessary? These contexts are only used for default 12222 // arguments, where local variables can't be used. 12223 const bool RefersToEnclosingScope = 12224 (SemaRef.CurContext != Var->getDeclContext() && 12225 Var->getDeclContext()->isFunctionOrMethod() && 12226 Var->hasLocalStorage()); 12227 if (!RefersToEnclosingScope) 12228 return; 12229 12230 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 12231 // If a variable could potentially be odr-used, defer marking it so 12232 // until we finish analyzing the full expression for any lvalue-to-rvalue 12233 // or discarded value conversions that would obviate odr-use. 12234 // Add it to the list of potential captures that will be analyzed 12235 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 12236 // unless the variable is a reference that was initialized by a constant 12237 // expression (this will never need to be captured or odr-used). 12238 assert(E && "Capture variable should be used in an expression."); 12239 if (!Var->getType()->isReferenceType() || 12240 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 12241 LSI->addPotentialCapture(E->IgnoreParens()); 12242 } 12243 return; 12244 } 12245 12246 VarTemplateSpecializationDecl *VarSpec = 12247 dyn_cast<VarTemplateSpecializationDecl>(Var); 12248 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 12249 "Can't instantiate a partial template specialization."); 12250 12251 // Perform implicit instantiation of static data members, static data member 12252 // templates of class templates, and variable template specializations. Delay 12253 // instantiations of variable templates, except for those that could be used 12254 // in a constant expression. 12255 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 12256 if (isTemplateInstantiation(TSK)) { 12257 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 12258 12259 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 12260 if (Var->getPointOfInstantiation().isInvalid()) { 12261 // This is a modification of an existing AST node. Notify listeners. 12262 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 12263 L->StaticDataMemberInstantiated(Var); 12264 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 12265 // Don't bother trying to instantiate it again, unless we might need 12266 // its initializer before we get to the end of the TU. 12267 TryInstantiating = false; 12268 } 12269 12270 if (Var->getPointOfInstantiation().isInvalid()) 12271 Var->setTemplateSpecializationKind(TSK, Loc); 12272 12273 if (TryInstantiating) { 12274 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 12275 bool InstantiationDependent = false; 12276 bool IsNonDependent = 12277 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 12278 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 12279 : true; 12280 12281 // Do not instantiate specializations that are still type-dependent. 12282 if (IsNonDependent) { 12283 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 12284 // Do not defer instantiations of variables which could be used in a 12285 // constant expression. 12286 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 12287 } else { 12288 SemaRef.PendingInstantiations 12289 .push_back(std::make_pair(Var, PointOfInstantiation)); 12290 } 12291 } 12292 } 12293 } 12294 12295 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 12296 // the requirements for appearing in a constant expression (5.19) and, if 12297 // it is an object, the lvalue-to-rvalue conversion (4.1) 12298 // is immediately applied." We check the first part here, and 12299 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 12300 // Note that we use the C++11 definition everywhere because nothing in 12301 // C++03 depends on whether we get the C++03 version correct. The second 12302 // part does not apply to references, since they are not objects. 12303 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 12304 // A reference initialized by a constant expression can never be 12305 // odr-used, so simply ignore it. 12306 if (!Var->getType()->isReferenceType()) 12307 SemaRef.MaybeODRUseExprs.insert(E); 12308 } else 12309 MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0); 12310 } 12311 12312 /// \brief Mark a variable referenced, and check whether it is odr-used 12313 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 12314 /// used directly for normal expressions referring to VarDecl. 12315 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 12316 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 12317 } 12318 12319 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 12320 Decl *D, Expr *E, bool OdrUse) { 12321 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 12322 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 12323 return; 12324 } 12325 12326 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 12327 12328 // If this is a call to a method via a cast, also mark the method in the 12329 // derived class used in case codegen can devirtualize the call. 12330 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12331 if (!ME) 12332 return; 12333 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12334 if (!MD) 12335 return; 12336 const Expr *Base = ME->getBase(); 12337 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12338 if (!MostDerivedClassDecl) 12339 return; 12340 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12341 if (!DM || DM->isPure()) 12342 return; 12343 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12344 } 12345 12346 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12347 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12348 // TODO: update this with DR# once a defect report is filed. 12349 // C++11 defect. The address of a pure member should not be an ODR use, even 12350 // if it's a qualified reference. 12351 bool OdrUse = true; 12352 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12353 if (Method->isVirtual()) 12354 OdrUse = false; 12355 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12356 } 12357 12358 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12359 void Sema::MarkMemberReferenced(MemberExpr *E) { 12360 // C++11 [basic.def.odr]p2: 12361 // A non-overloaded function whose name appears as a potentially-evaluated 12362 // expression or a member of a set of candidate functions, if selected by 12363 // overload resolution when referred to from a potentially-evaluated 12364 // expression, is odr-used, unless it is a pure virtual function and its 12365 // name is not explicitly qualified. 12366 bool OdrUse = true; 12367 if (!E->hasQualifier()) { 12368 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12369 if (Method->isPure()) 12370 OdrUse = false; 12371 } 12372 SourceLocation Loc = E->getMemberLoc().isValid() ? 12373 E->getMemberLoc() : E->getLocStart(); 12374 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12375 } 12376 12377 /// \brief Perform marking for a reference to an arbitrary declaration. It 12378 /// marks the declaration referenced, and performs odr-use checking for functions 12379 /// and variables. This method should not be used when building an normal 12380 /// expression which refers to a variable. 12381 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12382 if (OdrUse) { 12383 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12384 MarkVariableReferenced(Loc, VD); 12385 return; 12386 } 12387 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12388 MarkFunctionReferenced(Loc, FD); 12389 return; 12390 } 12391 } 12392 D->setReferenced(); 12393 } 12394 12395 namespace { 12396 // Mark all of the declarations referenced 12397 // FIXME: Not fully implemented yet! We need to have a better understanding 12398 // of when we're entering 12399 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12400 Sema &S; 12401 SourceLocation Loc; 12402 12403 public: 12404 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12405 12406 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12407 12408 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12409 bool TraverseRecordType(RecordType *T); 12410 }; 12411 } 12412 12413 bool MarkReferencedDecls::TraverseTemplateArgument( 12414 const TemplateArgument &Arg) { 12415 if (Arg.getKind() == TemplateArgument::Declaration) { 12416 if (Decl *D = Arg.getAsDecl()) 12417 S.MarkAnyDeclReferenced(Loc, D, true); 12418 } 12419 12420 return Inherited::TraverseTemplateArgument(Arg); 12421 } 12422 12423 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12424 if (ClassTemplateSpecializationDecl *Spec 12425 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12426 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12427 return TraverseTemplateArguments(Args.data(), Args.size()); 12428 } 12429 12430 return true; 12431 } 12432 12433 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12434 MarkReferencedDecls Marker(*this, Loc); 12435 Marker.TraverseType(Context.getCanonicalType(T)); 12436 } 12437 12438 namespace { 12439 /// \brief Helper class that marks all of the declarations referenced by 12440 /// potentially-evaluated subexpressions as "referenced". 12441 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12442 Sema &S; 12443 bool SkipLocalVariables; 12444 12445 public: 12446 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12447 12448 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12449 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12450 12451 void VisitDeclRefExpr(DeclRefExpr *E) { 12452 // If we were asked not to visit local variables, don't. 12453 if (SkipLocalVariables) { 12454 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12455 if (VD->hasLocalStorage()) 12456 return; 12457 } 12458 12459 S.MarkDeclRefReferenced(E); 12460 } 12461 12462 void VisitMemberExpr(MemberExpr *E) { 12463 S.MarkMemberReferenced(E); 12464 Inherited::VisitMemberExpr(E); 12465 } 12466 12467 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12468 S.MarkFunctionReferenced(E->getLocStart(), 12469 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12470 Visit(E->getSubExpr()); 12471 } 12472 12473 void VisitCXXNewExpr(CXXNewExpr *E) { 12474 if (E->getOperatorNew()) 12475 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12476 if (E->getOperatorDelete()) 12477 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12478 Inherited::VisitCXXNewExpr(E); 12479 } 12480 12481 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12482 if (E->getOperatorDelete()) 12483 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12484 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12485 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12486 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12487 S.MarkFunctionReferenced(E->getLocStart(), 12488 S.LookupDestructor(Record)); 12489 } 12490 12491 Inherited::VisitCXXDeleteExpr(E); 12492 } 12493 12494 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12495 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12496 Inherited::VisitCXXConstructExpr(E); 12497 } 12498 12499 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12500 Visit(E->getExpr()); 12501 } 12502 12503 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12504 Inherited::VisitImplicitCastExpr(E); 12505 12506 if (E->getCastKind() == CK_LValueToRValue) 12507 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12508 } 12509 }; 12510 } 12511 12512 /// \brief Mark any declarations that appear within this expression or any 12513 /// potentially-evaluated subexpressions as "referenced". 12514 /// 12515 /// \param SkipLocalVariables If true, don't mark local variables as 12516 /// 'referenced'. 12517 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12518 bool SkipLocalVariables) { 12519 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12520 } 12521 12522 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 12523 /// of the program being compiled. 12524 /// 12525 /// This routine emits the given diagnostic when the code currently being 12526 /// type-checked is "potentially evaluated", meaning that there is a 12527 /// possibility that the code will actually be executable. Code in sizeof() 12528 /// expressions, code used only during overload resolution, etc., are not 12529 /// potentially evaluated. This routine will suppress such diagnostics or, 12530 /// in the absolutely nutty case of potentially potentially evaluated 12531 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 12532 /// later. 12533 /// 12534 /// This routine should be used for all diagnostics that describe the run-time 12535 /// behavior of a program, such as passing a non-POD value through an ellipsis. 12536 /// Failure to do so will likely result in spurious diagnostics or failures 12537 /// during overload resolution or within sizeof/alignof/typeof/typeid. 12538 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12539 const PartialDiagnostic &PD) { 12540 switch (ExprEvalContexts.back().Context) { 12541 case Unevaluated: 12542 case UnevaluatedAbstract: 12543 // The argument will never be evaluated, so don't complain. 12544 break; 12545 12546 case ConstantEvaluated: 12547 // Relevant diagnostics should be produced by constant evaluation. 12548 break; 12549 12550 case PotentiallyEvaluated: 12551 case PotentiallyEvaluatedIfUsed: 12552 if (Statement && getCurFunctionOrMethodDecl()) { 12553 FunctionScopes.back()->PossiblyUnreachableDiags. 12554 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12555 } 12556 else 12557 Diag(Loc, PD); 12558 12559 return true; 12560 } 12561 12562 return false; 12563 } 12564 12565 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12566 CallExpr *CE, FunctionDecl *FD) { 12567 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12568 return false; 12569 12570 // If we're inside a decltype's expression, don't check for a valid return 12571 // type or construct temporaries until we know whether this is the last call. 12572 if (ExprEvalContexts.back().IsDecltype) { 12573 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12574 return false; 12575 } 12576 12577 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12578 FunctionDecl *FD; 12579 CallExpr *CE; 12580 12581 public: 12582 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12583 : FD(FD), CE(CE) { } 12584 12585 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 12586 if (!FD) { 12587 S.Diag(Loc, diag::err_call_incomplete_return) 12588 << T << CE->getSourceRange(); 12589 return; 12590 } 12591 12592 S.Diag(Loc, diag::err_call_function_incomplete_return) 12593 << CE->getSourceRange() << FD->getDeclName() << T; 12594 S.Diag(FD->getLocation(), 12595 diag::note_function_with_incomplete_return_type_declared_here) 12596 << FD->getDeclName(); 12597 } 12598 } Diagnoser(FD, CE); 12599 12600 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12601 return true; 12602 12603 return false; 12604 } 12605 12606 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12607 // will prevent this condition from triggering, which is what we want. 12608 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12609 SourceLocation Loc; 12610 12611 unsigned diagnostic = diag::warn_condition_is_assignment; 12612 bool IsOrAssign = false; 12613 12614 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12615 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12616 return; 12617 12618 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12619 12620 // Greylist some idioms by putting them into a warning subcategory. 12621 if (ObjCMessageExpr *ME 12622 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12623 Selector Sel = ME->getSelector(); 12624 12625 // self = [<foo> init...] 12626 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12627 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12628 12629 // <foo> = [<bar> nextObject] 12630 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12631 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12632 } 12633 12634 Loc = Op->getOperatorLoc(); 12635 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12636 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12637 return; 12638 12639 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12640 Loc = Op->getOperatorLoc(); 12641 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12642 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12643 else { 12644 // Not an assignment. 12645 return; 12646 } 12647 12648 Diag(Loc, diagnostic) << E->getSourceRange(); 12649 12650 SourceLocation Open = E->getLocStart(); 12651 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12652 Diag(Loc, diag::note_condition_assign_silence) 12653 << FixItHint::CreateInsertion(Open, "(") 12654 << FixItHint::CreateInsertion(Close, ")"); 12655 12656 if (IsOrAssign) 12657 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12658 << FixItHint::CreateReplacement(Loc, "!="); 12659 else 12660 Diag(Loc, diag::note_condition_assign_to_comparison) 12661 << FixItHint::CreateReplacement(Loc, "=="); 12662 } 12663 12664 /// \brief Redundant parentheses over an equality comparison can indicate 12665 /// that the user intended an assignment used as condition. 12666 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12667 // Don't warn if the parens came from a macro. 12668 SourceLocation parenLoc = ParenE->getLocStart(); 12669 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12670 return; 12671 // Don't warn for dependent expressions. 12672 if (ParenE->isTypeDependent()) 12673 return; 12674 12675 Expr *E = ParenE->IgnoreParens(); 12676 12677 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12678 if (opE->getOpcode() == BO_EQ && 12679 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12680 == Expr::MLV_Valid) { 12681 SourceLocation Loc = opE->getOperatorLoc(); 12682 12683 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12684 SourceRange ParenERange = ParenE->getSourceRange(); 12685 Diag(Loc, diag::note_equality_comparison_silence) 12686 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12687 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12688 Diag(Loc, diag::note_equality_comparison_to_assign) 12689 << FixItHint::CreateReplacement(Loc, "="); 12690 } 12691 } 12692 12693 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12694 DiagnoseAssignmentAsCondition(E); 12695 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12696 DiagnoseEqualityWithExtraParens(parenE); 12697 12698 ExprResult result = CheckPlaceholderExpr(E); 12699 if (result.isInvalid()) return ExprError(); 12700 E = result.take(); 12701 12702 if (!E->isTypeDependent()) { 12703 if (getLangOpts().CPlusPlus) 12704 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12705 12706 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12707 if (ERes.isInvalid()) 12708 return ExprError(); 12709 E = ERes.take(); 12710 12711 QualType T = E->getType(); 12712 if (!T->isScalarType()) { // C99 6.8.4.1p1 12713 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12714 << T << E->getSourceRange(); 12715 return ExprError(); 12716 } 12717 } 12718 12719 return Owned(E); 12720 } 12721 12722 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12723 Expr *SubExpr) { 12724 if (!SubExpr) 12725 return ExprError(); 12726 12727 return CheckBooleanCondition(SubExpr, Loc); 12728 } 12729 12730 namespace { 12731 /// A visitor for rebuilding a call to an __unknown_any expression 12732 /// to have an appropriate type. 12733 struct RebuildUnknownAnyFunction 12734 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12735 12736 Sema &S; 12737 12738 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12739 12740 ExprResult VisitStmt(Stmt *S) { 12741 llvm_unreachable("unexpected statement!"); 12742 } 12743 12744 ExprResult VisitExpr(Expr *E) { 12745 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12746 << E->getSourceRange(); 12747 return ExprError(); 12748 } 12749 12750 /// Rebuild an expression which simply semantically wraps another 12751 /// expression which it shares the type and value kind of. 12752 template <class T> ExprResult rebuildSugarExpr(T *E) { 12753 ExprResult SubResult = Visit(E->getSubExpr()); 12754 if (SubResult.isInvalid()) return ExprError(); 12755 12756 Expr *SubExpr = SubResult.take(); 12757 E->setSubExpr(SubExpr); 12758 E->setType(SubExpr->getType()); 12759 E->setValueKind(SubExpr->getValueKind()); 12760 assert(E->getObjectKind() == OK_Ordinary); 12761 return E; 12762 } 12763 12764 ExprResult VisitParenExpr(ParenExpr *E) { 12765 return rebuildSugarExpr(E); 12766 } 12767 12768 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12769 return rebuildSugarExpr(E); 12770 } 12771 12772 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12773 ExprResult SubResult = Visit(E->getSubExpr()); 12774 if (SubResult.isInvalid()) return ExprError(); 12775 12776 Expr *SubExpr = SubResult.take(); 12777 E->setSubExpr(SubExpr); 12778 E->setType(S.Context.getPointerType(SubExpr->getType())); 12779 assert(E->getValueKind() == VK_RValue); 12780 assert(E->getObjectKind() == OK_Ordinary); 12781 return E; 12782 } 12783 12784 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12785 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12786 12787 E->setType(VD->getType()); 12788 12789 assert(E->getValueKind() == VK_RValue); 12790 if (S.getLangOpts().CPlusPlus && 12791 !(isa<CXXMethodDecl>(VD) && 12792 cast<CXXMethodDecl>(VD)->isInstance())) 12793 E->setValueKind(VK_LValue); 12794 12795 return E; 12796 } 12797 12798 ExprResult VisitMemberExpr(MemberExpr *E) { 12799 return resolveDecl(E, E->getMemberDecl()); 12800 } 12801 12802 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12803 return resolveDecl(E, E->getDecl()); 12804 } 12805 }; 12806 } 12807 12808 /// Given a function expression of unknown-any type, try to rebuild it 12809 /// to have a function type. 12810 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12811 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12812 if (Result.isInvalid()) return ExprError(); 12813 return S.DefaultFunctionArrayConversion(Result.take()); 12814 } 12815 12816 namespace { 12817 /// A visitor for rebuilding an expression of type __unknown_anytype 12818 /// into one which resolves the type directly on the referring 12819 /// expression. Strict preservation of the original source 12820 /// structure is not a goal. 12821 struct RebuildUnknownAnyExpr 12822 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12823 12824 Sema &S; 12825 12826 /// The current destination type. 12827 QualType DestType; 12828 12829 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12830 : S(S), DestType(CastType) {} 12831 12832 ExprResult VisitStmt(Stmt *S) { 12833 llvm_unreachable("unexpected statement!"); 12834 } 12835 12836 ExprResult VisitExpr(Expr *E) { 12837 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12838 << E->getSourceRange(); 12839 return ExprError(); 12840 } 12841 12842 ExprResult VisitCallExpr(CallExpr *E); 12843 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12844 12845 /// Rebuild an expression which simply semantically wraps another 12846 /// expression which it shares the type and value kind of. 12847 template <class T> ExprResult rebuildSugarExpr(T *E) { 12848 ExprResult SubResult = Visit(E->getSubExpr()); 12849 if (SubResult.isInvalid()) return ExprError(); 12850 Expr *SubExpr = SubResult.take(); 12851 E->setSubExpr(SubExpr); 12852 E->setType(SubExpr->getType()); 12853 E->setValueKind(SubExpr->getValueKind()); 12854 assert(E->getObjectKind() == OK_Ordinary); 12855 return E; 12856 } 12857 12858 ExprResult VisitParenExpr(ParenExpr *E) { 12859 return rebuildSugarExpr(E); 12860 } 12861 12862 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12863 return rebuildSugarExpr(E); 12864 } 12865 12866 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12867 const PointerType *Ptr = DestType->getAs<PointerType>(); 12868 if (!Ptr) { 12869 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12870 << E->getSourceRange(); 12871 return ExprError(); 12872 } 12873 assert(E->getValueKind() == VK_RValue); 12874 assert(E->getObjectKind() == OK_Ordinary); 12875 E->setType(DestType); 12876 12877 // Build the sub-expression as if it were an object of the pointee type. 12878 DestType = Ptr->getPointeeType(); 12879 ExprResult SubResult = Visit(E->getSubExpr()); 12880 if (SubResult.isInvalid()) return ExprError(); 12881 E->setSubExpr(SubResult.take()); 12882 return E; 12883 } 12884 12885 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12886 12887 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12888 12889 ExprResult VisitMemberExpr(MemberExpr *E) { 12890 return resolveDecl(E, E->getMemberDecl()); 12891 } 12892 12893 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12894 return resolveDecl(E, E->getDecl()); 12895 } 12896 }; 12897 } 12898 12899 /// Rebuilds a call expression which yielded __unknown_anytype. 12900 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12901 Expr *CalleeExpr = E->getCallee(); 12902 12903 enum FnKind { 12904 FK_MemberFunction, 12905 FK_FunctionPointer, 12906 FK_BlockPointer 12907 }; 12908 12909 FnKind Kind; 12910 QualType CalleeType = CalleeExpr->getType(); 12911 if (CalleeType == S.Context.BoundMemberTy) { 12912 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12913 Kind = FK_MemberFunction; 12914 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12915 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12916 CalleeType = Ptr->getPointeeType(); 12917 Kind = FK_FunctionPointer; 12918 } else { 12919 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12920 Kind = FK_BlockPointer; 12921 } 12922 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12923 12924 // Verify that this is a legal result type of a function. 12925 if (DestType->isArrayType() || DestType->isFunctionType()) { 12926 unsigned diagID = diag::err_func_returning_array_function; 12927 if (Kind == FK_BlockPointer) 12928 diagID = diag::err_block_returning_array_function; 12929 12930 S.Diag(E->getExprLoc(), diagID) 12931 << DestType->isFunctionType() << DestType; 12932 return ExprError(); 12933 } 12934 12935 // Otherwise, go ahead and set DestType as the call's result. 12936 E->setType(DestType.getNonLValueExprType(S.Context)); 12937 E->setValueKind(Expr::getValueKindForType(DestType)); 12938 assert(E->getObjectKind() == OK_Ordinary); 12939 12940 // Rebuild the function type, replacing the result type with DestType. 12941 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12942 if (Proto) { 12943 // __unknown_anytype(...) is a special case used by the debugger when 12944 // it has no idea what a function's signature is. 12945 // 12946 // We want to build this call essentially under the K&R 12947 // unprototyped rules, but making a FunctionNoProtoType in C++ 12948 // would foul up all sorts of assumptions. However, we cannot 12949 // simply pass all arguments as variadic arguments, nor can we 12950 // portably just call the function under a non-variadic type; see 12951 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12952 // However, it turns out that in practice it is generally safe to 12953 // call a function declared as "A foo(B,C,D);" under the prototype 12954 // "A foo(B,C,D,...);". The only known exception is with the 12955 // Windows ABI, where any variadic function is implicitly cdecl 12956 // regardless of its normal CC. Therefore we change the parameter 12957 // types to match the types of the arguments. 12958 // 12959 // This is a hack, but it is far superior to moving the 12960 // corresponding target-specific code from IR-gen to Sema/AST. 12961 12962 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 12963 SmallVector<QualType, 8> ArgTypes; 12964 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12965 ArgTypes.reserve(E->getNumArgs()); 12966 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12967 Expr *Arg = E->getArg(i); 12968 QualType ArgType = Arg->getType(); 12969 if (E->isLValue()) { 12970 ArgType = S.Context.getLValueReferenceType(ArgType); 12971 } else if (E->isXValue()) { 12972 ArgType = S.Context.getRValueReferenceType(ArgType); 12973 } 12974 ArgTypes.push_back(ArgType); 12975 } 12976 ParamTypes = ArgTypes; 12977 } 12978 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12979 Proto->getExtProtoInfo()); 12980 } else { 12981 DestType = S.Context.getFunctionNoProtoType(DestType, 12982 FnType->getExtInfo()); 12983 } 12984 12985 // Rebuild the appropriate pointer-to-function type. 12986 switch (Kind) { 12987 case FK_MemberFunction: 12988 // Nothing to do. 12989 break; 12990 12991 case FK_FunctionPointer: 12992 DestType = S.Context.getPointerType(DestType); 12993 break; 12994 12995 case FK_BlockPointer: 12996 DestType = S.Context.getBlockPointerType(DestType); 12997 break; 12998 } 12999 13000 // Finally, we can recurse. 13001 ExprResult CalleeResult = Visit(CalleeExpr); 13002 if (!CalleeResult.isUsable()) return ExprError(); 13003 E->setCallee(CalleeResult.take()); 13004 13005 // Bind a temporary if necessary. 13006 return S.MaybeBindToTemporary(E); 13007 } 13008 13009 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 13010 // Verify that this is a legal result type of a call. 13011 if (DestType->isArrayType() || DestType->isFunctionType()) { 13012 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 13013 << DestType->isFunctionType() << DestType; 13014 return ExprError(); 13015 } 13016 13017 // Rewrite the method result type if available. 13018 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 13019 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 13020 Method->setReturnType(DestType); 13021 } 13022 13023 // Change the type of the message. 13024 E->setType(DestType.getNonReferenceType()); 13025 E->setValueKind(Expr::getValueKindForType(DestType)); 13026 13027 return S.MaybeBindToTemporary(E); 13028 } 13029 13030 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 13031 // The only case we should ever see here is a function-to-pointer decay. 13032 if (E->getCastKind() == CK_FunctionToPointerDecay) { 13033 assert(E->getValueKind() == VK_RValue); 13034 assert(E->getObjectKind() == OK_Ordinary); 13035 13036 E->setType(DestType); 13037 13038 // Rebuild the sub-expression as the pointee (function) type. 13039 DestType = DestType->castAs<PointerType>()->getPointeeType(); 13040 13041 ExprResult Result = Visit(E->getSubExpr()); 13042 if (!Result.isUsable()) return ExprError(); 13043 13044 E->setSubExpr(Result.take()); 13045 return S.Owned(E); 13046 } else if (E->getCastKind() == CK_LValueToRValue) { 13047 assert(E->getValueKind() == VK_RValue); 13048 assert(E->getObjectKind() == OK_Ordinary); 13049 13050 assert(isa<BlockPointerType>(E->getType())); 13051 13052 E->setType(DestType); 13053 13054 // The sub-expression has to be a lvalue reference, so rebuild it as such. 13055 DestType = S.Context.getLValueReferenceType(DestType); 13056 13057 ExprResult Result = Visit(E->getSubExpr()); 13058 if (!Result.isUsable()) return ExprError(); 13059 13060 E->setSubExpr(Result.take()); 13061 return S.Owned(E); 13062 } else { 13063 llvm_unreachable("Unhandled cast type!"); 13064 } 13065 } 13066 13067 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 13068 ExprValueKind ValueKind = VK_LValue; 13069 QualType Type = DestType; 13070 13071 // We know how to make this work for certain kinds of decls: 13072 13073 // - functions 13074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 13075 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 13076 DestType = Ptr->getPointeeType(); 13077 ExprResult Result = resolveDecl(E, VD); 13078 if (Result.isInvalid()) return ExprError(); 13079 return S.ImpCastExprToType(Result.take(), Type, 13080 CK_FunctionToPointerDecay, VK_RValue); 13081 } 13082 13083 if (!Type->isFunctionType()) { 13084 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 13085 << VD << E->getSourceRange(); 13086 return ExprError(); 13087 } 13088 13089 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 13090 if (MD->isInstance()) { 13091 ValueKind = VK_RValue; 13092 Type = S.Context.BoundMemberTy; 13093 } 13094 13095 // Function references aren't l-values in C. 13096 if (!S.getLangOpts().CPlusPlus) 13097 ValueKind = VK_RValue; 13098 13099 // - variables 13100 } else if (isa<VarDecl>(VD)) { 13101 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 13102 Type = RefTy->getPointeeType(); 13103 } else if (Type->isFunctionType()) { 13104 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 13105 << VD << E->getSourceRange(); 13106 return ExprError(); 13107 } 13108 13109 // - nothing else 13110 } else { 13111 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 13112 << VD << E->getSourceRange(); 13113 return ExprError(); 13114 } 13115 13116 // Modifying the declaration like this is friendly to IR-gen but 13117 // also really dangerous. 13118 VD->setType(DestType); 13119 E->setType(Type); 13120 E->setValueKind(ValueKind); 13121 return S.Owned(E); 13122 } 13123 13124 /// Check a cast of an unknown-any type. We intentionally only 13125 /// trigger this for C-style casts. 13126 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 13127 Expr *CastExpr, CastKind &CastKind, 13128 ExprValueKind &VK, CXXCastPath &Path) { 13129 // Rewrite the casted expression from scratch. 13130 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 13131 if (!result.isUsable()) return ExprError(); 13132 13133 CastExpr = result.take(); 13134 VK = CastExpr->getValueKind(); 13135 CastKind = CK_NoOp; 13136 13137 return CastExpr; 13138 } 13139 13140 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 13141 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 13142 } 13143 13144 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 13145 Expr *arg, QualType ¶mType) { 13146 // If the syntactic form of the argument is not an explicit cast of 13147 // any sort, just do default argument promotion. 13148 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 13149 if (!castArg) { 13150 ExprResult result = DefaultArgumentPromotion(arg); 13151 if (result.isInvalid()) return ExprError(); 13152 paramType = result.get()->getType(); 13153 return result; 13154 } 13155 13156 // Otherwise, use the type that was written in the explicit cast. 13157 assert(!arg->hasPlaceholderType()); 13158 paramType = castArg->getTypeAsWritten(); 13159 13160 // Copy-initialize a parameter of that type. 13161 InitializedEntity entity = 13162 InitializedEntity::InitializeParameter(Context, paramType, 13163 /*consumed*/ false); 13164 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 13165 } 13166 13167 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 13168 Expr *orig = E; 13169 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 13170 while (true) { 13171 E = E->IgnoreParenImpCasts(); 13172 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 13173 E = call->getCallee(); 13174 diagID = diag::err_uncasted_call_of_unknown_any; 13175 } else { 13176 break; 13177 } 13178 } 13179 13180 SourceLocation loc; 13181 NamedDecl *d; 13182 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 13183 loc = ref->getLocation(); 13184 d = ref->getDecl(); 13185 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 13186 loc = mem->getMemberLoc(); 13187 d = mem->getMemberDecl(); 13188 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 13189 diagID = diag::err_uncasted_call_of_unknown_any; 13190 loc = msg->getSelectorStartLoc(); 13191 d = msg->getMethodDecl(); 13192 if (!d) { 13193 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 13194 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 13195 << orig->getSourceRange(); 13196 return ExprError(); 13197 } 13198 } else { 13199 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13200 << E->getSourceRange(); 13201 return ExprError(); 13202 } 13203 13204 S.Diag(loc, diagID) << d << orig->getSourceRange(); 13205 13206 // Never recoverable. 13207 return ExprError(); 13208 } 13209 13210 /// Check for operands with placeholder types and complain if found. 13211 /// Returns true if there was an error and no recovery was possible. 13212 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 13213 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 13214 if (!placeholderType) return Owned(E); 13215 13216 switch (placeholderType->getKind()) { 13217 13218 // Overloaded expressions. 13219 case BuiltinType::Overload: { 13220 // Try to resolve a single function template specialization. 13221 // This is obligatory. 13222 ExprResult result = Owned(E); 13223 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 13224 return result; 13225 13226 // If that failed, try to recover with a call. 13227 } else { 13228 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 13229 /*complain*/ true); 13230 return result; 13231 } 13232 } 13233 13234 // Bound member functions. 13235 case BuiltinType::BoundMember: { 13236 ExprResult result = Owned(E); 13237 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 13238 /*complain*/ true); 13239 return result; 13240 } 13241 13242 // ARC unbridged casts. 13243 case BuiltinType::ARCUnbridgedCast: { 13244 Expr *realCast = stripARCUnbridgedCast(E); 13245 diagnoseARCUnbridgedCast(realCast); 13246 return Owned(realCast); 13247 } 13248 13249 // Expressions of unknown type. 13250 case BuiltinType::UnknownAny: 13251 return diagnoseUnknownAnyExpr(*this, E); 13252 13253 // Pseudo-objects. 13254 case BuiltinType::PseudoObject: 13255 return checkPseudoObjectRValue(E); 13256 13257 case BuiltinType::BuiltinFn: 13258 Diag(E->getLocStart(), diag::err_builtin_fn_use); 13259 return ExprError(); 13260 13261 // Everything else should be impossible. 13262 #define BUILTIN_TYPE(Id, SingletonId) \ 13263 case BuiltinType::Id: 13264 #define PLACEHOLDER_TYPE(Id, SingletonId) 13265 #include "clang/AST/BuiltinTypes.def" 13266 break; 13267 } 13268 13269 llvm_unreachable("invalid placeholder type!"); 13270 } 13271 13272 bool Sema::CheckCaseExpression(Expr *E) { 13273 if (E->isTypeDependent()) 13274 return true; 13275 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 13276 return E->getType()->isIntegralOrEnumerationType(); 13277 return false; 13278 } 13279 13280 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 13281 ExprResult 13282 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 13283 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 13284 "Unknown Objective-C Boolean value!"); 13285 QualType BoolT = Context.ObjCBuiltinBoolTy; 13286 if (!Context.getBOOLDecl()) { 13287 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 13288 Sema::LookupOrdinaryName); 13289 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 13290 NamedDecl *ND = Result.getFoundDecl(); 13291 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 13292 Context.setBOOLDecl(TD); 13293 } 13294 } 13295 if (Context.getBOOLDecl()) 13296 BoolT = Context.getBOOLType(); 13297 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 13298 BoolT, OpLoc)); 13299 } 13300