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 E = ImpCastExprToType(E, Context.getPointerType(Ty), 439 CK_FunctionToPointerDecay).take(); 440 else if (Ty->isArrayType()) { 441 // In C90 mode, arrays only promote to pointers if the array expression is 442 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 443 // type 'array of type' is converted to an expression that has type 'pointer 444 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 445 // that has type 'array of type' ...". The relevant change is "an lvalue" 446 // (C90) to "an expression" (C99). 447 // 448 // C++ 4.2p1: 449 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 450 // T" can be converted to an rvalue of type "pointer to T". 451 // 452 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 453 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 454 CK_ArrayToPointerDecay).take(); 455 } 456 return Owned(E); 457 } 458 459 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 460 // Check to see if we are dereferencing a null pointer. If so, 461 // and if not volatile-qualified, this is undefined behavior that the 462 // optimizer will delete, so warn about it. People sometimes try to use this 463 // to get a deterministic trap and are surprised by clang's behavior. This 464 // only handles the pattern "*null", which is a very syntactic check. 465 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 466 if (UO->getOpcode() == UO_Deref && 467 UO->getSubExpr()->IgnoreParenCasts()-> 468 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 469 !UO->getType().isVolatileQualified()) { 470 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 471 S.PDiag(diag::warn_indirection_through_null) 472 << UO->getSubExpr()->getSourceRange()); 473 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 474 S.PDiag(diag::note_indirection_through_null)); 475 } 476 } 477 478 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 479 SourceLocation AssignLoc, 480 const Expr* RHS) { 481 const ObjCIvarDecl *IV = OIRE->getDecl(); 482 if (!IV) 483 return; 484 485 DeclarationName MemberName = IV->getDeclName(); 486 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 487 if (!Member || !Member->isStr("isa")) 488 return; 489 490 const Expr *Base = OIRE->getBase(); 491 QualType BaseType = Base->getType(); 492 if (OIRE->isArrow()) 493 BaseType = BaseType->getPointeeType(); 494 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 495 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 496 ObjCInterfaceDecl *ClassDeclared = 0; 497 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 498 if (!ClassDeclared->getSuperClass() 499 && (*ClassDeclared->ivar_begin()) == IV) { 500 if (RHS) { 501 NamedDecl *ObjectSetClass = 502 S.LookupSingleName(S.TUScope, 503 &S.Context.Idents.get("object_setClass"), 504 SourceLocation(), S.LookupOrdinaryName); 505 if (ObjectSetClass) { 506 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 507 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 508 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 509 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 510 AssignLoc), ",") << 511 FixItHint::CreateInsertion(RHSLocEnd, ")"); 512 } 513 else 514 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 515 } else { 516 NamedDecl *ObjectGetClass = 517 S.LookupSingleName(S.TUScope, 518 &S.Context.Idents.get("object_getClass"), 519 SourceLocation(), S.LookupOrdinaryName); 520 if (ObjectGetClass) 521 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 522 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 523 FixItHint::CreateReplacement( 524 SourceRange(OIRE->getOpLoc(), 525 OIRE->getLocEnd()), ")"); 526 else 527 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 528 } 529 S.Diag(IV->getLocation(), diag::note_ivar_decl); 530 } 531 } 532 } 533 534 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 535 // Handle any placeholder expressions which made it here. 536 if (E->getType()->isPlaceholderType()) { 537 ExprResult result = CheckPlaceholderExpr(E); 538 if (result.isInvalid()) return ExprError(); 539 E = result.take(); 540 } 541 542 // C++ [conv.lval]p1: 543 // A glvalue of a non-function, non-array type T can be 544 // converted to a prvalue. 545 if (!E->isGLValue()) return Owned(E); 546 547 QualType T = E->getType(); 548 assert(!T.isNull() && "r-value conversion on typeless expression?"); 549 550 // We don't want to throw lvalue-to-rvalue casts on top of 551 // expressions of certain types in C++. 552 if (getLangOpts().CPlusPlus && 553 (E->getType() == Context.OverloadTy || 554 T->isDependentType() || 555 T->isRecordType())) 556 return Owned(E); 557 558 // The C standard is actually really unclear on this point, and 559 // DR106 tells us what the result should be but not why. It's 560 // generally best to say that void types just doesn't undergo 561 // lvalue-to-rvalue at all. Note that expressions of unqualified 562 // 'void' type are never l-values, but qualified void can be. 563 if (T->isVoidType()) 564 return Owned(E); 565 566 // OpenCL usually rejects direct accesses to values of 'half' type. 567 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 568 T->isHalfType()) { 569 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 570 << 0 << T; 571 return ExprError(); 572 } 573 574 CheckForNullPointerDereference(*this, E); 575 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 576 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 577 &Context.Idents.get("object_getClass"), 578 SourceLocation(), LookupOrdinaryName); 579 if (ObjectGetClass) 580 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 581 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 582 FixItHint::CreateReplacement( 583 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 584 else 585 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 586 } 587 else if (const ObjCIvarRefExpr *OIRE = 588 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 589 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 590 591 // C++ [conv.lval]p1: 592 // [...] If T is a non-class type, the type of the prvalue is the 593 // cv-unqualified version of T. Otherwise, the type of the 594 // rvalue is T. 595 // 596 // C99 6.3.2.1p2: 597 // If the lvalue has qualified type, the value has the unqualified 598 // version of the type of the lvalue; otherwise, the value has the 599 // type of the lvalue. 600 if (T.hasQualifiers()) 601 T = T.getUnqualifiedType(); 602 603 UpdateMarkingForLValueToRValue(E); 604 605 // Loading a __weak object implicitly retains the value, so we need a cleanup to 606 // balance that. 607 if (getLangOpts().ObjCAutoRefCount && 608 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 609 ExprNeedsCleanups = true; 610 611 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 612 E, 0, VK_RValue)); 613 614 // C11 6.3.2.1p2: 615 // ... if the lvalue has atomic type, the value has the non-atomic version 616 // of the type of the lvalue ... 617 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 618 T = Atomic->getValueType().getUnqualifiedType(); 619 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 620 Res.get(), 0, VK_RValue)); 621 } 622 623 return Res; 624 } 625 626 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 627 ExprResult Res = DefaultFunctionArrayConversion(E); 628 if (Res.isInvalid()) 629 return ExprError(); 630 Res = DefaultLvalueConversion(Res.take()); 631 if (Res.isInvalid()) 632 return ExprError(); 633 return Res; 634 } 635 636 637 /// UsualUnaryConversions - Performs various conversions that are common to most 638 /// operators (C99 6.3). The conversions of array and function types are 639 /// sometimes suppressed. For example, the array->pointer conversion doesn't 640 /// apply if the array is an argument to the sizeof or address (&) operators. 641 /// In these instances, this routine should *not* be called. 642 ExprResult Sema::UsualUnaryConversions(Expr *E) { 643 // First, convert to an r-value. 644 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 645 if (Res.isInvalid()) 646 return ExprError(); 647 E = Res.take(); 648 649 QualType Ty = E->getType(); 650 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 651 652 // Half FP have to be promoted to float unless it is natively supported 653 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 654 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 655 656 // Try to perform integral promotions if the object has a theoretically 657 // promotable type. 658 if (Ty->isIntegralOrUnscopedEnumerationType()) { 659 // C99 6.3.1.1p2: 660 // 661 // The following may be used in an expression wherever an int or 662 // unsigned int may be used: 663 // - an object or expression with an integer type whose integer 664 // conversion rank is less than or equal to the rank of int 665 // and unsigned int. 666 // - A bit-field of type _Bool, int, signed int, or unsigned int. 667 // 668 // If an int can represent all values of the original type, the 669 // value is converted to an int; otherwise, it is converted to an 670 // unsigned int. These are called the integer promotions. All 671 // other types are unchanged by the integer promotions. 672 673 QualType PTy = Context.isPromotableBitField(E); 674 if (!PTy.isNull()) { 675 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 676 return Owned(E); 677 } 678 if (Ty->isPromotableIntegerType()) { 679 QualType PT = Context.getPromotedIntegerType(Ty); 680 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 681 return Owned(E); 682 } 683 } 684 return Owned(E); 685 } 686 687 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 688 /// do not have a prototype. Arguments that have type float or __fp16 689 /// are promoted to double. All other argument types are converted by 690 /// UsualUnaryConversions(). 691 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 692 QualType Ty = E->getType(); 693 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 694 695 ExprResult Res = UsualUnaryConversions(E); 696 if (Res.isInvalid()) 697 return ExprError(); 698 E = Res.take(); 699 700 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 701 // double. 702 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 703 if (BTy && (BTy->getKind() == BuiltinType::Half || 704 BTy->getKind() == BuiltinType::Float)) 705 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 706 707 // C++ performs lvalue-to-rvalue conversion as a default argument 708 // promotion, even on class types, but note: 709 // C++11 [conv.lval]p2: 710 // When an lvalue-to-rvalue conversion occurs in an unevaluated 711 // operand or a subexpression thereof the value contained in the 712 // referenced object is not accessed. Otherwise, if the glvalue 713 // has a class type, the conversion copy-initializes a temporary 714 // of type T from the glvalue and the result of the conversion 715 // is a prvalue for the temporary. 716 // FIXME: add some way to gate this entire thing for correctness in 717 // potentially potentially evaluated contexts. 718 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 719 ExprResult Temp = PerformCopyInitialization( 720 InitializedEntity::InitializeTemporary(E->getType()), 721 E->getExprLoc(), 722 Owned(E)); 723 if (Temp.isInvalid()) 724 return ExprError(); 725 E = Temp.get(); 726 } 727 728 return Owned(E); 729 } 730 731 /// Determine the degree of POD-ness for an expression. 732 /// Incomplete types are considered POD, since this check can be performed 733 /// when we're in an unevaluated context. 734 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 735 if (Ty->isIncompleteType()) { 736 // C++11 [expr.call]p7: 737 // After these conversions, if the argument does not have arithmetic, 738 // enumeration, pointer, pointer to member, or class type, the program 739 // is ill-formed. 740 // 741 // Since we've already performed array-to-pointer and function-to-pointer 742 // decay, the only such type in C++ is cv void. This also handles 743 // initializer lists as variadic arguments. 744 if (Ty->isVoidType()) 745 return VAK_Invalid; 746 747 if (Ty->isObjCObjectType()) 748 return VAK_Invalid; 749 return VAK_Valid; 750 } 751 752 if (Ty.isCXX98PODType(Context)) 753 return VAK_Valid; 754 755 // C++11 [expr.call]p7: 756 // Passing a potentially-evaluated argument of class type (Clause 9) 757 // having a non-trivial copy constructor, a non-trivial move constructor, 758 // or a non-trivial destructor, with no corresponding parameter, 759 // is conditionally-supported with implementation-defined semantics. 760 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 761 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 762 if (!Record->hasNonTrivialCopyConstructor() && 763 !Record->hasNonTrivialMoveConstructor() && 764 !Record->hasNonTrivialDestructor()) 765 return VAK_ValidInCXX11; 766 767 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 768 return VAK_Valid; 769 770 if (Ty->isObjCObjectType()) 771 return VAK_Invalid; 772 773 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 774 // permitted to reject them. We should consider doing so. 775 return VAK_Undefined; 776 } 777 778 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 779 // Don't allow one to pass an Objective-C interface to a vararg. 780 const QualType &Ty = E->getType(); 781 VarArgKind VAK = isValidVarArgType(Ty); 782 783 // Complain about passing non-POD types through varargs. 784 switch (VAK) { 785 case VAK_Valid: 786 break; 787 788 case VAK_ValidInCXX11: 789 DiagRuntimeBehavior( 790 E->getLocStart(), 0, 791 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 792 << E->getType() << CT); 793 break; 794 795 case VAK_Undefined: 796 DiagRuntimeBehavior( 797 E->getLocStart(), 0, 798 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 799 << getLangOpts().CPlusPlus11 << Ty << CT); 800 break; 801 802 case VAK_Invalid: 803 if (Ty->isObjCObjectType()) 804 DiagRuntimeBehavior( 805 E->getLocStart(), 0, 806 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 807 << Ty << CT); 808 else 809 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 810 << isa<InitListExpr>(E) << Ty << CT; 811 break; 812 } 813 } 814 815 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 816 /// will create a trap if the resulting type is not a POD type. 817 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 818 FunctionDecl *FDecl) { 819 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 820 // Strip the unbridged-cast placeholder expression off, if applicable. 821 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 822 (CT == VariadicMethod || 823 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 824 E = stripARCUnbridgedCast(E); 825 826 // Otherwise, do normal placeholder checking. 827 } else { 828 ExprResult ExprRes = CheckPlaceholderExpr(E); 829 if (ExprRes.isInvalid()) 830 return ExprError(); 831 E = ExprRes.take(); 832 } 833 } 834 835 ExprResult ExprRes = DefaultArgumentPromotion(E); 836 if (ExprRes.isInvalid()) 837 return ExprError(); 838 E = ExprRes.take(); 839 840 // Diagnostics regarding non-POD argument types are 841 // emitted along with format string checking in Sema::CheckFunctionCall(). 842 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 843 // Turn this into a trap. 844 CXXScopeSpec SS; 845 SourceLocation TemplateKWLoc; 846 UnqualifiedId Name; 847 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 848 E->getLocStart()); 849 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 850 Name, true, false); 851 if (TrapFn.isInvalid()) 852 return ExprError(); 853 854 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 855 E->getLocStart(), None, 856 E->getLocEnd()); 857 if (Call.isInvalid()) 858 return ExprError(); 859 860 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 861 Call.get(), E); 862 if (Comma.isInvalid()) 863 return ExprError(); 864 return Comma.get(); 865 } 866 867 if (!getLangOpts().CPlusPlus && 868 RequireCompleteType(E->getExprLoc(), E->getType(), 869 diag::err_call_incomplete_argument)) 870 return ExprError(); 871 872 return Owned(E); 873 } 874 875 /// \brief Converts an integer to complex float type. Helper function of 876 /// UsualArithmeticConversions() 877 /// 878 /// \return false if the integer expression is an integer type and is 879 /// successfully converted to the complex type. 880 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 881 ExprResult &ComplexExpr, 882 QualType IntTy, 883 QualType ComplexTy, 884 bool SkipCast) { 885 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 886 if (SkipCast) return false; 887 if (IntTy->isIntegerType()) { 888 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 889 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 890 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 891 CK_FloatingRealToComplex); 892 } else { 893 assert(IntTy->isComplexIntegerType()); 894 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 895 CK_IntegralComplexToFloatingComplex); 896 } 897 return false; 898 } 899 900 /// \brief Takes two complex float types and converts them to the same type. 901 /// Helper function of UsualArithmeticConversions() 902 static QualType 903 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 904 ExprResult &RHS, QualType LHSType, 905 QualType RHSType, 906 bool IsCompAssign) { 907 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 908 909 if (order < 0) { 910 // _Complex float -> _Complex double 911 if (!IsCompAssign) 912 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 913 return RHSType; 914 } 915 if (order > 0) 916 // _Complex float -> _Complex double 917 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 918 return LHSType; 919 } 920 921 /// \brief Converts otherExpr to complex float and promotes complexExpr if 922 /// necessary. Helper function of UsualArithmeticConversions() 923 static QualType handleOtherComplexFloatConversion(Sema &S, 924 ExprResult &ComplexExpr, 925 ExprResult &OtherExpr, 926 QualType ComplexTy, 927 QualType OtherTy, 928 bool ConvertComplexExpr, 929 bool ConvertOtherExpr) { 930 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 931 932 // If just the complexExpr is complex, the otherExpr needs to be converted, 933 // and the complexExpr might need to be promoted. 934 if (order > 0) { // complexExpr is wider 935 // float -> _Complex double 936 if (ConvertOtherExpr) { 937 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 938 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 939 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 940 CK_FloatingRealToComplex); 941 } 942 return ComplexTy; 943 } 944 945 // otherTy is at least as wide. Find its corresponding complex type. 946 QualType result = (order == 0 ? ComplexTy : 947 S.Context.getComplexType(OtherTy)); 948 949 // double -> _Complex double 950 if (ConvertOtherExpr) 951 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 952 CK_FloatingRealToComplex); 953 954 // _Complex float -> _Complex double 955 if (ConvertComplexExpr && order < 0) 956 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 957 CK_FloatingComplexCast); 958 959 return result; 960 } 961 962 /// \brief Handle arithmetic conversion with complex types. Helper function of 963 /// UsualArithmeticConversions() 964 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 965 ExprResult &RHS, QualType LHSType, 966 QualType RHSType, 967 bool IsCompAssign) { 968 // if we have an integer operand, the result is the complex type. 969 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 970 /*skipCast*/false)) 971 return LHSType; 972 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 973 /*skipCast*/IsCompAssign)) 974 return RHSType; 975 976 // This handles complex/complex, complex/float, or float/complex. 977 // When both operands are complex, the shorter operand is converted to the 978 // type of the longer, and that is the type of the result. This corresponds 979 // to what is done when combining two real floating-point operands. 980 // The fun begins when size promotion occur across type domains. 981 // From H&S 6.3.4: When one operand is complex and the other is a real 982 // floating-point type, the less precise type is converted, within it's 983 // real or complex domain, to the precision of the other type. For example, 984 // when combining a "long double" with a "double _Complex", the 985 // "double _Complex" is promoted to "long double _Complex". 986 987 bool LHSComplexFloat = LHSType->isComplexType(); 988 bool RHSComplexFloat = RHSType->isComplexType(); 989 990 // If both are complex, just cast to the more precise type. 991 if (LHSComplexFloat && RHSComplexFloat) 992 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 993 LHSType, RHSType, 994 IsCompAssign); 995 996 // If only one operand is complex, promote it if necessary and convert the 997 // other operand to complex. 998 if (LHSComplexFloat) 999 return handleOtherComplexFloatConversion( 1000 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1001 /*convertOtherExpr*/ true); 1002 1003 assert(RHSComplexFloat); 1004 return handleOtherComplexFloatConversion( 1005 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1006 /*convertOtherExpr*/ !IsCompAssign); 1007 } 1008 1009 /// \brief Hande arithmetic conversion from integer to float. Helper function 1010 /// of UsualArithmeticConversions() 1011 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1012 ExprResult &IntExpr, 1013 QualType FloatTy, QualType IntTy, 1014 bool ConvertFloat, bool ConvertInt) { 1015 if (IntTy->isIntegerType()) { 1016 if (ConvertInt) 1017 // Convert intExpr to the lhs floating point type. 1018 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 1019 CK_IntegralToFloating); 1020 return FloatTy; 1021 } 1022 1023 // Convert both sides to the appropriate complex float. 1024 assert(IntTy->isComplexIntegerType()); 1025 QualType result = S.Context.getComplexType(FloatTy); 1026 1027 // _Complex int -> _Complex float 1028 if (ConvertInt) 1029 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 1030 CK_IntegralComplexToFloatingComplex); 1031 1032 // float -> _Complex float 1033 if (ConvertFloat) 1034 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1035 CK_FloatingRealToComplex); 1036 1037 return result; 1038 } 1039 1040 /// \brief Handle arithmethic conversion with floating point types. Helper 1041 /// function of UsualArithmeticConversions() 1042 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1043 ExprResult &RHS, QualType LHSType, 1044 QualType RHSType, bool IsCompAssign) { 1045 bool LHSFloat = LHSType->isRealFloatingType(); 1046 bool RHSFloat = RHSType->isRealFloatingType(); 1047 1048 // If we have two real floating types, convert the smaller operand 1049 // to the bigger result. 1050 if (LHSFloat && RHSFloat) { 1051 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1052 if (order > 0) { 1053 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1054 return LHSType; 1055 } 1056 1057 assert(order < 0 && "illegal float comparison"); 1058 if (!IsCompAssign) 1059 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1060 return RHSType; 1061 } 1062 1063 if (LHSFloat) 1064 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1065 /*convertFloat=*/!IsCompAssign, 1066 /*convertInt=*/ true); 1067 assert(RHSFloat); 1068 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1069 /*convertInt=*/ true, 1070 /*convertFloat=*/!IsCompAssign); 1071 } 1072 1073 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1074 1075 namespace { 1076 /// These helper callbacks are placed in an anonymous namespace to 1077 /// permit their use as function template parameters. 1078 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1079 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1080 } 1081 1082 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1083 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1084 CK_IntegralComplexCast); 1085 } 1086 } 1087 1088 /// \brief Handle integer arithmetic conversions. Helper function of 1089 /// UsualArithmeticConversions() 1090 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1091 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1092 ExprResult &RHS, QualType LHSType, 1093 QualType RHSType, bool IsCompAssign) { 1094 // The rules for this case are in C99 6.3.1.8 1095 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1096 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1097 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1098 if (LHSSigned == RHSSigned) { 1099 // Same signedness; use the higher-ranked type 1100 if (order >= 0) { 1101 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1102 return LHSType; 1103 } else if (!IsCompAssign) 1104 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1105 return RHSType; 1106 } else if (order != (LHSSigned ? 1 : -1)) { 1107 // The unsigned type has greater than or equal rank to the 1108 // signed type, so use the unsigned type 1109 if (RHSSigned) { 1110 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1111 return LHSType; 1112 } else if (!IsCompAssign) 1113 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1114 return RHSType; 1115 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1116 // The two types are different widths; if we are here, that 1117 // means the signed type is larger than the unsigned type, so 1118 // use the signed type. 1119 if (LHSSigned) { 1120 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1121 return LHSType; 1122 } else if (!IsCompAssign) 1123 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1124 return RHSType; 1125 } else { 1126 // The signed type is higher-ranked than the unsigned type, 1127 // but isn't actually any bigger (like unsigned int and long 1128 // on most 32-bit systems). Use the unsigned type corresponding 1129 // to the signed type. 1130 QualType result = 1131 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1132 RHS = (*doRHSCast)(S, RHS.take(), result); 1133 if (!IsCompAssign) 1134 LHS = (*doLHSCast)(S, LHS.take(), result); 1135 return result; 1136 } 1137 } 1138 1139 /// \brief Handle conversions with GCC complex int extension. Helper function 1140 /// of UsualArithmeticConversions() 1141 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1142 ExprResult &RHS, QualType LHSType, 1143 QualType RHSType, 1144 bool IsCompAssign) { 1145 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1146 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1147 1148 if (LHSComplexInt && RHSComplexInt) { 1149 QualType LHSEltType = LHSComplexInt->getElementType(); 1150 QualType RHSEltType = RHSComplexInt->getElementType(); 1151 QualType ScalarType = 1152 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1153 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1154 1155 return S.Context.getComplexType(ScalarType); 1156 } 1157 1158 if (LHSComplexInt) { 1159 QualType LHSEltType = LHSComplexInt->getElementType(); 1160 QualType ScalarType = 1161 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1162 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1163 QualType ComplexType = S.Context.getComplexType(ScalarType); 1164 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1165 CK_IntegralRealToComplex); 1166 1167 return ComplexType; 1168 } 1169 1170 assert(RHSComplexInt); 1171 1172 QualType RHSEltType = RHSComplexInt->getElementType(); 1173 QualType ScalarType = 1174 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1175 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1176 QualType ComplexType = S.Context.getComplexType(ScalarType); 1177 1178 if (!IsCompAssign) 1179 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1180 CK_IntegralRealToComplex); 1181 return ComplexType; 1182 } 1183 1184 /// UsualArithmeticConversions - Performs various conversions that are common to 1185 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1186 /// routine returns the first non-arithmetic type found. The client is 1187 /// responsible for emitting appropriate error diagnostics. 1188 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1189 bool IsCompAssign) { 1190 if (!IsCompAssign) { 1191 LHS = UsualUnaryConversions(LHS.take()); 1192 if (LHS.isInvalid()) 1193 return QualType(); 1194 } 1195 1196 RHS = UsualUnaryConversions(RHS.take()); 1197 if (RHS.isInvalid()) 1198 return QualType(); 1199 1200 // For conversion purposes, we ignore any qualifiers. 1201 // For example, "const float" and "float" are equivalent. 1202 QualType LHSType = 1203 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1204 QualType RHSType = 1205 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1206 1207 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1208 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1209 LHSType = AtomicLHS->getValueType(); 1210 1211 // If both types are identical, no conversion is needed. 1212 if (LHSType == RHSType) 1213 return LHSType; 1214 1215 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1216 // The caller can deal with this (e.g. pointer + int). 1217 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1218 return QualType(); 1219 1220 // Apply unary and bitfield promotions to the LHS's type. 1221 QualType LHSUnpromotedType = LHSType; 1222 if (LHSType->isPromotableIntegerType()) 1223 LHSType = Context.getPromotedIntegerType(LHSType); 1224 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1225 if (!LHSBitfieldPromoteTy.isNull()) 1226 LHSType = LHSBitfieldPromoteTy; 1227 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1228 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1229 1230 // If both types are identical, no conversion is needed. 1231 if (LHSType == RHSType) 1232 return LHSType; 1233 1234 // At this point, we have two different arithmetic types. 1235 1236 // Handle complex types first (C99 6.3.1.8p1). 1237 if (LHSType->isComplexType() || RHSType->isComplexType()) 1238 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1239 IsCompAssign); 1240 1241 // Now handle "real" floating types (i.e. float, double, long double). 1242 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1243 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1244 IsCompAssign); 1245 1246 // Handle GCC complex int extension. 1247 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1248 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1249 IsCompAssign); 1250 1251 // Finally, we have two differing integer types. 1252 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1253 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1254 } 1255 1256 1257 //===----------------------------------------------------------------------===// 1258 // Semantic Analysis for various Expression Types 1259 //===----------------------------------------------------------------------===// 1260 1261 1262 ExprResult 1263 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1264 SourceLocation DefaultLoc, 1265 SourceLocation RParenLoc, 1266 Expr *ControllingExpr, 1267 ArrayRef<ParsedType> ArgTypes, 1268 ArrayRef<Expr *> ArgExprs) { 1269 unsigned NumAssocs = ArgTypes.size(); 1270 assert(NumAssocs == ArgExprs.size()); 1271 1272 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1273 for (unsigned i = 0; i < NumAssocs; ++i) { 1274 if (ArgTypes[i]) 1275 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1276 else 1277 Types[i] = 0; 1278 } 1279 1280 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1281 ControllingExpr, 1282 llvm::makeArrayRef(Types, NumAssocs), 1283 ArgExprs); 1284 delete [] Types; 1285 return ER; 1286 } 1287 1288 ExprResult 1289 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1290 SourceLocation DefaultLoc, 1291 SourceLocation RParenLoc, 1292 Expr *ControllingExpr, 1293 ArrayRef<TypeSourceInfo *> Types, 1294 ArrayRef<Expr *> Exprs) { 1295 unsigned NumAssocs = Types.size(); 1296 assert(NumAssocs == Exprs.size()); 1297 if (ControllingExpr->getType()->isPlaceholderType()) { 1298 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1299 if (result.isInvalid()) return ExprError(); 1300 ControllingExpr = result.take(); 1301 } 1302 1303 bool TypeErrorFound = false, 1304 IsResultDependent = ControllingExpr->isTypeDependent(), 1305 ContainsUnexpandedParameterPack 1306 = ControllingExpr->containsUnexpandedParameterPack(); 1307 1308 for (unsigned i = 0; i < NumAssocs; ++i) { 1309 if (Exprs[i]->containsUnexpandedParameterPack()) 1310 ContainsUnexpandedParameterPack = true; 1311 1312 if (Types[i]) { 1313 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1314 ContainsUnexpandedParameterPack = true; 1315 1316 if (Types[i]->getType()->isDependentType()) { 1317 IsResultDependent = true; 1318 } else { 1319 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1320 // complete object type other than a variably modified type." 1321 unsigned D = 0; 1322 if (Types[i]->getType()->isIncompleteType()) 1323 D = diag::err_assoc_type_incomplete; 1324 else if (!Types[i]->getType()->isObjectType()) 1325 D = diag::err_assoc_type_nonobject; 1326 else if (Types[i]->getType()->isVariablyModifiedType()) 1327 D = diag::err_assoc_type_variably_modified; 1328 1329 if (D != 0) { 1330 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1331 << Types[i]->getTypeLoc().getSourceRange() 1332 << Types[i]->getType(); 1333 TypeErrorFound = true; 1334 } 1335 1336 // C11 6.5.1.1p2 "No two generic associations in the same generic 1337 // selection shall specify compatible types." 1338 for (unsigned j = i+1; j < NumAssocs; ++j) 1339 if (Types[j] && !Types[j]->getType()->isDependentType() && 1340 Context.typesAreCompatible(Types[i]->getType(), 1341 Types[j]->getType())) { 1342 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1343 diag::err_assoc_compatible_types) 1344 << Types[j]->getTypeLoc().getSourceRange() 1345 << Types[j]->getType() 1346 << Types[i]->getType(); 1347 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1348 diag::note_compat_assoc) 1349 << Types[i]->getTypeLoc().getSourceRange() 1350 << Types[i]->getType(); 1351 TypeErrorFound = true; 1352 } 1353 } 1354 } 1355 } 1356 if (TypeErrorFound) 1357 return ExprError(); 1358 1359 // If we determined that the generic selection is result-dependent, don't 1360 // try to compute the result expression. 1361 if (IsResultDependent) 1362 return Owned(new (Context) GenericSelectionExpr( 1363 Context, KeyLoc, ControllingExpr, 1364 Types, Exprs, 1365 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1366 1367 SmallVector<unsigned, 1> CompatIndices; 1368 unsigned DefaultIndex = -1U; 1369 for (unsigned i = 0; i < NumAssocs; ++i) { 1370 if (!Types[i]) 1371 DefaultIndex = i; 1372 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1373 Types[i]->getType())) 1374 CompatIndices.push_back(i); 1375 } 1376 1377 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1378 // type compatible with at most one of the types named in its generic 1379 // association list." 1380 if (CompatIndices.size() > 1) { 1381 // We strip parens here because the controlling expression is typically 1382 // parenthesized in macro definitions. 1383 ControllingExpr = ControllingExpr->IgnoreParens(); 1384 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1385 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1386 << (unsigned) CompatIndices.size(); 1387 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1388 E = CompatIndices.end(); I != E; ++I) { 1389 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1390 diag::note_compat_assoc) 1391 << Types[*I]->getTypeLoc().getSourceRange() 1392 << Types[*I]->getType(); 1393 } 1394 return ExprError(); 1395 } 1396 1397 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1398 // its controlling expression shall have type compatible with exactly one of 1399 // the types named in its generic association list." 1400 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1401 // We strip parens here because the controlling expression is typically 1402 // parenthesized in macro definitions. 1403 ControllingExpr = ControllingExpr->IgnoreParens(); 1404 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1405 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1406 return ExprError(); 1407 } 1408 1409 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1410 // type name that is compatible with the type of the controlling expression, 1411 // then the result expression of the generic selection is the expression 1412 // in that generic association. Otherwise, the result expression of the 1413 // generic selection is the expression in the default generic association." 1414 unsigned ResultIndex = 1415 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1416 1417 return Owned(new (Context) GenericSelectionExpr( 1418 Context, KeyLoc, ControllingExpr, 1419 Types, Exprs, 1420 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1421 ResultIndex)); 1422 } 1423 1424 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1425 /// location of the token and the offset of the ud-suffix within it. 1426 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1427 unsigned Offset) { 1428 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1429 S.getLangOpts()); 1430 } 1431 1432 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1433 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1434 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1435 IdentifierInfo *UDSuffix, 1436 SourceLocation UDSuffixLoc, 1437 ArrayRef<Expr*> Args, 1438 SourceLocation LitEndLoc) { 1439 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1440 1441 QualType ArgTy[2]; 1442 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1443 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1444 if (ArgTy[ArgIdx]->isArrayType()) 1445 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1446 } 1447 1448 DeclarationName OpName = 1449 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1450 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1451 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1452 1453 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1454 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1455 /*AllowRaw*/false, /*AllowTemplate*/false, 1456 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1457 return ExprError(); 1458 1459 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1460 } 1461 1462 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1463 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1464 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1465 /// multiple tokens. However, the common case is that StringToks points to one 1466 /// string. 1467 /// 1468 ExprResult 1469 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1470 Scope *UDLScope) { 1471 assert(NumStringToks && "Must have at least one string!"); 1472 1473 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1474 if (Literal.hadError) 1475 return ExprError(); 1476 1477 SmallVector<SourceLocation, 4> StringTokLocs; 1478 for (unsigned i = 0; i != NumStringToks; ++i) 1479 StringTokLocs.push_back(StringToks[i].getLocation()); 1480 1481 QualType CharTy = Context.CharTy; 1482 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1483 if (Literal.isWide()) { 1484 CharTy = Context.getWideCharType(); 1485 Kind = StringLiteral::Wide; 1486 } else if (Literal.isUTF8()) { 1487 Kind = StringLiteral::UTF8; 1488 } else if (Literal.isUTF16()) { 1489 CharTy = Context.Char16Ty; 1490 Kind = StringLiteral::UTF16; 1491 } else if (Literal.isUTF32()) { 1492 CharTy = Context.Char32Ty; 1493 Kind = StringLiteral::UTF32; 1494 } else if (Literal.isPascal()) { 1495 CharTy = Context.UnsignedCharTy; 1496 } 1497 1498 QualType CharTyConst = CharTy; 1499 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1500 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1501 CharTyConst.addConst(); 1502 1503 // Get an array type for the string, according to C99 6.4.5. This includes 1504 // the nul terminator character as well as the string length for pascal 1505 // strings. 1506 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1507 llvm::APInt(32, Literal.GetNumStringChars()+1), 1508 ArrayType::Normal, 0); 1509 1510 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1511 if (getLangOpts().OpenCL) { 1512 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1513 } 1514 1515 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1516 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1517 Kind, Literal.Pascal, StrTy, 1518 &StringTokLocs[0], 1519 StringTokLocs.size()); 1520 if (Literal.getUDSuffix().empty()) 1521 return Owned(Lit); 1522 1523 // We're building a user-defined literal. 1524 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1525 SourceLocation UDSuffixLoc = 1526 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1527 Literal.getUDSuffixOffset()); 1528 1529 // Make sure we're allowed user-defined literals here. 1530 if (!UDLScope) 1531 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1532 1533 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1534 // operator "" X (str, len) 1535 QualType SizeType = Context.getSizeType(); 1536 1537 DeclarationName OpName = 1538 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1539 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1540 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1541 1542 QualType ArgTy[] = { 1543 Context.getArrayDecayedType(StrTy), SizeType 1544 }; 1545 1546 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1547 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1548 /*AllowRaw*/false, /*AllowTemplate*/false, 1549 /*AllowStringTemplate*/true)) { 1550 1551 case LOLR_Cooked: { 1552 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1553 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1554 StringTokLocs[0]); 1555 Expr *Args[] = { Lit, LenArg }; 1556 1557 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1558 } 1559 1560 case LOLR_StringTemplate: { 1561 TemplateArgumentListInfo ExplicitArgs; 1562 1563 unsigned CharBits = Context.getIntWidth(CharTy); 1564 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1565 llvm::APSInt Value(CharBits, CharIsUnsigned); 1566 1567 TemplateArgument TypeArg(CharTy); 1568 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1569 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1570 1571 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1572 Value = Lit->getCodeUnit(I); 1573 TemplateArgument Arg(Context, Value, CharTy); 1574 TemplateArgumentLocInfo ArgInfo; 1575 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1576 } 1577 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1578 &ExplicitArgs); 1579 } 1580 case LOLR_Raw: 1581 case LOLR_Template: 1582 llvm_unreachable("unexpected literal operator lookup result"); 1583 case LOLR_Error: 1584 return ExprError(); 1585 } 1586 llvm_unreachable("unexpected literal operator lookup result"); 1587 } 1588 1589 ExprResult 1590 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1591 SourceLocation Loc, 1592 const CXXScopeSpec *SS) { 1593 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1594 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1595 } 1596 1597 /// BuildDeclRefExpr - Build an expression that references a 1598 /// declaration that does not require a closure capture. 1599 ExprResult 1600 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1601 const DeclarationNameInfo &NameInfo, 1602 const CXXScopeSpec *SS, NamedDecl *FoundD, 1603 const TemplateArgumentListInfo *TemplateArgs) { 1604 if (getLangOpts().CUDA) 1605 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1606 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1607 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1608 CalleeTarget = IdentifyCUDATarget(Callee); 1609 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1610 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1611 << CalleeTarget << D->getIdentifier() << CallerTarget; 1612 Diag(D->getLocation(), diag::note_previous_decl) 1613 << D->getIdentifier(); 1614 return ExprError(); 1615 } 1616 } 1617 1618 bool refersToEnclosingScope = 1619 (CurContext != D->getDeclContext() && 1620 D->getDeclContext()->isFunctionOrMethod()) || 1621 (isa<VarDecl>(D) && 1622 cast<VarDecl>(D)->isInitCapture()); 1623 1624 DeclRefExpr *E; 1625 if (isa<VarTemplateSpecializationDecl>(D)) { 1626 VarTemplateSpecializationDecl *VarSpec = 1627 cast<VarTemplateSpecializationDecl>(D); 1628 1629 E = DeclRefExpr::Create( 1630 Context, 1631 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1632 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1633 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1634 } else { 1635 assert(!TemplateArgs && "No template arguments for non-variable" 1636 " template specialization references"); 1637 E = DeclRefExpr::Create( 1638 Context, 1639 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1640 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1641 } 1642 1643 MarkDeclRefReferenced(E); 1644 1645 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1646 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1647 DiagnosticsEngine::Level Level = 1648 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1649 E->getLocStart()); 1650 if (Level != DiagnosticsEngine::Ignored) 1651 recordUseOfEvaluatedWeak(E); 1652 } 1653 1654 // Just in case we're building an illegal pointer-to-member. 1655 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1656 if (FD && FD->isBitField()) 1657 E->setObjectKind(OK_BitField); 1658 1659 return Owned(E); 1660 } 1661 1662 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1663 /// possibly a list of template arguments. 1664 /// 1665 /// If this produces template arguments, it is permitted to call 1666 /// DecomposeTemplateName. 1667 /// 1668 /// This actually loses a lot of source location information for 1669 /// non-standard name kinds; we should consider preserving that in 1670 /// some way. 1671 void 1672 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1673 TemplateArgumentListInfo &Buffer, 1674 DeclarationNameInfo &NameInfo, 1675 const TemplateArgumentListInfo *&TemplateArgs) { 1676 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1677 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1678 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1679 1680 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1681 Id.TemplateId->NumArgs); 1682 translateTemplateArguments(TemplateArgsPtr, Buffer); 1683 1684 TemplateName TName = Id.TemplateId->Template.get(); 1685 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1686 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1687 TemplateArgs = &Buffer; 1688 } else { 1689 NameInfo = GetNameFromUnqualifiedId(Id); 1690 TemplateArgs = 0; 1691 } 1692 } 1693 1694 /// Diagnose an empty lookup. 1695 /// 1696 /// \return false if new lookup candidates were found 1697 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1698 CorrectionCandidateCallback &CCC, 1699 TemplateArgumentListInfo *ExplicitTemplateArgs, 1700 ArrayRef<Expr *> Args) { 1701 DeclarationName Name = R.getLookupName(); 1702 1703 unsigned diagnostic = diag::err_undeclared_var_use; 1704 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1705 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1706 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1707 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1708 diagnostic = diag::err_undeclared_use; 1709 diagnostic_suggest = diag::err_undeclared_use_suggest; 1710 } 1711 1712 // If the original lookup was an unqualified lookup, fake an 1713 // unqualified lookup. This is useful when (for example) the 1714 // original lookup would not have found something because it was a 1715 // dependent name. 1716 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1717 ? CurContext : 0; 1718 while (DC) { 1719 if (isa<CXXRecordDecl>(DC)) { 1720 LookupQualifiedName(R, DC); 1721 1722 if (!R.empty()) { 1723 // Don't give errors about ambiguities in this lookup. 1724 R.suppressDiagnostics(); 1725 1726 // During a default argument instantiation the CurContext points 1727 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1728 // function parameter list, hence add an explicit check. 1729 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1730 ActiveTemplateInstantiations.back().Kind == 1731 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1732 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1733 bool isInstance = CurMethod && 1734 CurMethod->isInstance() && 1735 DC == CurMethod->getParent() && !isDefaultArgument; 1736 1737 1738 // Give a code modification hint to insert 'this->'. 1739 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1740 // Actually quite difficult! 1741 if (getLangOpts().MSVCCompat) 1742 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1743 if (isInstance) { 1744 Diag(R.getNameLoc(), diagnostic) << Name 1745 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1746 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1747 CallsUndergoingInstantiation.back()->getCallee()); 1748 1749 CXXMethodDecl *DepMethod; 1750 if (CurMethod->isDependentContext()) 1751 DepMethod = CurMethod; 1752 else if (CurMethod->getTemplatedKind() == 1753 FunctionDecl::TK_FunctionTemplateSpecialization) 1754 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1755 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1756 else 1757 DepMethod = cast<CXXMethodDecl>( 1758 CurMethod->getInstantiatedFromMemberFunction()); 1759 assert(DepMethod && "No template pattern found"); 1760 1761 QualType DepThisType = DepMethod->getThisType(Context); 1762 CheckCXXThisCapture(R.getNameLoc()); 1763 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1764 R.getNameLoc(), DepThisType, false); 1765 TemplateArgumentListInfo TList; 1766 if (ULE->hasExplicitTemplateArgs()) 1767 ULE->copyTemplateArgumentsInto(TList); 1768 1769 CXXScopeSpec SS; 1770 SS.Adopt(ULE->getQualifierLoc()); 1771 CXXDependentScopeMemberExpr *DepExpr = 1772 CXXDependentScopeMemberExpr::Create( 1773 Context, DepThis, DepThisType, true, SourceLocation(), 1774 SS.getWithLocInContext(Context), 1775 ULE->getTemplateKeywordLoc(), 0, 1776 R.getLookupNameInfo(), 1777 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1778 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1779 } else { 1780 Diag(R.getNameLoc(), diagnostic) << Name; 1781 } 1782 1783 // Do we really want to note all of these? 1784 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1785 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1786 1787 // Return true if we are inside a default argument instantiation 1788 // and the found name refers to an instance member function, otherwise 1789 // the function calling DiagnoseEmptyLookup will try to create an 1790 // implicit member call and this is wrong for default argument. 1791 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1792 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1793 return true; 1794 } 1795 1796 // Tell the callee to try to recover. 1797 return false; 1798 } 1799 1800 R.clear(); 1801 } 1802 1803 // In Microsoft mode, if we are performing lookup from within a friend 1804 // function definition declared at class scope then we must set 1805 // DC to the lexical parent to be able to search into the parent 1806 // class. 1807 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1808 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1809 DC->getLexicalParent()->isRecord()) 1810 DC = DC->getLexicalParent(); 1811 else 1812 DC = DC->getParent(); 1813 } 1814 1815 // We didn't find anything, so try to correct for a typo. 1816 TypoCorrection Corrected; 1817 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1818 S, &SS, CCC))) { 1819 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1820 bool DroppedSpecifier = 1821 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1822 R.setLookupName(Corrected.getCorrection()); 1823 1824 bool AcceptableWithRecovery = false; 1825 bool AcceptableWithoutRecovery = false; 1826 NamedDecl *ND = Corrected.getCorrectionDecl(); 1827 if (ND) { 1828 if (Corrected.isOverloaded()) { 1829 OverloadCandidateSet OCS(R.getNameLoc()); 1830 OverloadCandidateSet::iterator Best; 1831 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1832 CDEnd = Corrected.end(); 1833 CD != CDEnd; ++CD) { 1834 if (FunctionTemplateDecl *FTD = 1835 dyn_cast<FunctionTemplateDecl>(*CD)) 1836 AddTemplateOverloadCandidate( 1837 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1838 Args, OCS); 1839 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1840 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1841 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1842 Args, OCS); 1843 } 1844 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1845 case OR_Success: 1846 ND = Best->Function; 1847 Corrected.setCorrectionDecl(ND); 1848 break; 1849 default: 1850 // FIXME: Arbitrarily pick the first declaration for the note. 1851 Corrected.setCorrectionDecl(ND); 1852 break; 1853 } 1854 } 1855 R.addDecl(ND); 1856 1857 AcceptableWithRecovery = 1858 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1859 // FIXME: If we ended up with a typo for a type name or 1860 // Objective-C class name, we're in trouble because the parser 1861 // is in the wrong place to recover. Suggest the typo 1862 // correction, but don't make it a fix-it since we're not going 1863 // to recover well anyway. 1864 AcceptableWithoutRecovery = 1865 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1866 } else { 1867 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1868 // because we aren't able to recover. 1869 AcceptableWithoutRecovery = true; 1870 } 1871 1872 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1873 unsigned NoteID = (Corrected.getCorrectionDecl() && 1874 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1875 ? diag::note_implicit_param_decl 1876 : diag::note_previous_decl; 1877 if (SS.isEmpty()) 1878 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1879 PDiag(NoteID), AcceptableWithRecovery); 1880 else 1881 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1882 << Name << computeDeclContext(SS, false) 1883 << DroppedSpecifier << SS.getRange(), 1884 PDiag(NoteID), AcceptableWithRecovery); 1885 1886 // Tell the callee whether to try to recover. 1887 return !AcceptableWithRecovery; 1888 } 1889 } 1890 R.clear(); 1891 1892 // Emit a special diagnostic for failed member lookups. 1893 // FIXME: computing the declaration context might fail here (?) 1894 if (!SS.isEmpty()) { 1895 Diag(R.getNameLoc(), diag::err_no_member) 1896 << Name << computeDeclContext(SS, false) 1897 << SS.getRange(); 1898 return true; 1899 } 1900 1901 // Give up, we can't recover. 1902 Diag(R.getNameLoc(), diagnostic) << Name; 1903 return true; 1904 } 1905 1906 ExprResult Sema::ActOnIdExpression(Scope *S, 1907 CXXScopeSpec &SS, 1908 SourceLocation TemplateKWLoc, 1909 UnqualifiedId &Id, 1910 bool HasTrailingLParen, 1911 bool IsAddressOfOperand, 1912 CorrectionCandidateCallback *CCC, 1913 bool IsInlineAsmIdentifier) { 1914 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1915 "cannot be direct & operand and have a trailing lparen"); 1916 if (SS.isInvalid()) 1917 return ExprError(); 1918 1919 TemplateArgumentListInfo TemplateArgsBuffer; 1920 1921 // Decompose the UnqualifiedId into the following data. 1922 DeclarationNameInfo NameInfo; 1923 const TemplateArgumentListInfo *TemplateArgs; 1924 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1925 1926 DeclarationName Name = NameInfo.getName(); 1927 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1928 SourceLocation NameLoc = NameInfo.getLoc(); 1929 1930 // C++ [temp.dep.expr]p3: 1931 // An id-expression is type-dependent if it contains: 1932 // -- an identifier that was declared with a dependent type, 1933 // (note: handled after lookup) 1934 // -- a template-id that is dependent, 1935 // (note: handled in BuildTemplateIdExpr) 1936 // -- a conversion-function-id that specifies a dependent type, 1937 // -- a nested-name-specifier that contains a class-name that 1938 // names a dependent type. 1939 // Determine whether this is a member of an unknown specialization; 1940 // we need to handle these differently. 1941 bool DependentID = false; 1942 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1943 Name.getCXXNameType()->isDependentType()) { 1944 DependentID = true; 1945 } else if (SS.isSet()) { 1946 if (DeclContext *DC = computeDeclContext(SS, false)) { 1947 if (RequireCompleteDeclContext(SS, DC)) 1948 return ExprError(); 1949 } else { 1950 DependentID = true; 1951 } 1952 } 1953 1954 if (DependentID) 1955 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1956 IsAddressOfOperand, TemplateArgs); 1957 1958 // Perform the required lookup. 1959 LookupResult R(*this, NameInfo, 1960 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1961 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1962 if (TemplateArgs) { 1963 // Lookup the template name again to correctly establish the context in 1964 // which it was found. This is really unfortunate as we already did the 1965 // lookup to determine that it was a template name in the first place. If 1966 // this becomes a performance hit, we can work harder to preserve those 1967 // results until we get here but it's likely not worth it. 1968 bool MemberOfUnknownSpecialization; 1969 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1970 MemberOfUnknownSpecialization); 1971 1972 if (MemberOfUnknownSpecialization || 1973 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1974 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1975 IsAddressOfOperand, TemplateArgs); 1976 } else { 1977 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1978 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1979 1980 // If the result might be in a dependent base class, this is a dependent 1981 // id-expression. 1982 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1983 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1984 IsAddressOfOperand, TemplateArgs); 1985 1986 // If this reference is in an Objective-C method, then we need to do 1987 // some special Objective-C lookup, too. 1988 if (IvarLookupFollowUp) { 1989 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1990 if (E.isInvalid()) 1991 return ExprError(); 1992 1993 if (Expr *Ex = E.takeAs<Expr>()) 1994 return Owned(Ex); 1995 } 1996 } 1997 1998 if (R.isAmbiguous()) 1999 return ExprError(); 2000 2001 // Determine whether this name might be a candidate for 2002 // argument-dependent lookup. 2003 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2004 2005 if (R.empty() && !ADL) { 2006 2007 // Otherwise, this could be an implicitly declared function reference (legal 2008 // in C90, extension in C99, forbidden in C++). 2009 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2010 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2011 if (D) R.addDecl(D); 2012 } 2013 2014 // If this name wasn't predeclared and if this is not a function 2015 // call, diagnose the problem. 2016 if (R.empty()) { 2017 // In Microsoft mode, if we are inside a template class member function 2018 // whose parent class has dependent base classes, and we can't resolve 2019 // an identifier, then assume the identifier is a member of a dependent 2020 // base class. The goal is to postpone name lookup to instantiation time 2021 // to be able to search into the type dependent base classes. 2022 // FIXME: If we want 100% compatibility with MSVC, we will have delay all 2023 // unqualified name lookup. Any name lookup during template parsing means 2024 // clang might find something that MSVC doesn't. For now, we only handle 2025 // the common case of members of a dependent base class. 2026 if (getLangOpts().MSVCCompat) { 2027 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 2028 if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) { 2029 assert(SS.isEmpty() && "qualifiers should be already handled"); 2030 QualType ThisType = MD->getThisType(Context); 2031 // Since the 'this' expression is synthesized, we don't need to 2032 // perform the double-lookup check. 2033 NamedDecl *FirstQualifierInScope = 0; 2034 return Owned(CXXDependentScopeMemberExpr::Create( 2035 Context, /*This=*/0, ThisType, /*IsArrow=*/true, 2036 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), 2037 TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs)); 2038 } 2039 } 2040 2041 // Don't diagnose an empty lookup for inline assmebly. 2042 if (IsInlineAsmIdentifier) 2043 return ExprError(); 2044 2045 CorrectionCandidateCallback DefaultValidator; 2046 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2047 return ExprError(); 2048 2049 assert(!R.empty() && 2050 "DiagnoseEmptyLookup returned false but added no results"); 2051 2052 // If we found an Objective-C instance variable, let 2053 // LookupInObjCMethod build the appropriate expression to 2054 // reference the ivar. 2055 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2056 R.clear(); 2057 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2058 // In a hopelessly buggy code, Objective-C instance variable 2059 // lookup fails and no expression will be built to reference it. 2060 if (!E.isInvalid() && !E.get()) 2061 return ExprError(); 2062 return E; 2063 } 2064 } 2065 } 2066 2067 // This is guaranteed from this point on. 2068 assert(!R.empty() || ADL); 2069 2070 // Check whether this might be a C++ implicit instance member access. 2071 // C++ [class.mfct.non-static]p3: 2072 // When an id-expression that is not part of a class member access 2073 // syntax and not used to form a pointer to member is used in the 2074 // body of a non-static member function of class X, if name lookup 2075 // resolves the name in the id-expression to a non-static non-type 2076 // member of some class C, the id-expression is transformed into a 2077 // class member access expression using (*this) as the 2078 // postfix-expression to the left of the . operator. 2079 // 2080 // But we don't actually need to do this for '&' operands if R 2081 // resolved to a function or overloaded function set, because the 2082 // expression is ill-formed if it actually works out to be a 2083 // non-static member function: 2084 // 2085 // C++ [expr.ref]p4: 2086 // Otherwise, if E1.E2 refers to a non-static member function. . . 2087 // [t]he expression can be used only as the left-hand operand of a 2088 // member function call. 2089 // 2090 // There are other safeguards against such uses, but it's important 2091 // to get this right here so that we don't end up making a 2092 // spuriously dependent expression if we're inside a dependent 2093 // instance method. 2094 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2095 bool MightBeImplicitMember; 2096 if (!IsAddressOfOperand) 2097 MightBeImplicitMember = true; 2098 else if (!SS.isEmpty()) 2099 MightBeImplicitMember = false; 2100 else if (R.isOverloadedResult()) 2101 MightBeImplicitMember = false; 2102 else if (R.isUnresolvableResult()) 2103 MightBeImplicitMember = true; 2104 else 2105 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2106 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2107 isa<MSPropertyDecl>(R.getFoundDecl()); 2108 2109 if (MightBeImplicitMember) 2110 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2111 R, TemplateArgs); 2112 } 2113 2114 if (TemplateArgs || TemplateKWLoc.isValid()) { 2115 2116 // In C++1y, if this is a variable template id, then check it 2117 // in BuildTemplateIdExpr(). 2118 // The single lookup result must be a variable template declaration. 2119 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2120 Id.TemplateId->Kind == TNK_Var_template) { 2121 assert(R.getAsSingle<VarTemplateDecl>() && 2122 "There should only be one declaration found."); 2123 } 2124 2125 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2126 } 2127 2128 return BuildDeclarationNameExpr(SS, R, ADL); 2129 } 2130 2131 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2132 /// declaration name, generally during template instantiation. 2133 /// There's a large number of things which don't need to be done along 2134 /// this path. 2135 ExprResult 2136 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2137 const DeclarationNameInfo &NameInfo, 2138 bool IsAddressOfOperand) { 2139 DeclContext *DC = computeDeclContext(SS, false); 2140 if (!DC) 2141 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2142 NameInfo, /*TemplateArgs=*/0); 2143 2144 if (RequireCompleteDeclContext(SS, DC)) 2145 return ExprError(); 2146 2147 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2148 LookupQualifiedName(R, DC); 2149 2150 if (R.isAmbiguous()) 2151 return ExprError(); 2152 2153 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2154 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2155 NameInfo, /*TemplateArgs=*/0); 2156 2157 if (R.empty()) { 2158 Diag(NameInfo.getLoc(), diag::err_no_member) 2159 << NameInfo.getName() << DC << SS.getRange(); 2160 return ExprError(); 2161 } 2162 2163 // Defend against this resolving to an implicit member access. We usually 2164 // won't get here if this might be a legitimate a class member (we end up in 2165 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2166 // a pointer-to-member or in an unevaluated context in C++11. 2167 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2168 return BuildPossibleImplicitMemberExpr(SS, 2169 /*TemplateKWLoc=*/SourceLocation(), 2170 R, /*TemplateArgs=*/0); 2171 2172 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2173 } 2174 2175 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2176 /// detected that we're currently inside an ObjC method. Perform some 2177 /// additional lookup. 2178 /// 2179 /// Ideally, most of this would be done by lookup, but there's 2180 /// actually quite a lot of extra work involved. 2181 /// 2182 /// Returns a null sentinel to indicate trivial success. 2183 ExprResult 2184 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2185 IdentifierInfo *II, bool AllowBuiltinCreation) { 2186 SourceLocation Loc = Lookup.getNameLoc(); 2187 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2188 2189 // Check for error condition which is already reported. 2190 if (!CurMethod) 2191 return ExprError(); 2192 2193 // There are two cases to handle here. 1) scoped lookup could have failed, 2194 // in which case we should look for an ivar. 2) scoped lookup could have 2195 // found a decl, but that decl is outside the current instance method (i.e. 2196 // a global variable). In these two cases, we do a lookup for an ivar with 2197 // this name, if the lookup sucedes, we replace it our current decl. 2198 2199 // If we're in a class method, we don't normally want to look for 2200 // ivars. But if we don't find anything else, and there's an 2201 // ivar, that's an error. 2202 bool IsClassMethod = CurMethod->isClassMethod(); 2203 2204 bool LookForIvars; 2205 if (Lookup.empty()) 2206 LookForIvars = true; 2207 else if (IsClassMethod) 2208 LookForIvars = false; 2209 else 2210 LookForIvars = (Lookup.isSingleResult() && 2211 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2212 ObjCInterfaceDecl *IFace = 0; 2213 if (LookForIvars) { 2214 IFace = CurMethod->getClassInterface(); 2215 ObjCInterfaceDecl *ClassDeclared; 2216 ObjCIvarDecl *IV = 0; 2217 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2218 // Diagnose using an ivar in a class method. 2219 if (IsClassMethod) 2220 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2221 << IV->getDeclName()); 2222 2223 // If we're referencing an invalid decl, just return this as a silent 2224 // error node. The error diagnostic was already emitted on the decl. 2225 if (IV->isInvalidDecl()) 2226 return ExprError(); 2227 2228 // Check if referencing a field with __attribute__((deprecated)). 2229 if (DiagnoseUseOfDecl(IV, Loc)) 2230 return ExprError(); 2231 2232 // Diagnose the use of an ivar outside of the declaring class. 2233 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2234 !declaresSameEntity(ClassDeclared, IFace) && 2235 !getLangOpts().DebuggerSupport) 2236 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2237 2238 // FIXME: This should use a new expr for a direct reference, don't 2239 // turn this into Self->ivar, just return a BareIVarExpr or something. 2240 IdentifierInfo &II = Context.Idents.get("self"); 2241 UnqualifiedId SelfName; 2242 SelfName.setIdentifier(&II, SourceLocation()); 2243 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2244 CXXScopeSpec SelfScopeSpec; 2245 SourceLocation TemplateKWLoc; 2246 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2247 SelfName, false, false); 2248 if (SelfExpr.isInvalid()) 2249 return ExprError(); 2250 2251 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2252 if (SelfExpr.isInvalid()) 2253 return ExprError(); 2254 2255 MarkAnyDeclReferenced(Loc, IV, true); 2256 2257 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2258 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2259 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2260 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2261 2262 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2263 Loc, IV->getLocation(), 2264 SelfExpr.take(), 2265 true, true); 2266 2267 if (getLangOpts().ObjCAutoRefCount) { 2268 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2269 DiagnosticsEngine::Level Level = 2270 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2271 if (Level != DiagnosticsEngine::Ignored) 2272 recordUseOfEvaluatedWeak(Result); 2273 } 2274 if (CurContext->isClosure()) 2275 Diag(Loc, diag::warn_implicitly_retains_self) 2276 << FixItHint::CreateInsertion(Loc, "self->"); 2277 } 2278 2279 return Owned(Result); 2280 } 2281 } else if (CurMethod->isInstanceMethod()) { 2282 // We should warn if a local variable hides an ivar. 2283 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2284 ObjCInterfaceDecl *ClassDeclared; 2285 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2286 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2287 declaresSameEntity(IFace, ClassDeclared)) 2288 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2289 } 2290 } 2291 } else if (Lookup.isSingleResult() && 2292 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2293 // If accessing a stand-alone ivar in a class method, this is an error. 2294 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2295 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2296 << IV->getDeclName()); 2297 } 2298 2299 if (Lookup.empty() && II && AllowBuiltinCreation) { 2300 // FIXME. Consolidate this with similar code in LookupName. 2301 if (unsigned BuiltinID = II->getBuiltinID()) { 2302 if (!(getLangOpts().CPlusPlus && 2303 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2304 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2305 S, Lookup.isForRedeclaration(), 2306 Lookup.getNameLoc()); 2307 if (D) Lookup.addDecl(D); 2308 } 2309 } 2310 } 2311 // Sentinel value saying that we didn't do anything special. 2312 return Owned((Expr*) 0); 2313 } 2314 2315 /// \brief Cast a base object to a member's actual type. 2316 /// 2317 /// Logically this happens in three phases: 2318 /// 2319 /// * First we cast from the base type to the naming class. 2320 /// The naming class is the class into which we were looking 2321 /// when we found the member; it's the qualifier type if a 2322 /// qualifier was provided, and otherwise it's the base type. 2323 /// 2324 /// * Next we cast from the naming class to the declaring class. 2325 /// If the member we found was brought into a class's scope by 2326 /// a using declaration, this is that class; otherwise it's 2327 /// the class declaring the member. 2328 /// 2329 /// * Finally we cast from the declaring class to the "true" 2330 /// declaring class of the member. This conversion does not 2331 /// obey access control. 2332 ExprResult 2333 Sema::PerformObjectMemberConversion(Expr *From, 2334 NestedNameSpecifier *Qualifier, 2335 NamedDecl *FoundDecl, 2336 NamedDecl *Member) { 2337 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2338 if (!RD) 2339 return Owned(From); 2340 2341 QualType DestRecordType; 2342 QualType DestType; 2343 QualType FromRecordType; 2344 QualType FromType = From->getType(); 2345 bool PointerConversions = false; 2346 if (isa<FieldDecl>(Member)) { 2347 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2348 2349 if (FromType->getAs<PointerType>()) { 2350 DestType = Context.getPointerType(DestRecordType); 2351 FromRecordType = FromType->getPointeeType(); 2352 PointerConversions = true; 2353 } else { 2354 DestType = DestRecordType; 2355 FromRecordType = FromType; 2356 } 2357 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2358 if (Method->isStatic()) 2359 return Owned(From); 2360 2361 DestType = Method->getThisType(Context); 2362 DestRecordType = DestType->getPointeeType(); 2363 2364 if (FromType->getAs<PointerType>()) { 2365 FromRecordType = FromType->getPointeeType(); 2366 PointerConversions = true; 2367 } else { 2368 FromRecordType = FromType; 2369 DestType = DestRecordType; 2370 } 2371 } else { 2372 // No conversion necessary. 2373 return Owned(From); 2374 } 2375 2376 if (DestType->isDependentType() || FromType->isDependentType()) 2377 return Owned(From); 2378 2379 // If the unqualified types are the same, no conversion is necessary. 2380 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2381 return Owned(From); 2382 2383 SourceRange FromRange = From->getSourceRange(); 2384 SourceLocation FromLoc = FromRange.getBegin(); 2385 2386 ExprValueKind VK = From->getValueKind(); 2387 2388 // C++ [class.member.lookup]p8: 2389 // [...] Ambiguities can often be resolved by qualifying a name with its 2390 // class name. 2391 // 2392 // If the member was a qualified name and the qualified referred to a 2393 // specific base subobject type, we'll cast to that intermediate type 2394 // first and then to the object in which the member is declared. That allows 2395 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2396 // 2397 // class Base { public: int x; }; 2398 // class Derived1 : public Base { }; 2399 // class Derived2 : public Base { }; 2400 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2401 // 2402 // void VeryDerived::f() { 2403 // x = 17; // error: ambiguous base subobjects 2404 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2405 // } 2406 if (Qualifier && Qualifier->getAsType()) { 2407 QualType QType = QualType(Qualifier->getAsType(), 0); 2408 assert(QType->isRecordType() && "lookup done with non-record type"); 2409 2410 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2411 2412 // In C++98, the qualifier type doesn't actually have to be a base 2413 // type of the object type, in which case we just ignore it. 2414 // Otherwise build the appropriate casts. 2415 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2416 CXXCastPath BasePath; 2417 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2418 FromLoc, FromRange, &BasePath)) 2419 return ExprError(); 2420 2421 if (PointerConversions) 2422 QType = Context.getPointerType(QType); 2423 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2424 VK, &BasePath).take(); 2425 2426 FromType = QType; 2427 FromRecordType = QRecordType; 2428 2429 // If the qualifier type was the same as the destination type, 2430 // we're done. 2431 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2432 return Owned(From); 2433 } 2434 } 2435 2436 bool IgnoreAccess = false; 2437 2438 // If we actually found the member through a using declaration, cast 2439 // down to the using declaration's type. 2440 // 2441 // Pointer equality is fine here because only one declaration of a 2442 // class ever has member declarations. 2443 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2444 assert(isa<UsingShadowDecl>(FoundDecl)); 2445 QualType URecordType = Context.getTypeDeclType( 2446 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2447 2448 // We only need to do this if the naming-class to declaring-class 2449 // conversion is non-trivial. 2450 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2451 assert(IsDerivedFrom(FromRecordType, URecordType)); 2452 CXXCastPath BasePath; 2453 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2454 FromLoc, FromRange, &BasePath)) 2455 return ExprError(); 2456 2457 QualType UType = URecordType; 2458 if (PointerConversions) 2459 UType = Context.getPointerType(UType); 2460 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2461 VK, &BasePath).take(); 2462 FromType = UType; 2463 FromRecordType = URecordType; 2464 } 2465 2466 // We don't do access control for the conversion from the 2467 // declaring class to the true declaring class. 2468 IgnoreAccess = true; 2469 } 2470 2471 CXXCastPath BasePath; 2472 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2473 FromLoc, FromRange, &BasePath, 2474 IgnoreAccess)) 2475 return ExprError(); 2476 2477 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2478 VK, &BasePath); 2479 } 2480 2481 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2482 const LookupResult &R, 2483 bool HasTrailingLParen) { 2484 // Only when used directly as the postfix-expression of a call. 2485 if (!HasTrailingLParen) 2486 return false; 2487 2488 // Never if a scope specifier was provided. 2489 if (SS.isSet()) 2490 return false; 2491 2492 // Only in C++ or ObjC++. 2493 if (!getLangOpts().CPlusPlus) 2494 return false; 2495 2496 // Turn off ADL when we find certain kinds of declarations during 2497 // normal lookup: 2498 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2499 NamedDecl *D = *I; 2500 2501 // C++0x [basic.lookup.argdep]p3: 2502 // -- a declaration of a class member 2503 // Since using decls preserve this property, we check this on the 2504 // original decl. 2505 if (D->isCXXClassMember()) 2506 return false; 2507 2508 // C++0x [basic.lookup.argdep]p3: 2509 // -- a block-scope function declaration that is not a 2510 // using-declaration 2511 // NOTE: we also trigger this for function templates (in fact, we 2512 // don't check the decl type at all, since all other decl types 2513 // turn off ADL anyway). 2514 if (isa<UsingShadowDecl>(D)) 2515 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2516 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2517 return false; 2518 2519 // C++0x [basic.lookup.argdep]p3: 2520 // -- a declaration that is neither a function or a function 2521 // template 2522 // And also for builtin functions. 2523 if (isa<FunctionDecl>(D)) { 2524 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2525 2526 // But also builtin functions. 2527 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2528 return false; 2529 } else if (!isa<FunctionTemplateDecl>(D)) 2530 return false; 2531 } 2532 2533 return true; 2534 } 2535 2536 2537 /// Diagnoses obvious problems with the use of the given declaration 2538 /// as an expression. This is only actually called for lookups that 2539 /// were not overloaded, and it doesn't promise that the declaration 2540 /// will in fact be used. 2541 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2542 if (isa<TypedefNameDecl>(D)) { 2543 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2544 return true; 2545 } 2546 2547 if (isa<ObjCInterfaceDecl>(D)) { 2548 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2549 return true; 2550 } 2551 2552 if (isa<NamespaceDecl>(D)) { 2553 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2554 return true; 2555 } 2556 2557 return false; 2558 } 2559 2560 ExprResult 2561 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2562 LookupResult &R, 2563 bool NeedsADL) { 2564 // If this is a single, fully-resolved result and we don't need ADL, 2565 // just build an ordinary singleton decl ref. 2566 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2567 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2568 R.getRepresentativeDecl()); 2569 2570 // We only need to check the declaration if there's exactly one 2571 // result, because in the overloaded case the results can only be 2572 // functions and function templates. 2573 if (R.isSingleResult() && 2574 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2575 return ExprError(); 2576 2577 // Otherwise, just build an unresolved lookup expression. Suppress 2578 // any lookup-related diagnostics; we'll hash these out later, when 2579 // we've picked a target. 2580 R.suppressDiagnostics(); 2581 2582 UnresolvedLookupExpr *ULE 2583 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2584 SS.getWithLocInContext(Context), 2585 R.getLookupNameInfo(), 2586 NeedsADL, R.isOverloadedResult(), 2587 R.begin(), R.end()); 2588 2589 return Owned(ULE); 2590 } 2591 2592 /// \brief Complete semantic analysis for a reference to the given declaration. 2593 ExprResult Sema::BuildDeclarationNameExpr( 2594 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2595 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2596 assert(D && "Cannot refer to a NULL declaration"); 2597 assert(!isa<FunctionTemplateDecl>(D) && 2598 "Cannot refer unambiguously to a function template"); 2599 2600 SourceLocation Loc = NameInfo.getLoc(); 2601 if (CheckDeclInExpr(*this, Loc, D)) 2602 return ExprError(); 2603 2604 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2605 // Specifically diagnose references to class templates that are missing 2606 // a template argument list. 2607 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2608 << Template << SS.getRange(); 2609 Diag(Template->getLocation(), diag::note_template_decl_here); 2610 return ExprError(); 2611 } 2612 2613 // Make sure that we're referring to a value. 2614 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2615 if (!VD) { 2616 Diag(Loc, diag::err_ref_non_value) 2617 << D << SS.getRange(); 2618 Diag(D->getLocation(), diag::note_declared_at); 2619 return ExprError(); 2620 } 2621 2622 // Check whether this declaration can be used. Note that we suppress 2623 // this check when we're going to perform argument-dependent lookup 2624 // on this function name, because this might not be the function 2625 // that overload resolution actually selects. 2626 if (DiagnoseUseOfDecl(VD, Loc)) 2627 return ExprError(); 2628 2629 // Only create DeclRefExpr's for valid Decl's. 2630 if (VD->isInvalidDecl()) 2631 return ExprError(); 2632 2633 // Handle members of anonymous structs and unions. If we got here, 2634 // and the reference is to a class member indirect field, then this 2635 // must be the subject of a pointer-to-member expression. 2636 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2637 if (!indirectField->isCXXClassMember()) 2638 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2639 indirectField); 2640 2641 { 2642 QualType type = VD->getType(); 2643 ExprValueKind valueKind = VK_RValue; 2644 2645 switch (D->getKind()) { 2646 // Ignore all the non-ValueDecl kinds. 2647 #define ABSTRACT_DECL(kind) 2648 #define VALUE(type, base) 2649 #define DECL(type, base) \ 2650 case Decl::type: 2651 #include "clang/AST/DeclNodes.inc" 2652 llvm_unreachable("invalid value decl kind"); 2653 2654 // These shouldn't make it here. 2655 case Decl::ObjCAtDefsField: 2656 case Decl::ObjCIvar: 2657 llvm_unreachable("forming non-member reference to ivar?"); 2658 2659 // Enum constants are always r-values and never references. 2660 // Unresolved using declarations are dependent. 2661 case Decl::EnumConstant: 2662 case Decl::UnresolvedUsingValue: 2663 valueKind = VK_RValue; 2664 break; 2665 2666 // Fields and indirect fields that got here must be for 2667 // pointer-to-member expressions; we just call them l-values for 2668 // internal consistency, because this subexpression doesn't really 2669 // exist in the high-level semantics. 2670 case Decl::Field: 2671 case Decl::IndirectField: 2672 assert(getLangOpts().CPlusPlus && 2673 "building reference to field in C?"); 2674 2675 // These can't have reference type in well-formed programs, but 2676 // for internal consistency we do this anyway. 2677 type = type.getNonReferenceType(); 2678 valueKind = VK_LValue; 2679 break; 2680 2681 // Non-type template parameters are either l-values or r-values 2682 // depending on the type. 2683 case Decl::NonTypeTemplateParm: { 2684 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2685 type = reftype->getPointeeType(); 2686 valueKind = VK_LValue; // even if the parameter is an r-value reference 2687 break; 2688 } 2689 2690 // For non-references, we need to strip qualifiers just in case 2691 // the template parameter was declared as 'const int' or whatever. 2692 valueKind = VK_RValue; 2693 type = type.getUnqualifiedType(); 2694 break; 2695 } 2696 2697 case Decl::Var: 2698 case Decl::VarTemplateSpecialization: 2699 case Decl::VarTemplatePartialSpecialization: 2700 // In C, "extern void blah;" is valid and is an r-value. 2701 if (!getLangOpts().CPlusPlus && 2702 !type.hasQualifiers() && 2703 type->isVoidType()) { 2704 valueKind = VK_RValue; 2705 break; 2706 } 2707 // fallthrough 2708 2709 case Decl::ImplicitParam: 2710 case Decl::ParmVar: { 2711 // These are always l-values. 2712 valueKind = VK_LValue; 2713 type = type.getNonReferenceType(); 2714 2715 // FIXME: Does the addition of const really only apply in 2716 // potentially-evaluated contexts? Since the variable isn't actually 2717 // captured in an unevaluated context, it seems that the answer is no. 2718 if (!isUnevaluatedContext()) { 2719 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2720 if (!CapturedType.isNull()) 2721 type = CapturedType; 2722 } 2723 2724 break; 2725 } 2726 2727 case Decl::Function: { 2728 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2729 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2730 type = Context.BuiltinFnTy; 2731 valueKind = VK_RValue; 2732 break; 2733 } 2734 } 2735 2736 const FunctionType *fty = type->castAs<FunctionType>(); 2737 2738 // If we're referring to a function with an __unknown_anytype 2739 // result type, make the entire expression __unknown_anytype. 2740 if (fty->getReturnType() == Context.UnknownAnyTy) { 2741 type = Context.UnknownAnyTy; 2742 valueKind = VK_RValue; 2743 break; 2744 } 2745 2746 // Functions are l-values in C++. 2747 if (getLangOpts().CPlusPlus) { 2748 valueKind = VK_LValue; 2749 break; 2750 } 2751 2752 // C99 DR 316 says that, if a function type comes from a 2753 // function definition (without a prototype), that type is only 2754 // used for checking compatibility. Therefore, when referencing 2755 // the function, we pretend that we don't have the full function 2756 // type. 2757 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2758 isa<FunctionProtoType>(fty)) 2759 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2760 fty->getExtInfo()); 2761 2762 // Functions are r-values in C. 2763 valueKind = VK_RValue; 2764 break; 2765 } 2766 2767 case Decl::MSProperty: 2768 valueKind = VK_LValue; 2769 break; 2770 2771 case Decl::CXXMethod: 2772 // If we're referring to a method with an __unknown_anytype 2773 // result type, make the entire expression __unknown_anytype. 2774 // This should only be possible with a type written directly. 2775 if (const FunctionProtoType *proto 2776 = dyn_cast<FunctionProtoType>(VD->getType())) 2777 if (proto->getReturnType() == Context.UnknownAnyTy) { 2778 type = Context.UnknownAnyTy; 2779 valueKind = VK_RValue; 2780 break; 2781 } 2782 2783 // C++ methods are l-values if static, r-values if non-static. 2784 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2785 valueKind = VK_LValue; 2786 break; 2787 } 2788 // fallthrough 2789 2790 case Decl::CXXConversion: 2791 case Decl::CXXDestructor: 2792 case Decl::CXXConstructor: 2793 valueKind = VK_RValue; 2794 break; 2795 } 2796 2797 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2798 TemplateArgs); 2799 } 2800 } 2801 2802 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2803 PredefinedExpr::IdentType IT) { 2804 // Pick the current block, lambda, captured statement or function. 2805 Decl *currentDecl = 0; 2806 if (const BlockScopeInfo *BSI = getCurBlock()) 2807 currentDecl = BSI->TheDecl; 2808 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2809 currentDecl = LSI->CallOperator; 2810 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2811 currentDecl = CSI->TheCapturedDecl; 2812 else 2813 currentDecl = getCurFunctionOrMethodDecl(); 2814 2815 if (!currentDecl) { 2816 Diag(Loc, diag::ext_predef_outside_function); 2817 currentDecl = Context.getTranslationUnitDecl(); 2818 } 2819 2820 QualType ResTy; 2821 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2822 ResTy = Context.DependentTy; 2823 else { 2824 // Pre-defined identifiers are of type char[x], where x is the length of 2825 // the string. 2826 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2827 2828 llvm::APInt LengthI(32, Length + 1); 2829 if (IT == PredefinedExpr::LFunction) 2830 ResTy = Context.WideCharTy.withConst(); 2831 else 2832 ResTy = Context.CharTy.withConst(); 2833 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2834 } 2835 2836 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2837 } 2838 2839 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2840 PredefinedExpr::IdentType IT; 2841 2842 switch (Kind) { 2843 default: llvm_unreachable("Unknown simple primary expr!"); 2844 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2845 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2846 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 2847 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2848 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2849 } 2850 2851 return BuildPredefinedExpr(Loc, IT); 2852 } 2853 2854 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2855 SmallString<16> CharBuffer; 2856 bool Invalid = false; 2857 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2858 if (Invalid) 2859 return ExprError(); 2860 2861 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2862 PP, Tok.getKind()); 2863 if (Literal.hadError()) 2864 return ExprError(); 2865 2866 QualType Ty; 2867 if (Literal.isWide()) 2868 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2869 else if (Literal.isUTF16()) 2870 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2871 else if (Literal.isUTF32()) 2872 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2873 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2874 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2875 else 2876 Ty = Context.CharTy; // 'x' -> char in C++ 2877 2878 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2879 if (Literal.isWide()) 2880 Kind = CharacterLiteral::Wide; 2881 else if (Literal.isUTF16()) 2882 Kind = CharacterLiteral::UTF16; 2883 else if (Literal.isUTF32()) 2884 Kind = CharacterLiteral::UTF32; 2885 2886 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2887 Tok.getLocation()); 2888 2889 if (Literal.getUDSuffix().empty()) 2890 return Owned(Lit); 2891 2892 // We're building a user-defined literal. 2893 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2894 SourceLocation UDSuffixLoc = 2895 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2896 2897 // Make sure we're allowed user-defined literals here. 2898 if (!UDLScope) 2899 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2900 2901 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2902 // operator "" X (ch) 2903 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2904 Lit, Tok.getLocation()); 2905 } 2906 2907 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2908 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2909 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2910 Context.IntTy, Loc)); 2911 } 2912 2913 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2914 QualType Ty, SourceLocation Loc) { 2915 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2916 2917 using llvm::APFloat; 2918 APFloat Val(Format); 2919 2920 APFloat::opStatus result = Literal.GetFloatValue(Val); 2921 2922 // Overflow is always an error, but underflow is only an error if 2923 // we underflowed to zero (APFloat reports denormals as underflow). 2924 if ((result & APFloat::opOverflow) || 2925 ((result & APFloat::opUnderflow) && Val.isZero())) { 2926 unsigned diagnostic; 2927 SmallString<20> buffer; 2928 if (result & APFloat::opOverflow) { 2929 diagnostic = diag::warn_float_overflow; 2930 APFloat::getLargest(Format).toString(buffer); 2931 } else { 2932 diagnostic = diag::warn_float_underflow; 2933 APFloat::getSmallest(Format).toString(buffer); 2934 } 2935 2936 S.Diag(Loc, diagnostic) 2937 << Ty 2938 << StringRef(buffer.data(), buffer.size()); 2939 } 2940 2941 bool isExact = (result == APFloat::opOK); 2942 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2943 } 2944 2945 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2946 // Fast path for a single digit (which is quite common). A single digit 2947 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2948 if (Tok.getLength() == 1) { 2949 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2950 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2951 } 2952 2953 SmallString<128> SpellingBuffer; 2954 // NumericLiteralParser wants to overread by one character. Add padding to 2955 // the buffer in case the token is copied to the buffer. If getSpelling() 2956 // returns a StringRef to the memory buffer, it should have a null char at 2957 // the EOF, so it is also safe. 2958 SpellingBuffer.resize(Tok.getLength() + 1); 2959 2960 // Get the spelling of the token, which eliminates trigraphs, etc. 2961 bool Invalid = false; 2962 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2963 if (Invalid) 2964 return ExprError(); 2965 2966 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2967 if (Literal.hadError) 2968 return ExprError(); 2969 2970 if (Literal.hasUDSuffix()) { 2971 // We're building a user-defined literal. 2972 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2973 SourceLocation UDSuffixLoc = 2974 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2975 2976 // Make sure we're allowed user-defined literals here. 2977 if (!UDLScope) 2978 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2979 2980 QualType CookedTy; 2981 if (Literal.isFloatingLiteral()) { 2982 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2983 // long double, the literal is treated as a call of the form 2984 // operator "" X (f L) 2985 CookedTy = Context.LongDoubleTy; 2986 } else { 2987 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2988 // unsigned long long, the literal is treated as a call of the form 2989 // operator "" X (n ULL) 2990 CookedTy = Context.UnsignedLongLongTy; 2991 } 2992 2993 DeclarationName OpName = 2994 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2995 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2996 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2997 2998 SourceLocation TokLoc = Tok.getLocation(); 2999 3000 // Perform literal operator lookup to determine if we're building a raw 3001 // literal or a cooked one. 3002 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3003 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3004 /*AllowRaw*/true, /*AllowTemplate*/true, 3005 /*AllowStringTemplate*/false)) { 3006 case LOLR_Error: 3007 return ExprError(); 3008 3009 case LOLR_Cooked: { 3010 Expr *Lit; 3011 if (Literal.isFloatingLiteral()) { 3012 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3013 } else { 3014 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3015 if (Literal.GetIntegerValue(ResultVal)) 3016 Diag(Tok.getLocation(), diag::err_integer_too_large); 3017 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3018 Tok.getLocation()); 3019 } 3020 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3021 } 3022 3023 case LOLR_Raw: { 3024 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3025 // literal is treated as a call of the form 3026 // operator "" X ("n") 3027 unsigned Length = Literal.getUDSuffixOffset(); 3028 QualType StrTy = Context.getConstantArrayType( 3029 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3030 ArrayType::Normal, 0); 3031 Expr *Lit = StringLiteral::Create( 3032 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3033 /*Pascal*/false, StrTy, &TokLoc, 1); 3034 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3035 } 3036 3037 case LOLR_Template: { 3038 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3039 // template), L is treated as a call fo the form 3040 // operator "" X <'c1', 'c2', ... 'ck'>() 3041 // where n is the source character sequence c1 c2 ... ck. 3042 TemplateArgumentListInfo ExplicitArgs; 3043 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3044 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3045 llvm::APSInt Value(CharBits, CharIsUnsigned); 3046 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3047 Value = TokSpelling[I]; 3048 TemplateArgument Arg(Context, Value, Context.CharTy); 3049 TemplateArgumentLocInfo ArgInfo; 3050 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3051 } 3052 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3053 &ExplicitArgs); 3054 } 3055 case LOLR_StringTemplate: 3056 llvm_unreachable("unexpected literal operator lookup result"); 3057 } 3058 } 3059 3060 Expr *Res; 3061 3062 if (Literal.isFloatingLiteral()) { 3063 QualType Ty; 3064 if (Literal.isFloat) 3065 Ty = Context.FloatTy; 3066 else if (!Literal.isLong) 3067 Ty = Context.DoubleTy; 3068 else 3069 Ty = Context.LongDoubleTy; 3070 3071 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3072 3073 if (Ty == Context.DoubleTy) { 3074 if (getLangOpts().SinglePrecisionConstants) { 3075 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3076 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3077 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3078 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3079 } 3080 } 3081 } else if (!Literal.isIntegerLiteral()) { 3082 return ExprError(); 3083 } else { 3084 QualType Ty; 3085 3086 // 'long long' is a C99 or C++11 feature. 3087 if (!getLangOpts().C99 && Literal.isLongLong) { 3088 if (getLangOpts().CPlusPlus) 3089 Diag(Tok.getLocation(), 3090 getLangOpts().CPlusPlus11 ? 3091 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3092 else 3093 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3094 } 3095 3096 // Get the value in the widest-possible width. 3097 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3098 // The microsoft literal suffix extensions support 128-bit literals, which 3099 // may be wider than [u]intmax_t. 3100 // FIXME: Actually, they don't. We seem to have accidentally invented the 3101 // i128 suffix. 3102 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 3103 PP.getTargetInfo().hasInt128Type()) 3104 MaxWidth = 128; 3105 llvm::APInt ResultVal(MaxWidth, 0); 3106 3107 if (Literal.GetIntegerValue(ResultVal)) { 3108 // If this value didn't fit into uintmax_t, error and force to ull. 3109 Diag(Tok.getLocation(), diag::err_integer_too_large); 3110 Ty = Context.UnsignedLongLongTy; 3111 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3112 "long long is not intmax_t?"); 3113 } else { 3114 // If this value fits into a ULL, try to figure out what else it fits into 3115 // according to the rules of C99 6.4.4.1p5. 3116 3117 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3118 // be an unsigned int. 3119 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3120 3121 // Check from smallest to largest, picking the smallest type we can. 3122 unsigned Width = 0; 3123 if (!Literal.isLong && !Literal.isLongLong) { 3124 // Are int/unsigned possibilities? 3125 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3126 3127 // Does it fit in a unsigned int? 3128 if (ResultVal.isIntN(IntSize)) { 3129 // Does it fit in a signed int? 3130 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3131 Ty = Context.IntTy; 3132 else if (AllowUnsigned) 3133 Ty = Context.UnsignedIntTy; 3134 Width = IntSize; 3135 } 3136 } 3137 3138 // Are long/unsigned long possibilities? 3139 if (Ty.isNull() && !Literal.isLongLong) { 3140 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3141 3142 // Does it fit in a unsigned long? 3143 if (ResultVal.isIntN(LongSize)) { 3144 // Does it fit in a signed long? 3145 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3146 Ty = Context.LongTy; 3147 else if (AllowUnsigned) 3148 Ty = Context.UnsignedLongTy; 3149 Width = LongSize; 3150 } 3151 } 3152 3153 // Check long long if needed. 3154 if (Ty.isNull()) { 3155 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3156 3157 // Does it fit in a unsigned long long? 3158 if (ResultVal.isIntN(LongLongSize)) { 3159 // Does it fit in a signed long long? 3160 // To be compatible with MSVC, hex integer literals ending with the 3161 // LL or i64 suffix are always signed in Microsoft mode. 3162 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3163 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3164 Ty = Context.LongLongTy; 3165 else if (AllowUnsigned) 3166 Ty = Context.UnsignedLongLongTy; 3167 Width = LongLongSize; 3168 } 3169 } 3170 3171 // If it doesn't fit in unsigned long long, and we're using Microsoft 3172 // extensions, then its a 128-bit integer literal. 3173 if (Ty.isNull() && Literal.isMicrosoftInteger && 3174 PP.getTargetInfo().hasInt128Type()) { 3175 if (Literal.isUnsigned) 3176 Ty = Context.UnsignedInt128Ty; 3177 else 3178 Ty = Context.Int128Ty; 3179 Width = 128; 3180 } 3181 3182 // If we still couldn't decide a type, we probably have something that 3183 // does not fit in a signed long long, but has no U suffix. 3184 if (Ty.isNull()) { 3185 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3186 Ty = Context.UnsignedLongLongTy; 3187 Width = Context.getTargetInfo().getLongLongWidth(); 3188 } 3189 3190 if (ResultVal.getBitWidth() != Width) 3191 ResultVal = ResultVal.trunc(Width); 3192 } 3193 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3194 } 3195 3196 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3197 if (Literal.isImaginary) 3198 Res = new (Context) ImaginaryLiteral(Res, 3199 Context.getComplexType(Res->getType())); 3200 3201 return Owned(Res); 3202 } 3203 3204 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3205 assert((E != 0) && "ActOnParenExpr() missing expr"); 3206 return Owned(new (Context) ParenExpr(L, R, E)); 3207 } 3208 3209 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3210 SourceLocation Loc, 3211 SourceRange ArgRange) { 3212 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3213 // scalar or vector data type argument..." 3214 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3215 // type (C99 6.2.5p18) or void. 3216 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3217 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3218 << T << ArgRange; 3219 return true; 3220 } 3221 3222 assert((T->isVoidType() || !T->isIncompleteType()) && 3223 "Scalar types should always be complete"); 3224 return false; 3225 } 3226 3227 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3228 SourceLocation Loc, 3229 SourceRange ArgRange, 3230 UnaryExprOrTypeTrait TraitKind) { 3231 // Invalid types must be hard errors for SFINAE in C++. 3232 if (S.LangOpts.CPlusPlus) 3233 return true; 3234 3235 // C99 6.5.3.4p1: 3236 if (T->isFunctionType() && 3237 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3238 // sizeof(function)/alignof(function) is allowed as an extension. 3239 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3240 << TraitKind << ArgRange; 3241 return false; 3242 } 3243 3244 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3245 // this is an error (OpenCL v1.1 s6.3.k) 3246 if (T->isVoidType()) { 3247 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3248 : diag::ext_sizeof_alignof_void_type; 3249 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3250 return false; 3251 } 3252 3253 return true; 3254 } 3255 3256 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3257 SourceLocation Loc, 3258 SourceRange ArgRange, 3259 UnaryExprOrTypeTrait TraitKind) { 3260 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3261 // runtime doesn't allow it. 3262 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3263 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3264 << T << (TraitKind == UETT_SizeOf) 3265 << ArgRange; 3266 return true; 3267 } 3268 3269 return false; 3270 } 3271 3272 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3273 /// pointer type is equal to T) and emit a warning if it is. 3274 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3275 Expr *E) { 3276 // Don't warn if the operation changed the type. 3277 if (T != E->getType()) 3278 return; 3279 3280 // Now look for array decays. 3281 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3282 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3283 return; 3284 3285 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3286 << ICE->getType() 3287 << ICE->getSubExpr()->getType(); 3288 } 3289 3290 /// \brief Check the constraints on expression operands to unary type expression 3291 /// and type traits. 3292 /// 3293 /// Completes any types necessary and validates the constraints on the operand 3294 /// expression. The logic mostly mirrors the type-based overload, but may modify 3295 /// the expression as it completes the type for that expression through template 3296 /// instantiation, etc. 3297 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3298 UnaryExprOrTypeTrait ExprKind) { 3299 QualType ExprTy = E->getType(); 3300 assert(!ExprTy->isReferenceType()); 3301 3302 if (ExprKind == UETT_VecStep) 3303 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3304 E->getSourceRange()); 3305 3306 // Whitelist some types as extensions 3307 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3308 E->getSourceRange(), ExprKind)) 3309 return false; 3310 3311 if (RequireCompleteExprType(E, 3312 diag::err_sizeof_alignof_incomplete_type, 3313 ExprKind, E->getSourceRange())) 3314 return true; 3315 3316 // Completing the expression's type may have changed it. 3317 ExprTy = E->getType(); 3318 assert(!ExprTy->isReferenceType()); 3319 3320 if (ExprTy->isFunctionType()) { 3321 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3322 << ExprKind << E->getSourceRange(); 3323 return true; 3324 } 3325 3326 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3327 E->getSourceRange(), ExprKind)) 3328 return true; 3329 3330 if (ExprKind == UETT_SizeOf) { 3331 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3332 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3333 QualType OType = PVD->getOriginalType(); 3334 QualType Type = PVD->getType(); 3335 if (Type->isPointerType() && OType->isArrayType()) { 3336 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3337 << Type << OType; 3338 Diag(PVD->getLocation(), diag::note_declared_at); 3339 } 3340 } 3341 } 3342 3343 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3344 // decays into a pointer and returns an unintended result. This is most 3345 // likely a typo for "sizeof(array) op x". 3346 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3347 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3348 BO->getLHS()); 3349 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3350 BO->getRHS()); 3351 } 3352 } 3353 3354 return false; 3355 } 3356 3357 /// \brief Check the constraints on operands to unary expression and type 3358 /// traits. 3359 /// 3360 /// This will complete any types necessary, and validate the various constraints 3361 /// on those operands. 3362 /// 3363 /// The UsualUnaryConversions() function is *not* called by this routine. 3364 /// C99 6.3.2.1p[2-4] all state: 3365 /// Except when it is the operand of the sizeof operator ... 3366 /// 3367 /// C++ [expr.sizeof]p4 3368 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3369 /// standard conversions are not applied to the operand of sizeof. 3370 /// 3371 /// This policy is followed for all of the unary trait expressions. 3372 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3373 SourceLocation OpLoc, 3374 SourceRange ExprRange, 3375 UnaryExprOrTypeTrait ExprKind) { 3376 if (ExprType->isDependentType()) 3377 return false; 3378 3379 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3380 // the result is the size of the referenced type." 3381 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3382 // result shall be the alignment of the referenced type." 3383 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3384 ExprType = Ref->getPointeeType(); 3385 3386 if (ExprKind == UETT_VecStep) 3387 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3388 3389 // Whitelist some types as extensions 3390 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3391 ExprKind)) 3392 return false; 3393 3394 if (RequireCompleteType(OpLoc, ExprType, 3395 diag::err_sizeof_alignof_incomplete_type, 3396 ExprKind, ExprRange)) 3397 return true; 3398 3399 if (ExprType->isFunctionType()) { 3400 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3401 << ExprKind << ExprRange; 3402 return true; 3403 } 3404 3405 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3406 ExprKind)) 3407 return true; 3408 3409 return false; 3410 } 3411 3412 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3413 E = E->IgnoreParens(); 3414 3415 // Cannot know anything else if the expression is dependent. 3416 if (E->isTypeDependent()) 3417 return false; 3418 3419 if (E->getObjectKind() == OK_BitField) { 3420 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3421 << 1 << E->getSourceRange(); 3422 return true; 3423 } 3424 3425 ValueDecl *D = 0; 3426 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3427 D = DRE->getDecl(); 3428 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3429 D = ME->getMemberDecl(); 3430 } 3431 3432 // If it's a field, require the containing struct to have a 3433 // complete definition so that we can compute the layout. 3434 // 3435 // This requires a very particular set of circumstances. For a 3436 // field to be contained within an incomplete type, we must in the 3437 // process of parsing that type. To have an expression refer to a 3438 // field, it must be an id-expression or a member-expression, but 3439 // the latter are always ill-formed when the base type is 3440 // incomplete, including only being partially complete. An 3441 // id-expression can never refer to a field in C because fields 3442 // are not in the ordinary namespace. In C++, an id-expression 3443 // can implicitly be a member access, but only if there's an 3444 // implicit 'this' value, and all such contexts are subject to 3445 // delayed parsing --- except for trailing return types in C++11. 3446 // And if an id-expression referring to a field occurs in a 3447 // context that lacks a 'this' value, it's ill-formed --- except, 3448 // again, in C++11, where such references are allowed in an 3449 // unevaluated context. So C++11 introduces some new complexity. 3450 // 3451 // For the record, since __alignof__ on expressions is a GCC 3452 // extension, GCC seems to permit this but always gives the 3453 // nonsensical answer 0. 3454 // 3455 // We don't really need the layout here --- we could instead just 3456 // directly check for all the appropriate alignment-lowing 3457 // attributes --- but that would require duplicating a lot of 3458 // logic that just isn't worth duplicating for such a marginal 3459 // use-case. 3460 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3461 // Fast path this check, since we at least know the record has a 3462 // definition if we can find a member of it. 3463 if (!FD->getParent()->isCompleteDefinition()) { 3464 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3465 << E->getSourceRange(); 3466 return true; 3467 } 3468 3469 // Otherwise, if it's a field, and the field doesn't have 3470 // reference type, then it must have a complete type (or be a 3471 // flexible array member, which we explicitly want to 3472 // white-list anyway), which makes the following checks trivial. 3473 if (!FD->getType()->isReferenceType()) 3474 return false; 3475 } 3476 3477 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3478 } 3479 3480 bool Sema::CheckVecStepExpr(Expr *E) { 3481 E = E->IgnoreParens(); 3482 3483 // Cannot know anything else if the expression is dependent. 3484 if (E->isTypeDependent()) 3485 return false; 3486 3487 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3488 } 3489 3490 /// \brief Build a sizeof or alignof expression given a type operand. 3491 ExprResult 3492 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3493 SourceLocation OpLoc, 3494 UnaryExprOrTypeTrait ExprKind, 3495 SourceRange R) { 3496 if (!TInfo) 3497 return ExprError(); 3498 3499 QualType T = TInfo->getType(); 3500 3501 if (!T->isDependentType() && 3502 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3503 return ExprError(); 3504 3505 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3506 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3507 Context.getSizeType(), 3508 OpLoc, R.getEnd())); 3509 } 3510 3511 /// \brief Build a sizeof or alignof expression given an expression 3512 /// operand. 3513 ExprResult 3514 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3515 UnaryExprOrTypeTrait ExprKind) { 3516 ExprResult PE = CheckPlaceholderExpr(E); 3517 if (PE.isInvalid()) 3518 return ExprError(); 3519 3520 E = PE.get(); 3521 3522 // Verify that the operand is valid. 3523 bool isInvalid = false; 3524 if (E->isTypeDependent()) { 3525 // Delay type-checking for type-dependent expressions. 3526 } else if (ExprKind == UETT_AlignOf) { 3527 isInvalid = CheckAlignOfExpr(*this, E); 3528 } else if (ExprKind == UETT_VecStep) { 3529 isInvalid = CheckVecStepExpr(E); 3530 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3531 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3532 isInvalid = true; 3533 } else { 3534 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3535 } 3536 3537 if (isInvalid) 3538 return ExprError(); 3539 3540 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3541 PE = TransformToPotentiallyEvaluated(E); 3542 if (PE.isInvalid()) return ExprError(); 3543 E = PE.take(); 3544 } 3545 3546 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3547 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3548 ExprKind, E, Context.getSizeType(), OpLoc, 3549 E->getSourceRange().getEnd())); 3550 } 3551 3552 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3553 /// expr and the same for @c alignof and @c __alignof 3554 /// Note that the ArgRange is invalid if isType is false. 3555 ExprResult 3556 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3557 UnaryExprOrTypeTrait ExprKind, bool IsType, 3558 void *TyOrEx, const SourceRange &ArgRange) { 3559 // If error parsing type, ignore. 3560 if (TyOrEx == 0) return ExprError(); 3561 3562 if (IsType) { 3563 TypeSourceInfo *TInfo; 3564 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3565 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3566 } 3567 3568 Expr *ArgEx = (Expr *)TyOrEx; 3569 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3570 return Result; 3571 } 3572 3573 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3574 bool IsReal) { 3575 if (V.get()->isTypeDependent()) 3576 return S.Context.DependentTy; 3577 3578 // _Real and _Imag are only l-values for normal l-values. 3579 if (V.get()->getObjectKind() != OK_Ordinary) { 3580 V = S.DefaultLvalueConversion(V.take()); 3581 if (V.isInvalid()) 3582 return QualType(); 3583 } 3584 3585 // These operators return the element type of a complex type. 3586 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3587 return CT->getElementType(); 3588 3589 // Otherwise they pass through real integer and floating point types here. 3590 if (V.get()->getType()->isArithmeticType()) 3591 return V.get()->getType(); 3592 3593 // Test for placeholders. 3594 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3595 if (PR.isInvalid()) return QualType(); 3596 if (PR.get() != V.get()) { 3597 V = PR; 3598 return CheckRealImagOperand(S, V, Loc, IsReal); 3599 } 3600 3601 // Reject anything else. 3602 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3603 << (IsReal ? "__real" : "__imag"); 3604 return QualType(); 3605 } 3606 3607 3608 3609 ExprResult 3610 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3611 tok::TokenKind Kind, Expr *Input) { 3612 UnaryOperatorKind Opc; 3613 switch (Kind) { 3614 default: llvm_unreachable("Unknown unary op!"); 3615 case tok::plusplus: Opc = UO_PostInc; break; 3616 case tok::minusminus: Opc = UO_PostDec; break; 3617 } 3618 3619 // Since this might is a postfix expression, get rid of ParenListExprs. 3620 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3621 if (Result.isInvalid()) return ExprError(); 3622 Input = Result.take(); 3623 3624 return BuildUnaryOp(S, OpLoc, Opc, Input); 3625 } 3626 3627 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3628 /// 3629 /// \return true on error 3630 static bool checkArithmeticOnObjCPointer(Sema &S, 3631 SourceLocation opLoc, 3632 Expr *op) { 3633 assert(op->getType()->isObjCObjectPointerType()); 3634 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3635 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3636 return false; 3637 3638 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3639 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3640 << op->getSourceRange(); 3641 return true; 3642 } 3643 3644 ExprResult 3645 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3646 Expr *idx, SourceLocation rbLoc) { 3647 // Since this might be a postfix expression, get rid of ParenListExprs. 3648 if (isa<ParenListExpr>(base)) { 3649 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3650 if (result.isInvalid()) return ExprError(); 3651 base = result.take(); 3652 } 3653 3654 // Handle any non-overload placeholder types in the base and index 3655 // expressions. We can't handle overloads here because the other 3656 // operand might be an overloadable type, in which case the overload 3657 // resolution for the operator overload should get the first crack 3658 // at the overload. 3659 if (base->getType()->isNonOverloadPlaceholderType()) { 3660 ExprResult result = CheckPlaceholderExpr(base); 3661 if (result.isInvalid()) return ExprError(); 3662 base = result.take(); 3663 } 3664 if (idx->getType()->isNonOverloadPlaceholderType()) { 3665 ExprResult result = CheckPlaceholderExpr(idx); 3666 if (result.isInvalid()) return ExprError(); 3667 idx = result.take(); 3668 } 3669 3670 // Build an unanalyzed expression if either operand is type-dependent. 3671 if (getLangOpts().CPlusPlus && 3672 (base->isTypeDependent() || idx->isTypeDependent())) { 3673 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3674 Context.DependentTy, 3675 VK_LValue, OK_Ordinary, 3676 rbLoc)); 3677 } 3678 3679 // Use C++ overloaded-operator rules if either operand has record 3680 // type. The spec says to do this if either type is *overloadable*, 3681 // but enum types can't declare subscript operators or conversion 3682 // operators, so there's nothing interesting for overload resolution 3683 // to do if there aren't any record types involved. 3684 // 3685 // ObjC pointers have their own subscripting logic that is not tied 3686 // to overload resolution and so should not take this path. 3687 if (getLangOpts().CPlusPlus && 3688 (base->getType()->isRecordType() || 3689 (!base->getType()->isObjCObjectPointerType() && 3690 idx->getType()->isRecordType()))) { 3691 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3692 } 3693 3694 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3695 } 3696 3697 ExprResult 3698 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3699 Expr *Idx, SourceLocation RLoc) { 3700 Expr *LHSExp = Base; 3701 Expr *RHSExp = Idx; 3702 3703 // Perform default conversions. 3704 if (!LHSExp->getType()->getAs<VectorType>()) { 3705 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3706 if (Result.isInvalid()) 3707 return ExprError(); 3708 LHSExp = Result.take(); 3709 } 3710 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3711 if (Result.isInvalid()) 3712 return ExprError(); 3713 RHSExp = Result.take(); 3714 3715 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3716 ExprValueKind VK = VK_LValue; 3717 ExprObjectKind OK = OK_Ordinary; 3718 3719 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3720 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3721 // in the subscript position. As a result, we need to derive the array base 3722 // and index from the expression types. 3723 Expr *BaseExpr, *IndexExpr; 3724 QualType ResultType; 3725 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3726 BaseExpr = LHSExp; 3727 IndexExpr = RHSExp; 3728 ResultType = Context.DependentTy; 3729 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3730 BaseExpr = LHSExp; 3731 IndexExpr = RHSExp; 3732 ResultType = PTy->getPointeeType(); 3733 } else if (const ObjCObjectPointerType *PTy = 3734 LHSTy->getAs<ObjCObjectPointerType>()) { 3735 BaseExpr = LHSExp; 3736 IndexExpr = RHSExp; 3737 3738 // Use custom logic if this should be the pseudo-object subscript 3739 // expression. 3740 if (!LangOpts.isSubscriptPointerArithmetic()) 3741 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3742 3743 ResultType = PTy->getPointeeType(); 3744 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3745 // Handle the uncommon case of "123[Ptr]". 3746 BaseExpr = RHSExp; 3747 IndexExpr = LHSExp; 3748 ResultType = PTy->getPointeeType(); 3749 } else if (const ObjCObjectPointerType *PTy = 3750 RHSTy->getAs<ObjCObjectPointerType>()) { 3751 // Handle the uncommon case of "123[Ptr]". 3752 BaseExpr = RHSExp; 3753 IndexExpr = LHSExp; 3754 ResultType = PTy->getPointeeType(); 3755 if (!LangOpts.isSubscriptPointerArithmetic()) { 3756 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3757 << ResultType << BaseExpr->getSourceRange(); 3758 return ExprError(); 3759 } 3760 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3761 BaseExpr = LHSExp; // vectors: V[123] 3762 IndexExpr = RHSExp; 3763 VK = LHSExp->getValueKind(); 3764 if (VK != VK_RValue) 3765 OK = OK_VectorComponent; 3766 3767 // FIXME: need to deal with const... 3768 ResultType = VTy->getElementType(); 3769 } else if (LHSTy->isArrayType()) { 3770 // If we see an array that wasn't promoted by 3771 // DefaultFunctionArrayLvalueConversion, it must be an array that 3772 // wasn't promoted because of the C90 rule that doesn't 3773 // allow promoting non-lvalue arrays. Warn, then 3774 // force the promotion here. 3775 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3776 LHSExp->getSourceRange(); 3777 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3778 CK_ArrayToPointerDecay).take(); 3779 LHSTy = LHSExp->getType(); 3780 3781 BaseExpr = LHSExp; 3782 IndexExpr = RHSExp; 3783 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3784 } else if (RHSTy->isArrayType()) { 3785 // Same as previous, except for 123[f().a] case 3786 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3787 RHSExp->getSourceRange(); 3788 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3789 CK_ArrayToPointerDecay).take(); 3790 RHSTy = RHSExp->getType(); 3791 3792 BaseExpr = RHSExp; 3793 IndexExpr = LHSExp; 3794 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3795 } else { 3796 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3797 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3798 } 3799 // C99 6.5.2.1p1 3800 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3801 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3802 << IndexExpr->getSourceRange()); 3803 3804 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3805 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3806 && !IndexExpr->isTypeDependent()) 3807 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3808 3809 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3810 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3811 // type. Note that Functions are not objects, and that (in C99 parlance) 3812 // incomplete types are not object types. 3813 if (ResultType->isFunctionType()) { 3814 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3815 << ResultType << BaseExpr->getSourceRange(); 3816 return ExprError(); 3817 } 3818 3819 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3820 // GNU extension: subscripting on pointer to void 3821 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3822 << BaseExpr->getSourceRange(); 3823 3824 // C forbids expressions of unqualified void type from being l-values. 3825 // See IsCForbiddenLValueType. 3826 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3827 } else if (!ResultType->isDependentType() && 3828 RequireCompleteType(LLoc, ResultType, 3829 diag::err_subscript_incomplete_type, BaseExpr)) 3830 return ExprError(); 3831 3832 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3833 !ResultType.isCForbiddenLValueType()); 3834 3835 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3836 ResultType, VK, OK, RLoc)); 3837 } 3838 3839 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3840 FunctionDecl *FD, 3841 ParmVarDecl *Param) { 3842 if (Param->hasUnparsedDefaultArg()) { 3843 Diag(CallLoc, 3844 diag::err_use_of_default_argument_to_function_declared_later) << 3845 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3846 Diag(UnparsedDefaultArgLocs[Param], 3847 diag::note_default_argument_declared_here); 3848 return ExprError(); 3849 } 3850 3851 if (Param->hasUninstantiatedDefaultArg()) { 3852 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3853 3854 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3855 Param); 3856 3857 // Instantiate the expression. 3858 MultiLevelTemplateArgumentList MutiLevelArgList 3859 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3860 3861 InstantiatingTemplate Inst(*this, CallLoc, Param, 3862 MutiLevelArgList.getInnermost()); 3863 if (Inst.isInvalid()) 3864 return ExprError(); 3865 3866 ExprResult Result; 3867 { 3868 // C++ [dcl.fct.default]p5: 3869 // The names in the [default argument] expression are bound, and 3870 // the semantic constraints are checked, at the point where the 3871 // default argument expression appears. 3872 ContextRAII SavedContext(*this, FD); 3873 LocalInstantiationScope Local(*this); 3874 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3875 } 3876 if (Result.isInvalid()) 3877 return ExprError(); 3878 3879 // Check the expression as an initializer for the parameter. 3880 InitializedEntity Entity 3881 = InitializedEntity::InitializeParameter(Context, Param); 3882 InitializationKind Kind 3883 = InitializationKind::CreateCopy(Param->getLocation(), 3884 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3885 Expr *ResultE = Result.takeAs<Expr>(); 3886 3887 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3888 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3889 if (Result.isInvalid()) 3890 return ExprError(); 3891 3892 Expr *Arg = Result.takeAs<Expr>(); 3893 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3894 // Build the default argument expression. 3895 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3896 } 3897 3898 // If the default expression creates temporaries, we need to 3899 // push them to the current stack of expression temporaries so they'll 3900 // be properly destroyed. 3901 // FIXME: We should really be rebuilding the default argument with new 3902 // bound temporaries; see the comment in PR5810. 3903 // We don't need to do that with block decls, though, because 3904 // blocks in default argument expression can never capture anything. 3905 if (isa<ExprWithCleanups>(Param->getInit())) { 3906 // Set the "needs cleanups" bit regardless of whether there are 3907 // any explicit objects. 3908 ExprNeedsCleanups = true; 3909 3910 // Append all the objects to the cleanup list. Right now, this 3911 // should always be a no-op, because blocks in default argument 3912 // expressions should never be able to capture anything. 3913 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3914 "default argument expression has capturing blocks?"); 3915 } 3916 3917 // We already type-checked the argument, so we know it works. 3918 // Just mark all of the declarations in this potentially-evaluated expression 3919 // as being "referenced". 3920 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3921 /*SkipLocalVariables=*/true); 3922 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3923 } 3924 3925 3926 Sema::VariadicCallType 3927 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3928 Expr *Fn) { 3929 if (Proto && Proto->isVariadic()) { 3930 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3931 return VariadicConstructor; 3932 else if (Fn && Fn->getType()->isBlockPointerType()) 3933 return VariadicBlock; 3934 else if (FDecl) { 3935 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3936 if (Method->isInstance()) 3937 return VariadicMethod; 3938 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 3939 return VariadicMethod; 3940 return VariadicFunction; 3941 } 3942 return VariadicDoesNotApply; 3943 } 3944 3945 namespace { 3946 class FunctionCallCCC : public FunctionCallFilterCCC { 3947 public: 3948 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 3949 unsigned NumArgs, bool HasExplicitTemplateArgs) 3950 : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs), 3951 FunctionName(FuncName) {} 3952 3953 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 3954 if (!candidate.getCorrectionSpecifier() || 3955 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 3956 return false; 3957 } 3958 3959 return FunctionCallFilterCCC::ValidateCandidate(candidate); 3960 } 3961 3962 private: 3963 const IdentifierInfo *const FunctionName; 3964 }; 3965 } 3966 3967 static TypoCorrection TryTypoCorrectionForCall(Sema &S, 3968 DeclarationNameInfo FuncName, 3969 ArrayRef<Expr *> Args) { 3970 FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(), 3971 Args.size(), false); 3972 if (TypoCorrection Corrected = 3973 S.CorrectTypo(FuncName, Sema::LookupOrdinaryName, 3974 S.getScopeForContext(S.CurContext), NULL, CCC)) { 3975 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 3976 if (Corrected.isOverloaded()) { 3977 OverloadCandidateSet OCS(FuncName.getLoc()); 3978 OverloadCandidateSet::iterator Best; 3979 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 3980 CDEnd = Corrected.end(); 3981 CD != CDEnd; ++CD) { 3982 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 3983 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 3984 OCS); 3985 } 3986 switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) { 3987 case OR_Success: 3988 ND = Best->Function; 3989 Corrected.setCorrectionDecl(ND); 3990 break; 3991 default: 3992 break; 3993 } 3994 } 3995 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 3996 return Corrected; 3997 } 3998 } 3999 } 4000 return TypoCorrection(); 4001 } 4002 4003 /// ConvertArgumentsForCall - Converts the arguments specified in 4004 /// Args/NumArgs to the parameter types of the function FDecl with 4005 /// function prototype Proto. Call is the call expression itself, and 4006 /// Fn is the function expression. For a C++ member function, this 4007 /// routine does not attempt to convert the object argument. Returns 4008 /// true if the call is ill-formed. 4009 bool 4010 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4011 FunctionDecl *FDecl, 4012 const FunctionProtoType *Proto, 4013 ArrayRef<Expr *> Args, 4014 SourceLocation RParenLoc, 4015 bool IsExecConfig) { 4016 // Bail out early if calling a builtin with custom typechecking. 4017 // We don't need to do this in the 4018 if (FDecl) 4019 if (unsigned ID = FDecl->getBuiltinID()) 4020 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4021 return false; 4022 4023 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4024 // assignment, to the types of the corresponding parameter, ... 4025 unsigned NumParams = Proto->getNumParams(); 4026 bool Invalid = false; 4027 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4028 unsigned FnKind = Fn->getType()->isBlockPointerType() 4029 ? 1 /* block */ 4030 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4031 : 0 /* function */); 4032 4033 // If too few arguments are available (and we don't have default 4034 // arguments for the remaining parameters), don't make the call. 4035 if (Args.size() < NumParams) { 4036 if (Args.size() < MinArgs) { 4037 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4038 TypoCorrection TC; 4039 if (FDecl && (TC = TryTypoCorrectionForCall( 4040 *this, DeclarationNameInfo(FDecl->getDeclName(), 4041 (ME ? ME->getMemberLoc() 4042 : Fn->getLocStart())), 4043 Args))) { 4044 unsigned diag_id = 4045 MinArgs == NumParams && !Proto->isVariadic() 4046 ? diag::err_typecheck_call_too_few_args_suggest 4047 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4048 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4049 << static_cast<unsigned>(Args.size()) 4050 << TC.getCorrectionRange()); 4051 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4052 Diag(RParenLoc, 4053 MinArgs == NumParams && !Proto->isVariadic() 4054 ? diag::err_typecheck_call_too_few_args_one 4055 : diag::err_typecheck_call_too_few_args_at_least_one) 4056 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4057 else 4058 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4059 ? diag::err_typecheck_call_too_few_args 4060 : diag::err_typecheck_call_too_few_args_at_least) 4061 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4062 << Fn->getSourceRange(); 4063 4064 // Emit the location of the prototype. 4065 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4066 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4067 << FDecl; 4068 4069 return true; 4070 } 4071 Call->setNumArgs(Context, NumParams); 4072 } 4073 4074 // If too many are passed and not variadic, error on the extras and drop 4075 // them. 4076 if (Args.size() > NumParams) { 4077 if (!Proto->isVariadic()) { 4078 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4079 TypoCorrection TC; 4080 if (FDecl && (TC = TryTypoCorrectionForCall( 4081 *this, DeclarationNameInfo(FDecl->getDeclName(), 4082 (ME ? ME->getMemberLoc() 4083 : Fn->getLocStart())), 4084 Args))) { 4085 unsigned diag_id = 4086 MinArgs == NumParams && !Proto->isVariadic() 4087 ? diag::err_typecheck_call_too_many_args_suggest 4088 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4089 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4090 << static_cast<unsigned>(Args.size()) 4091 << TC.getCorrectionRange()); 4092 } else if (NumParams == 1 && FDecl && 4093 FDecl->getParamDecl(0)->getDeclName()) 4094 Diag(Args[NumParams]->getLocStart(), 4095 MinArgs == NumParams 4096 ? diag::err_typecheck_call_too_many_args_one 4097 : diag::err_typecheck_call_too_many_args_at_most_one) 4098 << FnKind << FDecl->getParamDecl(0) 4099 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4100 << SourceRange(Args[NumParams]->getLocStart(), 4101 Args.back()->getLocEnd()); 4102 else 4103 Diag(Args[NumParams]->getLocStart(), 4104 MinArgs == NumParams 4105 ? diag::err_typecheck_call_too_many_args 4106 : diag::err_typecheck_call_too_many_args_at_most) 4107 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4108 << Fn->getSourceRange() 4109 << SourceRange(Args[NumParams]->getLocStart(), 4110 Args.back()->getLocEnd()); 4111 4112 // Emit the location of the prototype. 4113 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4114 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4115 << FDecl; 4116 4117 // This deletes the extra arguments. 4118 Call->setNumArgs(Context, NumParams); 4119 return true; 4120 } 4121 } 4122 SmallVector<Expr *, 8> AllArgs; 4123 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4124 4125 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4126 Proto, 0, Args, AllArgs, CallType); 4127 if (Invalid) 4128 return true; 4129 unsigned TotalNumArgs = AllArgs.size(); 4130 for (unsigned i = 0; i < TotalNumArgs; ++i) 4131 Call->setArg(i, AllArgs[i]); 4132 4133 return false; 4134 } 4135 4136 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4137 const FunctionProtoType *Proto, 4138 unsigned FirstParam, ArrayRef<Expr *> Args, 4139 SmallVectorImpl<Expr *> &AllArgs, 4140 VariadicCallType CallType, bool AllowExplicit, 4141 bool IsListInitialization) { 4142 unsigned NumParams = Proto->getNumParams(); 4143 unsigned NumArgsToCheck = Args.size(); 4144 bool Invalid = false; 4145 if (Args.size() != NumParams) 4146 // Use default arguments for missing arguments 4147 NumArgsToCheck = NumParams; 4148 unsigned ArgIx = 0; 4149 // Continue to check argument types (even if we have too few/many args). 4150 for (unsigned i = FirstParam; i != NumArgsToCheck; i++) { 4151 QualType ProtoArgType = Proto->getParamType(i); 4152 4153 Expr *Arg; 4154 ParmVarDecl *Param; 4155 if (ArgIx < Args.size()) { 4156 Arg = Args[ArgIx++]; 4157 4158 if (RequireCompleteType(Arg->getLocStart(), 4159 ProtoArgType, 4160 diag::err_call_incomplete_argument, Arg)) 4161 return true; 4162 4163 // Pass the argument 4164 Param = 0; 4165 if (FDecl && i < FDecl->getNumParams()) 4166 Param = FDecl->getParamDecl(i); 4167 4168 // Strip the unbridged-cast placeholder expression off, if applicable. 4169 bool CFAudited = false; 4170 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4171 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4172 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4173 Arg = stripARCUnbridgedCast(Arg); 4174 else if (getLangOpts().ObjCAutoRefCount && 4175 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4176 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4177 CFAudited = true; 4178 4179 InitializedEntity Entity = 4180 Param ? InitializedEntity::InitializeParameter(Context, Param, 4181 ProtoArgType) 4182 : InitializedEntity::InitializeParameter( 4183 Context, ProtoArgType, Proto->isParamConsumed(i)); 4184 4185 // Remember that parameter belongs to a CF audited API. 4186 if (CFAudited) 4187 Entity.setParameterCFAudited(); 4188 4189 ExprResult ArgE = PerformCopyInitialization(Entity, 4190 SourceLocation(), 4191 Owned(Arg), 4192 IsListInitialization, 4193 AllowExplicit); 4194 if (ArgE.isInvalid()) 4195 return true; 4196 4197 Arg = ArgE.takeAs<Expr>(); 4198 } else { 4199 assert(FDecl && "can't use default arguments without a known callee"); 4200 Param = FDecl->getParamDecl(i); 4201 4202 ExprResult ArgExpr = 4203 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4204 if (ArgExpr.isInvalid()) 4205 return true; 4206 4207 Arg = ArgExpr.takeAs<Expr>(); 4208 } 4209 4210 // Check for array bounds violations for each argument to the call. This 4211 // check only triggers warnings when the argument isn't a more complex Expr 4212 // with its own checking, such as a BinaryOperator. 4213 CheckArrayAccess(Arg); 4214 4215 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4216 CheckStaticArrayArgument(CallLoc, Param, Arg); 4217 4218 AllArgs.push_back(Arg); 4219 } 4220 4221 // If this is a variadic call, handle args passed through "...". 4222 if (CallType != VariadicDoesNotApply) { 4223 // Assume that extern "C" functions with variadic arguments that 4224 // return __unknown_anytype aren't *really* variadic. 4225 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4226 FDecl->isExternC()) { 4227 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4228 QualType paramType; // ignored 4229 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4230 Invalid |= arg.isInvalid(); 4231 AllArgs.push_back(arg.take()); 4232 } 4233 4234 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4235 } else { 4236 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4237 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4238 FDecl); 4239 Invalid |= Arg.isInvalid(); 4240 AllArgs.push_back(Arg.take()); 4241 } 4242 } 4243 4244 // Check for array bounds violations. 4245 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4246 CheckArrayAccess(Args[i]); 4247 } 4248 return Invalid; 4249 } 4250 4251 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4252 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4253 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4254 TL = DTL.getOriginalLoc(); 4255 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4256 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4257 << ATL.getLocalSourceRange(); 4258 } 4259 4260 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4261 /// array parameter, check that it is non-null, and that if it is formed by 4262 /// array-to-pointer decay, the underlying array is sufficiently large. 4263 /// 4264 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4265 /// array type derivation, then for each call to the function, the value of the 4266 /// corresponding actual argument shall provide access to the first element of 4267 /// an array with at least as many elements as specified by the size expression. 4268 void 4269 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4270 ParmVarDecl *Param, 4271 const Expr *ArgExpr) { 4272 // Static array parameters are not supported in C++. 4273 if (!Param || getLangOpts().CPlusPlus) 4274 return; 4275 4276 QualType OrigTy = Param->getOriginalType(); 4277 4278 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4279 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4280 return; 4281 4282 if (ArgExpr->isNullPointerConstant(Context, 4283 Expr::NPC_NeverValueDependent)) { 4284 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4285 DiagnoseCalleeStaticArrayParam(*this, Param); 4286 return; 4287 } 4288 4289 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4290 if (!CAT) 4291 return; 4292 4293 const ConstantArrayType *ArgCAT = 4294 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4295 if (!ArgCAT) 4296 return; 4297 4298 if (ArgCAT->getSize().ult(CAT->getSize())) { 4299 Diag(CallLoc, diag::warn_static_array_too_small) 4300 << ArgExpr->getSourceRange() 4301 << (unsigned) ArgCAT->getSize().getZExtValue() 4302 << (unsigned) CAT->getSize().getZExtValue(); 4303 DiagnoseCalleeStaticArrayParam(*this, Param); 4304 } 4305 } 4306 4307 /// Given a function expression of unknown-any type, try to rebuild it 4308 /// to have a function type. 4309 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4310 4311 /// Is the given type a placeholder that we need to lower out 4312 /// immediately during argument processing? 4313 static bool isPlaceholderToRemoveAsArg(QualType type) { 4314 // Placeholders are never sugared. 4315 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4316 if (!placeholder) return false; 4317 4318 switch (placeholder->getKind()) { 4319 // Ignore all the non-placeholder types. 4320 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4321 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4322 #include "clang/AST/BuiltinTypes.def" 4323 return false; 4324 4325 // We cannot lower out overload sets; they might validly be resolved 4326 // by the call machinery. 4327 case BuiltinType::Overload: 4328 return false; 4329 4330 // Unbridged casts in ARC can be handled in some call positions and 4331 // should be left in place. 4332 case BuiltinType::ARCUnbridgedCast: 4333 return false; 4334 4335 // Pseudo-objects should be converted as soon as possible. 4336 case BuiltinType::PseudoObject: 4337 return true; 4338 4339 // The debugger mode could theoretically but currently does not try 4340 // to resolve unknown-typed arguments based on known parameter types. 4341 case BuiltinType::UnknownAny: 4342 return true; 4343 4344 // These are always invalid as call arguments and should be reported. 4345 case BuiltinType::BoundMember: 4346 case BuiltinType::BuiltinFn: 4347 return true; 4348 } 4349 llvm_unreachable("bad builtin type kind"); 4350 } 4351 4352 /// Check an argument list for placeholders that we won't try to 4353 /// handle later. 4354 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4355 // Apply this processing to all the arguments at once instead of 4356 // dying at the first failure. 4357 bool hasInvalid = false; 4358 for (size_t i = 0, e = args.size(); i != e; i++) { 4359 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4360 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4361 if (result.isInvalid()) hasInvalid = true; 4362 else args[i] = result.take(); 4363 } 4364 } 4365 return hasInvalid; 4366 } 4367 4368 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4369 /// This provides the location of the left/right parens and a list of comma 4370 /// locations. 4371 ExprResult 4372 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4373 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4374 Expr *ExecConfig, bool IsExecConfig) { 4375 // Since this might be a postfix expression, get rid of ParenListExprs. 4376 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4377 if (Result.isInvalid()) return ExprError(); 4378 Fn = Result.take(); 4379 4380 if (checkArgsForPlaceholders(*this, ArgExprs)) 4381 return ExprError(); 4382 4383 if (getLangOpts().CPlusPlus) { 4384 // If this is a pseudo-destructor expression, build the call immediately. 4385 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4386 if (!ArgExprs.empty()) { 4387 // Pseudo-destructor calls should not have any arguments. 4388 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4389 << FixItHint::CreateRemoval( 4390 SourceRange(ArgExprs[0]->getLocStart(), 4391 ArgExprs.back()->getLocEnd())); 4392 } 4393 4394 return Owned(new (Context) CallExpr(Context, Fn, None, 4395 Context.VoidTy, VK_RValue, 4396 RParenLoc)); 4397 } 4398 if (Fn->getType() == Context.PseudoObjectTy) { 4399 ExprResult result = CheckPlaceholderExpr(Fn); 4400 if (result.isInvalid()) return ExprError(); 4401 Fn = result.take(); 4402 } 4403 4404 // Determine whether this is a dependent call inside a C++ template, 4405 // in which case we won't do any semantic analysis now. 4406 // FIXME: Will need to cache the results of name lookup (including ADL) in 4407 // Fn. 4408 bool Dependent = false; 4409 if (Fn->isTypeDependent()) 4410 Dependent = true; 4411 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4412 Dependent = true; 4413 4414 if (Dependent) { 4415 if (ExecConfig) { 4416 return Owned(new (Context) CUDAKernelCallExpr( 4417 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4418 Context.DependentTy, VK_RValue, RParenLoc)); 4419 } else { 4420 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4421 Context.DependentTy, VK_RValue, 4422 RParenLoc)); 4423 } 4424 } 4425 4426 // Determine whether this is a call to an object (C++ [over.call.object]). 4427 if (Fn->getType()->isRecordType()) 4428 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4429 ArgExprs, RParenLoc)); 4430 4431 if (Fn->getType() == Context.UnknownAnyTy) { 4432 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4433 if (result.isInvalid()) return ExprError(); 4434 Fn = result.take(); 4435 } 4436 4437 if (Fn->getType() == Context.BoundMemberTy) { 4438 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4439 } 4440 } 4441 4442 // Check for overloaded calls. This can happen even in C due to extensions. 4443 if (Fn->getType() == Context.OverloadTy) { 4444 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4445 4446 // We aren't supposed to apply this logic for if there's an '&' involved. 4447 if (!find.HasFormOfMemberPointer) { 4448 OverloadExpr *ovl = find.Expression; 4449 if (isa<UnresolvedLookupExpr>(ovl)) { 4450 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4451 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4452 RParenLoc, ExecConfig); 4453 } else { 4454 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4455 RParenLoc); 4456 } 4457 } 4458 } 4459 4460 // If we're directly calling a function, get the appropriate declaration. 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 Expr *NakedFn = Fn->IgnoreParens(); 4468 4469 NamedDecl *NDecl = 0; 4470 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4471 if (UnOp->getOpcode() == UO_AddrOf) 4472 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4473 4474 if (isa<DeclRefExpr>(NakedFn)) 4475 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4476 else if (isa<MemberExpr>(NakedFn)) 4477 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4478 4479 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4480 if (FD->hasAttr<EnableIfAttr>()) { 4481 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4482 Diag(Fn->getLocStart(), 4483 isa<CXXMethodDecl>(FD) ? 4484 diag::err_ovl_no_viable_member_function_in_call : 4485 diag::err_ovl_no_viable_function_in_call) 4486 << FD << FD->getSourceRange(); 4487 Diag(FD->getLocation(), 4488 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4489 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4490 } 4491 } 4492 } 4493 4494 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4495 ExecConfig, IsExecConfig); 4496 } 4497 4498 ExprResult 4499 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4500 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4501 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4502 if (!ConfigDecl) 4503 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4504 << "cudaConfigureCall"); 4505 QualType ConfigQTy = ConfigDecl->getType(); 4506 4507 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4508 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4509 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4510 4511 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4512 /*IsExecConfig=*/true); 4513 } 4514 4515 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4516 /// 4517 /// __builtin_astype( value, dst type ) 4518 /// 4519 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4520 SourceLocation BuiltinLoc, 4521 SourceLocation RParenLoc) { 4522 ExprValueKind VK = VK_RValue; 4523 ExprObjectKind OK = OK_Ordinary; 4524 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4525 QualType SrcTy = E->getType(); 4526 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4527 return ExprError(Diag(BuiltinLoc, 4528 diag::err_invalid_astype_of_different_size) 4529 << DstTy 4530 << SrcTy 4531 << E->getSourceRange()); 4532 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4533 RParenLoc)); 4534 } 4535 4536 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4537 /// provided arguments. 4538 /// 4539 /// __builtin_convertvector( value, dst type ) 4540 /// 4541 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4542 SourceLocation BuiltinLoc, 4543 SourceLocation RParenLoc) { 4544 TypeSourceInfo *TInfo; 4545 GetTypeFromParser(ParsedDestTy, &TInfo); 4546 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4547 } 4548 4549 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4550 /// i.e. an expression not of \p OverloadTy. The expression should 4551 /// unary-convert to an expression of function-pointer or 4552 /// block-pointer type. 4553 /// 4554 /// \param NDecl the declaration being called, if available 4555 ExprResult 4556 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4557 SourceLocation LParenLoc, 4558 ArrayRef<Expr *> Args, 4559 SourceLocation RParenLoc, 4560 Expr *Config, bool IsExecConfig) { 4561 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4562 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4563 4564 // Promote the function operand. 4565 // We special-case function promotion here because we only allow promoting 4566 // builtin functions to function pointers in the callee of a call. 4567 ExprResult Result; 4568 if (BuiltinID && 4569 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4570 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4571 CK_BuiltinFnToFnPtr).take(); 4572 } else { 4573 Result = UsualUnaryConversions(Fn); 4574 } 4575 if (Result.isInvalid()) 4576 return ExprError(); 4577 Fn = Result.take(); 4578 4579 // Make the call expr early, before semantic checks. This guarantees cleanup 4580 // of arguments and function on error. 4581 CallExpr *TheCall; 4582 if (Config) 4583 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4584 cast<CallExpr>(Config), Args, 4585 Context.BoolTy, VK_RValue, 4586 RParenLoc); 4587 else 4588 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4589 VK_RValue, RParenLoc); 4590 4591 // Bail out early if calling a builtin with custom typechecking. 4592 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4593 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4594 4595 retry: 4596 const FunctionType *FuncT; 4597 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4598 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4599 // have type pointer to function". 4600 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4601 if (FuncT == 0) 4602 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4603 << Fn->getType() << Fn->getSourceRange()); 4604 } else if (const BlockPointerType *BPT = 4605 Fn->getType()->getAs<BlockPointerType>()) { 4606 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4607 } else { 4608 // Handle calls to expressions of unknown-any type. 4609 if (Fn->getType() == Context.UnknownAnyTy) { 4610 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4611 if (rewrite.isInvalid()) return ExprError(); 4612 Fn = rewrite.take(); 4613 TheCall->setCallee(Fn); 4614 goto retry; 4615 } 4616 4617 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4618 << Fn->getType() << Fn->getSourceRange()); 4619 } 4620 4621 if (getLangOpts().CUDA) { 4622 if (Config) { 4623 // CUDA: Kernel calls must be to global functions 4624 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4625 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4626 << FDecl->getName() << Fn->getSourceRange()); 4627 4628 // CUDA: Kernel function must have 'void' return type 4629 if (!FuncT->getReturnType()->isVoidType()) 4630 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4631 << Fn->getType() << Fn->getSourceRange()); 4632 } else { 4633 // CUDA: Calls to global functions must be configured 4634 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4635 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4636 << FDecl->getName() << Fn->getSourceRange()); 4637 } 4638 } 4639 4640 // Check for a valid return type 4641 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 4642 FDecl)) 4643 return ExprError(); 4644 4645 // We know the result type of the call, set it. 4646 TheCall->setType(FuncT->getCallResultType(Context)); 4647 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 4648 4649 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4650 if (Proto) { 4651 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4652 IsExecConfig)) 4653 return ExprError(); 4654 } else { 4655 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4656 4657 if (FDecl) { 4658 // Check if we have too few/too many template arguments, based 4659 // on our knowledge of the function definition. 4660 const FunctionDecl *Def = 0; 4661 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4662 Proto = Def->getType()->getAs<FunctionProtoType>(); 4663 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4664 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4665 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4666 } 4667 4668 // If the function we're calling isn't a function prototype, but we have 4669 // a function prototype from a prior declaratiom, use that prototype. 4670 if (!FDecl->hasPrototype()) 4671 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4672 } 4673 4674 // Promote the arguments (C99 6.5.2.2p6). 4675 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4676 Expr *Arg = Args[i]; 4677 4678 if (Proto && i < Proto->getNumParams()) { 4679 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4680 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 4681 ExprResult ArgE = PerformCopyInitialization(Entity, 4682 SourceLocation(), 4683 Owned(Arg)); 4684 if (ArgE.isInvalid()) 4685 return true; 4686 4687 Arg = ArgE.takeAs<Expr>(); 4688 4689 } else { 4690 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4691 4692 if (ArgE.isInvalid()) 4693 return true; 4694 4695 Arg = ArgE.takeAs<Expr>(); 4696 } 4697 4698 if (RequireCompleteType(Arg->getLocStart(), 4699 Arg->getType(), 4700 diag::err_call_incomplete_argument, Arg)) 4701 return ExprError(); 4702 4703 TheCall->setArg(i, Arg); 4704 } 4705 } 4706 4707 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4708 if (!Method->isStatic()) 4709 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4710 << Fn->getSourceRange()); 4711 4712 // Check for sentinels 4713 if (NDecl) 4714 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4715 4716 // Do special checking on direct calls to functions. 4717 if (FDecl) { 4718 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4719 return ExprError(); 4720 4721 if (BuiltinID) 4722 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4723 } else if (NDecl) { 4724 if (CheckPointerCall(NDecl, TheCall, Proto)) 4725 return ExprError(); 4726 } else { 4727 if (CheckOtherCall(TheCall, Proto)) 4728 return ExprError(); 4729 } 4730 4731 return MaybeBindToTemporary(TheCall); 4732 } 4733 4734 ExprResult 4735 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4736 SourceLocation RParenLoc, Expr *InitExpr) { 4737 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4738 // FIXME: put back this assert when initializers are worked out. 4739 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4740 4741 TypeSourceInfo *TInfo; 4742 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4743 if (!TInfo) 4744 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4745 4746 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4747 } 4748 4749 ExprResult 4750 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4751 SourceLocation RParenLoc, Expr *LiteralExpr) { 4752 QualType literalType = TInfo->getType(); 4753 4754 if (literalType->isArrayType()) { 4755 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4756 diag::err_illegal_decl_array_incomplete_type, 4757 SourceRange(LParenLoc, 4758 LiteralExpr->getSourceRange().getEnd()))) 4759 return ExprError(); 4760 if (literalType->isVariableArrayType()) 4761 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4762 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4763 } else if (!literalType->isDependentType() && 4764 RequireCompleteType(LParenLoc, literalType, 4765 diag::err_typecheck_decl_incomplete_type, 4766 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4767 return ExprError(); 4768 4769 InitializedEntity Entity 4770 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4771 InitializationKind Kind 4772 = InitializationKind::CreateCStyleCast(LParenLoc, 4773 SourceRange(LParenLoc, RParenLoc), 4774 /*InitList=*/true); 4775 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4776 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4777 &literalType); 4778 if (Result.isInvalid()) 4779 return ExprError(); 4780 LiteralExpr = Result.get(); 4781 4782 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4783 if (isFileScope && 4784 !LiteralExpr->isTypeDependent() && 4785 !LiteralExpr->isValueDependent() && 4786 !literalType->isDependentType()) { // 6.5.2.5p3 4787 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4788 return ExprError(); 4789 } 4790 4791 // In C, compound literals are l-values for some reason. 4792 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4793 4794 return MaybeBindToTemporary( 4795 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4796 VK, LiteralExpr, isFileScope)); 4797 } 4798 4799 ExprResult 4800 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4801 SourceLocation RBraceLoc) { 4802 // Immediately handle non-overload placeholders. Overloads can be 4803 // resolved contextually, but everything else here can't. 4804 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4805 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4806 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4807 4808 // Ignore failures; dropping the entire initializer list because 4809 // of one failure would be terrible for indexing/etc. 4810 if (result.isInvalid()) continue; 4811 4812 InitArgList[I] = result.take(); 4813 } 4814 } 4815 4816 // Semantic analysis for initializers is done by ActOnDeclarator() and 4817 // CheckInitializer() - it requires knowledge of the object being intialized. 4818 4819 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4820 RBraceLoc); 4821 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4822 return Owned(E); 4823 } 4824 4825 /// Do an explicit extend of the given block pointer if we're in ARC. 4826 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4827 assert(E.get()->getType()->isBlockPointerType()); 4828 assert(E.get()->isRValue()); 4829 4830 // Only do this in an r-value context. 4831 if (!S.getLangOpts().ObjCAutoRefCount) return; 4832 4833 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4834 CK_ARCExtendBlockObject, E.get(), 4835 /*base path*/ 0, VK_RValue); 4836 S.ExprNeedsCleanups = true; 4837 } 4838 4839 /// Prepare a conversion of the given expression to an ObjC object 4840 /// pointer type. 4841 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4842 QualType type = E.get()->getType(); 4843 if (type->isObjCObjectPointerType()) { 4844 return CK_BitCast; 4845 } else if (type->isBlockPointerType()) { 4846 maybeExtendBlockObject(*this, E); 4847 return CK_BlockPointerToObjCPointerCast; 4848 } else { 4849 assert(type->isPointerType()); 4850 return CK_CPointerToObjCPointerCast; 4851 } 4852 } 4853 4854 /// Prepares for a scalar cast, performing all the necessary stages 4855 /// except the final cast and returning the kind required. 4856 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4857 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4858 // Also, callers should have filtered out the invalid cases with 4859 // pointers. Everything else should be possible. 4860 4861 QualType SrcTy = Src.get()->getType(); 4862 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4863 return CK_NoOp; 4864 4865 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4866 case Type::STK_MemberPointer: 4867 llvm_unreachable("member pointer type in C"); 4868 4869 case Type::STK_CPointer: 4870 case Type::STK_BlockPointer: 4871 case Type::STK_ObjCObjectPointer: 4872 switch (DestTy->getScalarTypeKind()) { 4873 case Type::STK_CPointer: { 4874 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 4875 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 4876 if (SrcAS != DestAS) 4877 return CK_AddressSpaceConversion; 4878 return CK_BitCast; 4879 } 4880 case Type::STK_BlockPointer: 4881 return (SrcKind == Type::STK_BlockPointer 4882 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4883 case Type::STK_ObjCObjectPointer: 4884 if (SrcKind == Type::STK_ObjCObjectPointer) 4885 return CK_BitCast; 4886 if (SrcKind == Type::STK_CPointer) 4887 return CK_CPointerToObjCPointerCast; 4888 maybeExtendBlockObject(*this, Src); 4889 return CK_BlockPointerToObjCPointerCast; 4890 case Type::STK_Bool: 4891 return CK_PointerToBoolean; 4892 case Type::STK_Integral: 4893 return CK_PointerToIntegral; 4894 case Type::STK_Floating: 4895 case Type::STK_FloatingComplex: 4896 case Type::STK_IntegralComplex: 4897 case Type::STK_MemberPointer: 4898 llvm_unreachable("illegal cast from pointer"); 4899 } 4900 llvm_unreachable("Should have returned before this"); 4901 4902 case Type::STK_Bool: // casting from bool is like casting from an integer 4903 case Type::STK_Integral: 4904 switch (DestTy->getScalarTypeKind()) { 4905 case Type::STK_CPointer: 4906 case Type::STK_ObjCObjectPointer: 4907 case Type::STK_BlockPointer: 4908 if (Src.get()->isNullPointerConstant(Context, 4909 Expr::NPC_ValueDependentIsNull)) 4910 return CK_NullToPointer; 4911 return CK_IntegralToPointer; 4912 case Type::STK_Bool: 4913 return CK_IntegralToBoolean; 4914 case Type::STK_Integral: 4915 return CK_IntegralCast; 4916 case Type::STK_Floating: 4917 return CK_IntegralToFloating; 4918 case Type::STK_IntegralComplex: 4919 Src = ImpCastExprToType(Src.take(), 4920 DestTy->castAs<ComplexType>()->getElementType(), 4921 CK_IntegralCast); 4922 return CK_IntegralRealToComplex; 4923 case Type::STK_FloatingComplex: 4924 Src = ImpCastExprToType(Src.take(), 4925 DestTy->castAs<ComplexType>()->getElementType(), 4926 CK_IntegralToFloating); 4927 return CK_FloatingRealToComplex; 4928 case Type::STK_MemberPointer: 4929 llvm_unreachable("member pointer type in C"); 4930 } 4931 llvm_unreachable("Should have returned before this"); 4932 4933 case Type::STK_Floating: 4934 switch (DestTy->getScalarTypeKind()) { 4935 case Type::STK_Floating: 4936 return CK_FloatingCast; 4937 case Type::STK_Bool: 4938 return CK_FloatingToBoolean; 4939 case Type::STK_Integral: 4940 return CK_FloatingToIntegral; 4941 case Type::STK_FloatingComplex: 4942 Src = ImpCastExprToType(Src.take(), 4943 DestTy->castAs<ComplexType>()->getElementType(), 4944 CK_FloatingCast); 4945 return CK_FloatingRealToComplex; 4946 case Type::STK_IntegralComplex: 4947 Src = ImpCastExprToType(Src.take(), 4948 DestTy->castAs<ComplexType>()->getElementType(), 4949 CK_FloatingToIntegral); 4950 return CK_IntegralRealToComplex; 4951 case Type::STK_CPointer: 4952 case Type::STK_ObjCObjectPointer: 4953 case Type::STK_BlockPointer: 4954 llvm_unreachable("valid float->pointer cast?"); 4955 case Type::STK_MemberPointer: 4956 llvm_unreachable("member pointer type in C"); 4957 } 4958 llvm_unreachable("Should have returned before this"); 4959 4960 case Type::STK_FloatingComplex: 4961 switch (DestTy->getScalarTypeKind()) { 4962 case Type::STK_FloatingComplex: 4963 return CK_FloatingComplexCast; 4964 case Type::STK_IntegralComplex: 4965 return CK_FloatingComplexToIntegralComplex; 4966 case Type::STK_Floating: { 4967 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4968 if (Context.hasSameType(ET, DestTy)) 4969 return CK_FloatingComplexToReal; 4970 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4971 return CK_FloatingCast; 4972 } 4973 case Type::STK_Bool: 4974 return CK_FloatingComplexToBoolean; 4975 case Type::STK_Integral: 4976 Src = ImpCastExprToType(Src.take(), 4977 SrcTy->castAs<ComplexType>()->getElementType(), 4978 CK_FloatingComplexToReal); 4979 return CK_FloatingToIntegral; 4980 case Type::STK_CPointer: 4981 case Type::STK_ObjCObjectPointer: 4982 case Type::STK_BlockPointer: 4983 llvm_unreachable("valid complex float->pointer cast?"); 4984 case Type::STK_MemberPointer: 4985 llvm_unreachable("member pointer type in C"); 4986 } 4987 llvm_unreachable("Should have returned before this"); 4988 4989 case Type::STK_IntegralComplex: 4990 switch (DestTy->getScalarTypeKind()) { 4991 case Type::STK_FloatingComplex: 4992 return CK_IntegralComplexToFloatingComplex; 4993 case Type::STK_IntegralComplex: 4994 return CK_IntegralComplexCast; 4995 case Type::STK_Integral: { 4996 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4997 if (Context.hasSameType(ET, DestTy)) 4998 return CK_IntegralComplexToReal; 4999 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 5000 return CK_IntegralCast; 5001 } 5002 case Type::STK_Bool: 5003 return CK_IntegralComplexToBoolean; 5004 case Type::STK_Floating: 5005 Src = ImpCastExprToType(Src.take(), 5006 SrcTy->castAs<ComplexType>()->getElementType(), 5007 CK_IntegralComplexToReal); 5008 return CK_IntegralToFloating; 5009 case Type::STK_CPointer: 5010 case Type::STK_ObjCObjectPointer: 5011 case Type::STK_BlockPointer: 5012 llvm_unreachable("valid complex int->pointer cast?"); 5013 case Type::STK_MemberPointer: 5014 llvm_unreachable("member pointer type in C"); 5015 } 5016 llvm_unreachable("Should have returned before this"); 5017 } 5018 5019 llvm_unreachable("Unhandled scalar cast"); 5020 } 5021 5022 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5023 CastKind &Kind) { 5024 assert(VectorTy->isVectorType() && "Not a vector type!"); 5025 5026 if (Ty->isVectorType() || Ty->isIntegerType()) { 5027 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 5028 return Diag(R.getBegin(), 5029 Ty->isVectorType() ? 5030 diag::err_invalid_conversion_between_vectors : 5031 diag::err_invalid_conversion_between_vector_and_integer) 5032 << VectorTy << Ty << R; 5033 } else 5034 return Diag(R.getBegin(), 5035 diag::err_invalid_conversion_between_vector_and_scalar) 5036 << VectorTy << Ty << R; 5037 5038 Kind = CK_BitCast; 5039 return false; 5040 } 5041 5042 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5043 Expr *CastExpr, CastKind &Kind) { 5044 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5045 5046 QualType SrcTy = CastExpr->getType(); 5047 5048 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5049 // an ExtVectorType. 5050 // In OpenCL, casts between vectors of different types are not allowed. 5051 // (See OpenCL 6.2). 5052 if (SrcTy->isVectorType()) { 5053 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 5054 || (getLangOpts().OpenCL && 5055 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5056 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5057 << DestTy << SrcTy << R; 5058 return ExprError(); 5059 } 5060 Kind = CK_BitCast; 5061 return Owned(CastExpr); 5062 } 5063 5064 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5065 // conversion will take place first from scalar to elt type, and then 5066 // splat from elt type to vector. 5067 if (SrcTy->isPointerType()) 5068 return Diag(R.getBegin(), 5069 diag::err_invalid_conversion_between_vector_and_scalar) 5070 << DestTy << SrcTy << R; 5071 5072 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5073 ExprResult CastExprRes = Owned(CastExpr); 5074 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5075 if (CastExprRes.isInvalid()) 5076 return ExprError(); 5077 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 5078 5079 Kind = CK_VectorSplat; 5080 return Owned(CastExpr); 5081 } 5082 5083 ExprResult 5084 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5085 Declarator &D, ParsedType &Ty, 5086 SourceLocation RParenLoc, Expr *CastExpr) { 5087 assert(!D.isInvalidType() && (CastExpr != 0) && 5088 "ActOnCastExpr(): missing type or expr"); 5089 5090 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5091 if (D.isInvalidType()) 5092 return ExprError(); 5093 5094 if (getLangOpts().CPlusPlus) { 5095 // Check that there are no default arguments (C++ only). 5096 CheckExtraCXXDefaultArguments(D); 5097 } 5098 5099 checkUnusedDeclAttributes(D); 5100 5101 QualType castType = castTInfo->getType(); 5102 Ty = CreateParsedType(castType, castTInfo); 5103 5104 bool isVectorLiteral = false; 5105 5106 // Check for an altivec or OpenCL literal, 5107 // i.e. all the elements are integer constants. 5108 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5109 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5110 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5111 && castType->isVectorType() && (PE || PLE)) { 5112 if (PLE && PLE->getNumExprs() == 0) { 5113 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5114 return ExprError(); 5115 } 5116 if (PE || PLE->getNumExprs() == 1) { 5117 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5118 if (!E->getType()->isVectorType()) 5119 isVectorLiteral = true; 5120 } 5121 else 5122 isVectorLiteral = true; 5123 } 5124 5125 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5126 // then handle it as such. 5127 if (isVectorLiteral) 5128 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5129 5130 // If the Expr being casted is a ParenListExpr, handle it specially. 5131 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5132 // sequence of BinOp comma operators. 5133 if (isa<ParenListExpr>(CastExpr)) { 5134 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5135 if (Result.isInvalid()) return ExprError(); 5136 CastExpr = Result.take(); 5137 } 5138 5139 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5140 !getSourceManager().isInSystemMacro(LParenLoc)) 5141 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5142 5143 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5144 } 5145 5146 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5147 SourceLocation RParenLoc, Expr *E, 5148 TypeSourceInfo *TInfo) { 5149 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5150 "Expected paren or paren list expression"); 5151 5152 Expr **exprs; 5153 unsigned numExprs; 5154 Expr *subExpr; 5155 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5156 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5157 LiteralLParenLoc = PE->getLParenLoc(); 5158 LiteralRParenLoc = PE->getRParenLoc(); 5159 exprs = PE->getExprs(); 5160 numExprs = PE->getNumExprs(); 5161 } else { // isa<ParenExpr> by assertion at function entrance 5162 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5163 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5164 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5165 exprs = &subExpr; 5166 numExprs = 1; 5167 } 5168 5169 QualType Ty = TInfo->getType(); 5170 assert(Ty->isVectorType() && "Expected vector type"); 5171 5172 SmallVector<Expr *, 8> initExprs; 5173 const VectorType *VTy = Ty->getAs<VectorType>(); 5174 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5175 5176 // '(...)' form of vector initialization in AltiVec: the number of 5177 // initializers must be one or must match the size of the vector. 5178 // If a single value is specified in the initializer then it will be 5179 // replicated to all the components of the vector 5180 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5181 // The number of initializers must be one or must match the size of the 5182 // vector. If a single value is specified in the initializer then it will 5183 // be replicated to all the components of the vector 5184 if (numExprs == 1) { 5185 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5186 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5187 if (Literal.isInvalid()) 5188 return ExprError(); 5189 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5190 PrepareScalarCast(Literal, ElemTy)); 5191 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5192 } 5193 else if (numExprs < numElems) { 5194 Diag(E->getExprLoc(), 5195 diag::err_incorrect_number_of_vector_initializers); 5196 return ExprError(); 5197 } 5198 else 5199 initExprs.append(exprs, exprs + numExprs); 5200 } 5201 else { 5202 // For OpenCL, when the number of initializers is a single value, 5203 // it will be replicated to all components of the vector. 5204 if (getLangOpts().OpenCL && 5205 VTy->getVectorKind() == VectorType::GenericVector && 5206 numExprs == 1) { 5207 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5208 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5209 if (Literal.isInvalid()) 5210 return ExprError(); 5211 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5212 PrepareScalarCast(Literal, ElemTy)); 5213 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5214 } 5215 5216 initExprs.append(exprs, exprs + numExprs); 5217 } 5218 // FIXME: This means that pretty-printing the final AST will produce curly 5219 // braces instead of the original commas. 5220 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5221 initExprs, LiteralRParenLoc); 5222 initE->setType(Ty); 5223 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5224 } 5225 5226 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5227 /// the ParenListExpr into a sequence of comma binary operators. 5228 ExprResult 5229 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5230 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5231 if (!E) 5232 return Owned(OrigExpr); 5233 5234 ExprResult Result(E->getExpr(0)); 5235 5236 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5237 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5238 E->getExpr(i)); 5239 5240 if (Result.isInvalid()) return ExprError(); 5241 5242 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5243 } 5244 5245 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5246 SourceLocation R, 5247 MultiExprArg Val) { 5248 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5249 return Owned(expr); 5250 } 5251 5252 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5253 /// constant and the other is not a pointer. Returns true if a diagnostic is 5254 /// emitted. 5255 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5256 SourceLocation QuestionLoc) { 5257 Expr *NullExpr = LHSExpr; 5258 Expr *NonPointerExpr = RHSExpr; 5259 Expr::NullPointerConstantKind NullKind = 5260 NullExpr->isNullPointerConstant(Context, 5261 Expr::NPC_ValueDependentIsNotNull); 5262 5263 if (NullKind == Expr::NPCK_NotNull) { 5264 NullExpr = RHSExpr; 5265 NonPointerExpr = LHSExpr; 5266 NullKind = 5267 NullExpr->isNullPointerConstant(Context, 5268 Expr::NPC_ValueDependentIsNotNull); 5269 } 5270 5271 if (NullKind == Expr::NPCK_NotNull) 5272 return false; 5273 5274 if (NullKind == Expr::NPCK_ZeroExpression) 5275 return false; 5276 5277 if (NullKind == Expr::NPCK_ZeroLiteral) { 5278 // In this case, check to make sure that we got here from a "NULL" 5279 // string in the source code. 5280 NullExpr = NullExpr->IgnoreParenImpCasts(); 5281 SourceLocation loc = NullExpr->getExprLoc(); 5282 if (!findMacroSpelling(loc, "NULL")) 5283 return false; 5284 } 5285 5286 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5287 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5288 << NonPointerExpr->getType() << DiagType 5289 << NonPointerExpr->getSourceRange(); 5290 return true; 5291 } 5292 5293 /// \brief Return false if the condition expression is valid, true otherwise. 5294 static bool checkCondition(Sema &S, Expr *Cond) { 5295 QualType CondTy = Cond->getType(); 5296 5297 // C99 6.5.15p2 5298 if (CondTy->isScalarType()) return false; 5299 5300 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5301 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5302 return false; 5303 5304 // Emit the proper error message. 5305 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5306 diag::err_typecheck_cond_expect_scalar : 5307 diag::err_typecheck_cond_expect_scalar_or_vector) 5308 << CondTy; 5309 return true; 5310 } 5311 5312 /// \brief Return false if the two expressions can be converted to a vector, 5313 /// true otherwise 5314 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5315 ExprResult &RHS, 5316 QualType CondTy) { 5317 // Both operands should be of scalar type. 5318 if (!LHS.get()->getType()->isScalarType()) { 5319 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5320 << CondTy; 5321 return true; 5322 } 5323 if (!RHS.get()->getType()->isScalarType()) { 5324 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5325 << CondTy; 5326 return true; 5327 } 5328 5329 // Implicity convert these scalars to the type of the condition. 5330 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5331 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5332 return false; 5333 } 5334 5335 /// \brief Handle when one or both operands are void type. 5336 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5337 ExprResult &RHS) { 5338 Expr *LHSExpr = LHS.get(); 5339 Expr *RHSExpr = RHS.get(); 5340 5341 if (!LHSExpr->getType()->isVoidType()) 5342 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5343 << RHSExpr->getSourceRange(); 5344 if (!RHSExpr->getType()->isVoidType()) 5345 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5346 << LHSExpr->getSourceRange(); 5347 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5348 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5349 return S.Context.VoidTy; 5350 } 5351 5352 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5353 /// true otherwise. 5354 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5355 QualType PointerTy) { 5356 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5357 !NullExpr.get()->isNullPointerConstant(S.Context, 5358 Expr::NPC_ValueDependentIsNull)) 5359 return true; 5360 5361 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5362 return false; 5363 } 5364 5365 /// \brief Checks compatibility between two pointers and return the resulting 5366 /// type. 5367 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5368 ExprResult &RHS, 5369 SourceLocation Loc) { 5370 QualType LHSTy = LHS.get()->getType(); 5371 QualType RHSTy = RHS.get()->getType(); 5372 5373 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5374 // Two identical pointers types are always compatible. 5375 return LHSTy; 5376 } 5377 5378 QualType lhptee, rhptee; 5379 5380 // Get the pointee types. 5381 bool IsBlockPointer = false; 5382 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5383 lhptee = LHSBTy->getPointeeType(); 5384 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5385 IsBlockPointer = true; 5386 } else { 5387 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5388 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5389 } 5390 5391 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5392 // differently qualified versions of compatible types, the result type is 5393 // a pointer to an appropriately qualified version of the composite 5394 // type. 5395 5396 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5397 // clause doesn't make sense for our extensions. E.g. address space 2 should 5398 // be incompatible with address space 3: they may live on different devices or 5399 // anything. 5400 Qualifiers lhQual = lhptee.getQualifiers(); 5401 Qualifiers rhQual = rhptee.getQualifiers(); 5402 5403 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5404 lhQual.removeCVRQualifiers(); 5405 rhQual.removeCVRQualifiers(); 5406 5407 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5408 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5409 5410 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5411 5412 if (CompositeTy.isNull()) { 5413 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5414 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5415 << RHS.get()->getSourceRange(); 5416 // In this situation, we assume void* type. No especially good 5417 // reason, but this is what gcc does, and we do have to pick 5418 // to get a consistent AST. 5419 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5420 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5421 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5422 return incompatTy; 5423 } 5424 5425 // The pointer types are compatible. 5426 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5427 if (IsBlockPointer) 5428 ResultTy = S.Context.getBlockPointerType(ResultTy); 5429 else 5430 ResultTy = S.Context.getPointerType(ResultTy); 5431 5432 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5433 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5434 return ResultTy; 5435 } 5436 5437 /// \brief Return the resulting type when the operands are both block pointers. 5438 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5439 ExprResult &LHS, 5440 ExprResult &RHS, 5441 SourceLocation Loc) { 5442 QualType LHSTy = LHS.get()->getType(); 5443 QualType RHSTy = RHS.get()->getType(); 5444 5445 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5446 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5447 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5448 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5449 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5450 return destType; 5451 } 5452 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5453 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5454 << RHS.get()->getSourceRange(); 5455 return QualType(); 5456 } 5457 5458 // We have 2 block pointer types. 5459 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5460 } 5461 5462 /// \brief Return the resulting type when the operands are both pointers. 5463 static QualType 5464 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5465 ExprResult &RHS, 5466 SourceLocation Loc) { 5467 // get the pointer types 5468 QualType LHSTy = LHS.get()->getType(); 5469 QualType RHSTy = RHS.get()->getType(); 5470 5471 // get the "pointed to" types 5472 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5473 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5474 5475 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5476 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5477 // Figure out necessary qualifiers (C99 6.5.15p6) 5478 QualType destPointee 5479 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5480 QualType destType = S.Context.getPointerType(destPointee); 5481 // Add qualifiers if necessary. 5482 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5483 // Promote to void*. 5484 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5485 return destType; 5486 } 5487 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5488 QualType destPointee 5489 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5490 QualType destType = S.Context.getPointerType(destPointee); 5491 // Add qualifiers if necessary. 5492 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5493 // Promote to void*. 5494 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5495 return destType; 5496 } 5497 5498 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5499 } 5500 5501 /// \brief Return false if the first expression is not an integer and the second 5502 /// expression is not a pointer, true otherwise. 5503 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5504 Expr* PointerExpr, SourceLocation Loc, 5505 bool IsIntFirstExpr) { 5506 if (!PointerExpr->getType()->isPointerType() || 5507 !Int.get()->getType()->isIntegerType()) 5508 return false; 5509 5510 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5511 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5512 5513 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5514 << Expr1->getType() << Expr2->getType() 5515 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5516 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5517 CK_IntegralToPointer); 5518 return true; 5519 } 5520 5521 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5522 /// In that case, LHS = cond. 5523 /// C99 6.5.15 5524 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5525 ExprResult &RHS, ExprValueKind &VK, 5526 ExprObjectKind &OK, 5527 SourceLocation QuestionLoc) { 5528 5529 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5530 if (!LHSResult.isUsable()) return QualType(); 5531 LHS = LHSResult; 5532 5533 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5534 if (!RHSResult.isUsable()) return QualType(); 5535 RHS = RHSResult; 5536 5537 // C++ is sufficiently different to merit its own checker. 5538 if (getLangOpts().CPlusPlus) 5539 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5540 5541 VK = VK_RValue; 5542 OK = OK_Ordinary; 5543 5544 // First, check the condition. 5545 Cond = UsualUnaryConversions(Cond.take()); 5546 if (Cond.isInvalid()) 5547 return QualType(); 5548 if (checkCondition(*this, Cond.get())) 5549 return QualType(); 5550 5551 // Now check the two expressions. 5552 if (LHS.get()->getType()->isVectorType() || 5553 RHS.get()->getType()->isVectorType()) 5554 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5555 5556 UsualArithmeticConversions(LHS, RHS); 5557 if (LHS.isInvalid() || RHS.isInvalid()) 5558 return QualType(); 5559 5560 QualType CondTy = Cond.get()->getType(); 5561 QualType LHSTy = LHS.get()->getType(); 5562 QualType RHSTy = RHS.get()->getType(); 5563 5564 // If the condition is a vector, and both operands are scalar, 5565 // attempt to implicity convert them to the vector type to act like the 5566 // built in select. (OpenCL v1.1 s6.3.i) 5567 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5568 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5569 return QualType(); 5570 5571 // If both operands have arithmetic type, do the usual arithmetic conversions 5572 // to find a common type: C99 6.5.15p3,5. 5573 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5574 return LHS.get()->getType(); 5575 5576 // If both operands are the same structure or union type, the result is that 5577 // type. 5578 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5579 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5580 if (LHSRT->getDecl() == RHSRT->getDecl()) 5581 // "If both the operands have structure or union type, the result has 5582 // that type." This implies that CV qualifiers are dropped. 5583 return LHSTy.getUnqualifiedType(); 5584 // FIXME: Type of conditional expression must be complete in C mode. 5585 } 5586 5587 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5588 // The following || allows only one side to be void (a GCC-ism). 5589 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5590 return checkConditionalVoidType(*this, LHS, RHS); 5591 } 5592 5593 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5594 // the type of the other operand." 5595 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5596 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5597 5598 // All objective-c pointer type analysis is done here. 5599 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5600 QuestionLoc); 5601 if (LHS.isInvalid() || RHS.isInvalid()) 5602 return QualType(); 5603 if (!compositeType.isNull()) 5604 return compositeType; 5605 5606 5607 // Handle block pointer types. 5608 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5609 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5610 QuestionLoc); 5611 5612 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5613 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5614 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5615 QuestionLoc); 5616 5617 // GCC compatibility: soften pointer/integer mismatch. Note that 5618 // null pointers have been filtered out by this point. 5619 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5620 /*isIntFirstExpr=*/true)) 5621 return RHSTy; 5622 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5623 /*isIntFirstExpr=*/false)) 5624 return LHSTy; 5625 5626 // Emit a better diagnostic if one of the expressions is a null pointer 5627 // constant and the other is not a pointer type. In this case, the user most 5628 // likely forgot to take the address of the other expression. 5629 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5630 return QualType(); 5631 5632 // Otherwise, the operands are not compatible. 5633 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5634 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5635 << RHS.get()->getSourceRange(); 5636 return QualType(); 5637 } 5638 5639 /// FindCompositeObjCPointerType - Helper method to find composite type of 5640 /// two objective-c pointer types of the two input expressions. 5641 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5642 SourceLocation QuestionLoc) { 5643 QualType LHSTy = LHS.get()->getType(); 5644 QualType RHSTy = RHS.get()->getType(); 5645 5646 // Handle things like Class and struct objc_class*. Here we case the result 5647 // to the pseudo-builtin, because that will be implicitly cast back to the 5648 // redefinition type if an attempt is made to access its fields. 5649 if (LHSTy->isObjCClassType() && 5650 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5651 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5652 return LHSTy; 5653 } 5654 if (RHSTy->isObjCClassType() && 5655 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5656 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5657 return RHSTy; 5658 } 5659 // And the same for struct objc_object* / id 5660 if (LHSTy->isObjCIdType() && 5661 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5662 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5663 return LHSTy; 5664 } 5665 if (RHSTy->isObjCIdType() && 5666 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5667 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5668 return RHSTy; 5669 } 5670 // And the same for struct objc_selector* / SEL 5671 if (Context.isObjCSelType(LHSTy) && 5672 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5673 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5674 return LHSTy; 5675 } 5676 if (Context.isObjCSelType(RHSTy) && 5677 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5678 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5679 return RHSTy; 5680 } 5681 // Check constraints for Objective-C object pointers types. 5682 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5683 5684 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5685 // Two identical object pointer types are always compatible. 5686 return LHSTy; 5687 } 5688 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5689 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5690 QualType compositeType = LHSTy; 5691 5692 // If both operands are interfaces and either operand can be 5693 // assigned to the other, use that type as the composite 5694 // type. This allows 5695 // xxx ? (A*) a : (B*) b 5696 // where B is a subclass of A. 5697 // 5698 // Additionally, as for assignment, if either type is 'id' 5699 // allow silent coercion. Finally, if the types are 5700 // incompatible then make sure to use 'id' as the composite 5701 // type so the result is acceptable for sending messages to. 5702 5703 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5704 // It could return the composite type. 5705 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5706 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5707 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5708 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5709 } else if ((LHSTy->isObjCQualifiedIdType() || 5710 RHSTy->isObjCQualifiedIdType()) && 5711 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5712 // Need to handle "id<xx>" explicitly. 5713 // GCC allows qualified id and any Objective-C type to devolve to 5714 // id. Currently localizing to here until clear this should be 5715 // part of ObjCQualifiedIdTypesAreCompatible. 5716 compositeType = Context.getObjCIdType(); 5717 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5718 compositeType = Context.getObjCIdType(); 5719 } else if (!(compositeType = 5720 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5721 ; 5722 else { 5723 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5724 << LHSTy << RHSTy 5725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5726 QualType incompatTy = Context.getObjCIdType(); 5727 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5728 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5729 return incompatTy; 5730 } 5731 // The object pointer types are compatible. 5732 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5733 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5734 return compositeType; 5735 } 5736 // Check Objective-C object pointer types and 'void *' 5737 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5738 if (getLangOpts().ObjCAutoRefCount) { 5739 // ARC forbids the implicit conversion of object pointers to 'void *', 5740 // so these types are not compatible. 5741 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5742 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5743 LHS = RHS = true; 5744 return QualType(); 5745 } 5746 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5747 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5748 QualType destPointee 5749 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5750 QualType destType = Context.getPointerType(destPointee); 5751 // Add qualifiers if necessary. 5752 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5753 // Promote to void*. 5754 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5755 return destType; 5756 } 5757 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5758 if (getLangOpts().ObjCAutoRefCount) { 5759 // ARC forbids the implicit conversion of object pointers to 'void *', 5760 // so these types are not compatible. 5761 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5762 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5763 LHS = RHS = true; 5764 return QualType(); 5765 } 5766 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5767 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5768 QualType destPointee 5769 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5770 QualType destType = Context.getPointerType(destPointee); 5771 // Add qualifiers if necessary. 5772 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5773 // Promote to void*. 5774 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5775 return destType; 5776 } 5777 return QualType(); 5778 } 5779 5780 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5781 /// ParenRange in parentheses. 5782 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5783 const PartialDiagnostic &Note, 5784 SourceRange ParenRange) { 5785 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5786 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5787 EndLoc.isValid()) { 5788 Self.Diag(Loc, Note) 5789 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5790 << FixItHint::CreateInsertion(EndLoc, ")"); 5791 } else { 5792 // We can't display the parentheses, so just show the bare note. 5793 Self.Diag(Loc, Note) << ParenRange; 5794 } 5795 } 5796 5797 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5798 return Opc >= BO_Mul && Opc <= BO_Shr; 5799 } 5800 5801 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5802 /// expression, either using a built-in or overloaded operator, 5803 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5804 /// expression. 5805 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5806 Expr **RHSExprs) { 5807 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5808 E = E->IgnoreImpCasts(); 5809 E = E->IgnoreConversionOperator(); 5810 E = E->IgnoreImpCasts(); 5811 5812 // Built-in binary operator. 5813 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5814 if (IsArithmeticOp(OP->getOpcode())) { 5815 *Opcode = OP->getOpcode(); 5816 *RHSExprs = OP->getRHS(); 5817 return true; 5818 } 5819 } 5820 5821 // Overloaded operator. 5822 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5823 if (Call->getNumArgs() != 2) 5824 return false; 5825 5826 // Make sure this is really a binary operator that is safe to pass into 5827 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5828 OverloadedOperatorKind OO = Call->getOperator(); 5829 if (OO < OO_Plus || OO > OO_Arrow || 5830 OO == OO_PlusPlus || OO == OO_MinusMinus) 5831 return false; 5832 5833 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5834 if (IsArithmeticOp(OpKind)) { 5835 *Opcode = OpKind; 5836 *RHSExprs = Call->getArg(1); 5837 return true; 5838 } 5839 } 5840 5841 return false; 5842 } 5843 5844 static bool IsLogicOp(BinaryOperatorKind Opc) { 5845 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5846 } 5847 5848 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5849 /// or is a logical expression such as (x==y) which has int type, but is 5850 /// commonly interpreted as boolean. 5851 static bool ExprLooksBoolean(Expr *E) { 5852 E = E->IgnoreParenImpCasts(); 5853 5854 if (E->getType()->isBooleanType()) 5855 return true; 5856 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5857 return IsLogicOp(OP->getOpcode()); 5858 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5859 return OP->getOpcode() == UO_LNot; 5860 5861 return false; 5862 } 5863 5864 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5865 /// and binary operator are mixed in a way that suggests the programmer assumed 5866 /// the conditional operator has higher precedence, for example: 5867 /// "int x = a + someBinaryCondition ? 1 : 2". 5868 static void DiagnoseConditionalPrecedence(Sema &Self, 5869 SourceLocation OpLoc, 5870 Expr *Condition, 5871 Expr *LHSExpr, 5872 Expr *RHSExpr) { 5873 BinaryOperatorKind CondOpcode; 5874 Expr *CondRHS; 5875 5876 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5877 return; 5878 if (!ExprLooksBoolean(CondRHS)) 5879 return; 5880 5881 // The condition is an arithmetic binary expression, with a right- 5882 // hand side that looks boolean, so warn. 5883 5884 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5885 << Condition->getSourceRange() 5886 << BinaryOperator::getOpcodeStr(CondOpcode); 5887 5888 SuggestParentheses(Self, OpLoc, 5889 Self.PDiag(diag::note_precedence_silence) 5890 << BinaryOperator::getOpcodeStr(CondOpcode), 5891 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5892 5893 SuggestParentheses(Self, OpLoc, 5894 Self.PDiag(diag::note_precedence_conditional_first), 5895 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5896 } 5897 5898 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5899 /// in the case of a the GNU conditional expr extension. 5900 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5901 SourceLocation ColonLoc, 5902 Expr *CondExpr, Expr *LHSExpr, 5903 Expr *RHSExpr) { 5904 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5905 // was the condition. 5906 OpaqueValueExpr *opaqueValue = 0; 5907 Expr *commonExpr = 0; 5908 if (LHSExpr == 0) { 5909 commonExpr = CondExpr; 5910 // Lower out placeholder types first. This is important so that we don't 5911 // try to capture a placeholder. This happens in few cases in C++; such 5912 // as Objective-C++'s dictionary subscripting syntax. 5913 if (commonExpr->hasPlaceholderType()) { 5914 ExprResult result = CheckPlaceholderExpr(commonExpr); 5915 if (!result.isUsable()) return ExprError(); 5916 commonExpr = result.take(); 5917 } 5918 // We usually want to apply unary conversions *before* saving, except 5919 // in the special case of a C++ l-value conditional. 5920 if (!(getLangOpts().CPlusPlus 5921 && !commonExpr->isTypeDependent() 5922 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5923 && commonExpr->isGLValue() 5924 && commonExpr->isOrdinaryOrBitFieldObject() 5925 && RHSExpr->isOrdinaryOrBitFieldObject() 5926 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5927 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5928 if (commonRes.isInvalid()) 5929 return ExprError(); 5930 commonExpr = commonRes.take(); 5931 } 5932 5933 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5934 commonExpr->getType(), 5935 commonExpr->getValueKind(), 5936 commonExpr->getObjectKind(), 5937 commonExpr); 5938 LHSExpr = CondExpr = opaqueValue; 5939 } 5940 5941 ExprValueKind VK = VK_RValue; 5942 ExprObjectKind OK = OK_Ordinary; 5943 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5944 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5945 VK, OK, QuestionLoc); 5946 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5947 RHS.isInvalid()) 5948 return ExprError(); 5949 5950 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5951 RHS.get()); 5952 5953 if (!commonExpr) 5954 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5955 LHS.take(), ColonLoc, 5956 RHS.take(), result, VK, OK)); 5957 5958 return Owned(new (Context) 5959 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5960 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5961 OK)); 5962 } 5963 5964 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5965 // being closely modeled after the C99 spec:-). The odd characteristic of this 5966 // routine is it effectively iqnores the qualifiers on the top level pointee. 5967 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5968 // FIXME: add a couple examples in this comment. 5969 static Sema::AssignConvertType 5970 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5971 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5972 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5973 5974 // get the "pointed to" type (ignoring qualifiers at the top level) 5975 const Type *lhptee, *rhptee; 5976 Qualifiers lhq, rhq; 5977 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5978 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5979 5980 Sema::AssignConvertType ConvTy = Sema::Compatible; 5981 5982 // C99 6.5.16.1p1: This following citation is common to constraints 5983 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5984 // qualifiers of the type *pointed to* by the right; 5985 5986 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5987 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5988 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5989 // Ignore lifetime for further calculation. 5990 lhq.removeObjCLifetime(); 5991 rhq.removeObjCLifetime(); 5992 } 5993 5994 if (!lhq.compatiblyIncludes(rhq)) { 5995 // Treat address-space mismatches as fatal. TODO: address subspaces 5996 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5997 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5998 5999 // It's okay to add or remove GC or lifetime qualifiers when converting to 6000 // and from void*. 6001 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6002 .compatiblyIncludes( 6003 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6004 && (lhptee->isVoidType() || rhptee->isVoidType())) 6005 ; // keep old 6006 6007 // Treat lifetime mismatches as fatal. 6008 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6009 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6010 6011 // For GCC compatibility, other qualifier mismatches are treated 6012 // as still compatible in C. 6013 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6014 } 6015 6016 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6017 // incomplete type and the other is a pointer to a qualified or unqualified 6018 // version of void... 6019 if (lhptee->isVoidType()) { 6020 if (rhptee->isIncompleteOrObjectType()) 6021 return ConvTy; 6022 6023 // As an extension, we allow cast to/from void* to function pointer. 6024 assert(rhptee->isFunctionType()); 6025 return Sema::FunctionVoidPointer; 6026 } 6027 6028 if (rhptee->isVoidType()) { 6029 if (lhptee->isIncompleteOrObjectType()) 6030 return ConvTy; 6031 6032 // As an extension, we allow cast to/from void* to function pointer. 6033 assert(lhptee->isFunctionType()); 6034 return Sema::FunctionVoidPointer; 6035 } 6036 6037 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6038 // unqualified versions of compatible types, ... 6039 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6040 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6041 // Check if the pointee types are compatible ignoring the sign. 6042 // We explicitly check for char so that we catch "char" vs 6043 // "unsigned char" on systems where "char" is unsigned. 6044 if (lhptee->isCharType()) 6045 ltrans = S.Context.UnsignedCharTy; 6046 else if (lhptee->hasSignedIntegerRepresentation()) 6047 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6048 6049 if (rhptee->isCharType()) 6050 rtrans = S.Context.UnsignedCharTy; 6051 else if (rhptee->hasSignedIntegerRepresentation()) 6052 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6053 6054 if (ltrans == rtrans) { 6055 // Types are compatible ignoring the sign. Qualifier incompatibility 6056 // takes priority over sign incompatibility because the sign 6057 // warning can be disabled. 6058 if (ConvTy != Sema::Compatible) 6059 return ConvTy; 6060 6061 return Sema::IncompatiblePointerSign; 6062 } 6063 6064 // If we are a multi-level pointer, it's possible that our issue is simply 6065 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6066 // the eventual target type is the same and the pointers have the same 6067 // level of indirection, this must be the issue. 6068 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6069 do { 6070 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6071 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6072 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6073 6074 if (lhptee == rhptee) 6075 return Sema::IncompatibleNestedPointerQualifiers; 6076 } 6077 6078 // General pointer incompatibility takes priority over qualifiers. 6079 return Sema::IncompatiblePointer; 6080 } 6081 if (!S.getLangOpts().CPlusPlus && 6082 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6083 return Sema::IncompatiblePointer; 6084 return ConvTy; 6085 } 6086 6087 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6088 /// block pointer types are compatible or whether a block and normal pointer 6089 /// are compatible. It is more restrict than comparing two function pointer 6090 // types. 6091 static Sema::AssignConvertType 6092 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6093 QualType RHSType) { 6094 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6095 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6096 6097 QualType lhptee, rhptee; 6098 6099 // get the "pointed to" type (ignoring qualifiers at the top level) 6100 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6101 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6102 6103 // In C++, the types have to match exactly. 6104 if (S.getLangOpts().CPlusPlus) 6105 return Sema::IncompatibleBlockPointer; 6106 6107 Sema::AssignConvertType ConvTy = Sema::Compatible; 6108 6109 // For blocks we enforce that qualifiers are identical. 6110 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6111 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6112 6113 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6114 return Sema::IncompatibleBlockPointer; 6115 6116 return ConvTy; 6117 } 6118 6119 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6120 /// for assignment compatibility. 6121 static Sema::AssignConvertType 6122 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6123 QualType RHSType) { 6124 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6125 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6126 6127 if (LHSType->isObjCBuiltinType()) { 6128 // Class is not compatible with ObjC object pointers. 6129 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6130 !RHSType->isObjCQualifiedClassType()) 6131 return Sema::IncompatiblePointer; 6132 return Sema::Compatible; 6133 } 6134 if (RHSType->isObjCBuiltinType()) { 6135 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6136 !LHSType->isObjCQualifiedClassType()) 6137 return Sema::IncompatiblePointer; 6138 return Sema::Compatible; 6139 } 6140 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6141 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6142 6143 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6144 // make an exception for id<P> 6145 !LHSType->isObjCQualifiedIdType()) 6146 return Sema::CompatiblePointerDiscardsQualifiers; 6147 6148 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6149 return Sema::Compatible; 6150 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6151 return Sema::IncompatibleObjCQualifiedId; 6152 return Sema::IncompatiblePointer; 6153 } 6154 6155 Sema::AssignConvertType 6156 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6157 QualType LHSType, QualType RHSType) { 6158 // Fake up an opaque expression. We don't actually care about what 6159 // cast operations are required, so if CheckAssignmentConstraints 6160 // adds casts to this they'll be wasted, but fortunately that doesn't 6161 // usually happen on valid code. 6162 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6163 ExprResult RHSPtr = &RHSExpr; 6164 CastKind K = CK_Invalid; 6165 6166 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6167 } 6168 6169 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6170 /// has code to accommodate several GCC extensions when type checking 6171 /// pointers. Here are some objectionable examples that GCC considers warnings: 6172 /// 6173 /// int a, *pint; 6174 /// short *pshort; 6175 /// struct foo *pfoo; 6176 /// 6177 /// pint = pshort; // warning: assignment from incompatible pointer type 6178 /// a = pint; // warning: assignment makes integer from pointer without a cast 6179 /// pint = a; // warning: assignment makes pointer from integer without a cast 6180 /// pint = pfoo; // warning: assignment from incompatible pointer type 6181 /// 6182 /// As a result, the code for dealing with pointers is more complex than the 6183 /// C99 spec dictates. 6184 /// 6185 /// Sets 'Kind' for any result kind except Incompatible. 6186 Sema::AssignConvertType 6187 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6188 CastKind &Kind) { 6189 QualType RHSType = RHS.get()->getType(); 6190 QualType OrigLHSType = LHSType; 6191 6192 // Get canonical types. We're not formatting these types, just comparing 6193 // them. 6194 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6195 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6196 6197 // Common case: no conversion required. 6198 if (LHSType == RHSType) { 6199 Kind = CK_NoOp; 6200 return Compatible; 6201 } 6202 6203 // If we have an atomic type, try a non-atomic assignment, then just add an 6204 // atomic qualification step. 6205 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6206 Sema::AssignConvertType result = 6207 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6208 if (result != Compatible) 6209 return result; 6210 if (Kind != CK_NoOp) 6211 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 6212 Kind = CK_NonAtomicToAtomic; 6213 return Compatible; 6214 } 6215 6216 // If the left-hand side is a reference type, then we are in a 6217 // (rare!) case where we've allowed the use of references in C, 6218 // e.g., as a parameter type in a built-in function. In this case, 6219 // just make sure that the type referenced is compatible with the 6220 // right-hand side type. The caller is responsible for adjusting 6221 // LHSType so that the resulting expression does not have reference 6222 // type. 6223 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6224 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6225 Kind = CK_LValueBitCast; 6226 return Compatible; 6227 } 6228 return Incompatible; 6229 } 6230 6231 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6232 // to the same ExtVector type. 6233 if (LHSType->isExtVectorType()) { 6234 if (RHSType->isExtVectorType()) 6235 return Incompatible; 6236 if (RHSType->isArithmeticType()) { 6237 // CK_VectorSplat does T -> vector T, so first cast to the 6238 // element type. 6239 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6240 if (elType != RHSType) { 6241 Kind = PrepareScalarCast(RHS, elType); 6242 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 6243 } 6244 Kind = CK_VectorSplat; 6245 return Compatible; 6246 } 6247 } 6248 6249 // Conversions to or from vector type. 6250 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6251 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6252 // Allow assignments of an AltiVec vector type to an equivalent GCC 6253 // vector type and vice versa 6254 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6255 Kind = CK_BitCast; 6256 return Compatible; 6257 } 6258 6259 // If we are allowing lax vector conversions, and LHS and RHS are both 6260 // vectors, the total size only needs to be the same. This is a bitcast; 6261 // no bits are changed but the result type is different. 6262 if (isLaxVectorConversion(RHSType, LHSType)) { 6263 Kind = CK_BitCast; 6264 return IncompatibleVectors; 6265 } 6266 } 6267 return Incompatible; 6268 } 6269 6270 // Arithmetic conversions. 6271 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6272 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6273 Kind = PrepareScalarCast(RHS, LHSType); 6274 return Compatible; 6275 } 6276 6277 // Conversions to normal pointers. 6278 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6279 // U* -> T* 6280 if (isa<PointerType>(RHSType)) { 6281 Kind = CK_BitCast; 6282 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6283 } 6284 6285 // int -> T* 6286 if (RHSType->isIntegerType()) { 6287 Kind = CK_IntegralToPointer; // FIXME: null? 6288 return IntToPointer; 6289 } 6290 6291 // C pointers are not compatible with ObjC object pointers, 6292 // with two exceptions: 6293 if (isa<ObjCObjectPointerType>(RHSType)) { 6294 // - conversions to void* 6295 if (LHSPointer->getPointeeType()->isVoidType()) { 6296 Kind = CK_BitCast; 6297 return Compatible; 6298 } 6299 6300 // - conversions from 'Class' to the redefinition type 6301 if (RHSType->isObjCClassType() && 6302 Context.hasSameType(LHSType, 6303 Context.getObjCClassRedefinitionType())) { 6304 Kind = CK_BitCast; 6305 return Compatible; 6306 } 6307 6308 Kind = CK_BitCast; 6309 return IncompatiblePointer; 6310 } 6311 6312 // U^ -> void* 6313 if (RHSType->getAs<BlockPointerType>()) { 6314 if (LHSPointer->getPointeeType()->isVoidType()) { 6315 Kind = CK_BitCast; 6316 return Compatible; 6317 } 6318 } 6319 6320 return Incompatible; 6321 } 6322 6323 // Conversions to block pointers. 6324 if (isa<BlockPointerType>(LHSType)) { 6325 // U^ -> T^ 6326 if (RHSType->isBlockPointerType()) { 6327 Kind = CK_BitCast; 6328 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6329 } 6330 6331 // int or null -> T^ 6332 if (RHSType->isIntegerType()) { 6333 Kind = CK_IntegralToPointer; // FIXME: null 6334 return IntToBlockPointer; 6335 } 6336 6337 // id -> T^ 6338 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6339 Kind = CK_AnyPointerToBlockPointerCast; 6340 return Compatible; 6341 } 6342 6343 // void* -> T^ 6344 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6345 if (RHSPT->getPointeeType()->isVoidType()) { 6346 Kind = CK_AnyPointerToBlockPointerCast; 6347 return Compatible; 6348 } 6349 6350 return Incompatible; 6351 } 6352 6353 // Conversions to Objective-C pointers. 6354 if (isa<ObjCObjectPointerType>(LHSType)) { 6355 // A* -> B* 6356 if (RHSType->isObjCObjectPointerType()) { 6357 Kind = CK_BitCast; 6358 Sema::AssignConvertType result = 6359 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6360 if (getLangOpts().ObjCAutoRefCount && 6361 result == Compatible && 6362 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6363 result = IncompatibleObjCWeakRef; 6364 return result; 6365 } 6366 6367 // int or null -> A* 6368 if (RHSType->isIntegerType()) { 6369 Kind = CK_IntegralToPointer; // FIXME: null 6370 return IntToPointer; 6371 } 6372 6373 // In general, C pointers are not compatible with ObjC object pointers, 6374 // with two exceptions: 6375 if (isa<PointerType>(RHSType)) { 6376 Kind = CK_CPointerToObjCPointerCast; 6377 6378 // - conversions from 'void*' 6379 if (RHSType->isVoidPointerType()) { 6380 return Compatible; 6381 } 6382 6383 // - conversions to 'Class' from its redefinition type 6384 if (LHSType->isObjCClassType() && 6385 Context.hasSameType(RHSType, 6386 Context.getObjCClassRedefinitionType())) { 6387 return Compatible; 6388 } 6389 6390 return IncompatiblePointer; 6391 } 6392 6393 // T^ -> A* 6394 if (RHSType->isBlockPointerType()) { 6395 maybeExtendBlockObject(*this, RHS); 6396 Kind = CK_BlockPointerToObjCPointerCast; 6397 return Compatible; 6398 } 6399 6400 return Incompatible; 6401 } 6402 6403 // Conversions from pointers that are not covered by the above. 6404 if (isa<PointerType>(RHSType)) { 6405 // T* -> _Bool 6406 if (LHSType == Context.BoolTy) { 6407 Kind = CK_PointerToBoolean; 6408 return Compatible; 6409 } 6410 6411 // T* -> int 6412 if (LHSType->isIntegerType()) { 6413 Kind = CK_PointerToIntegral; 6414 return PointerToInt; 6415 } 6416 6417 return Incompatible; 6418 } 6419 6420 // Conversions from Objective-C pointers that are not covered by the above. 6421 if (isa<ObjCObjectPointerType>(RHSType)) { 6422 // T* -> _Bool 6423 if (LHSType == Context.BoolTy) { 6424 Kind = CK_PointerToBoolean; 6425 return Compatible; 6426 } 6427 6428 // T* -> int 6429 if (LHSType->isIntegerType()) { 6430 Kind = CK_PointerToIntegral; 6431 return PointerToInt; 6432 } 6433 6434 return Incompatible; 6435 } 6436 6437 // struct A -> struct B 6438 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6439 if (Context.typesAreCompatible(LHSType, RHSType)) { 6440 Kind = CK_NoOp; 6441 return Compatible; 6442 } 6443 } 6444 6445 return Incompatible; 6446 } 6447 6448 /// \brief Constructs a transparent union from an expression that is 6449 /// used to initialize the transparent union. 6450 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6451 ExprResult &EResult, QualType UnionType, 6452 FieldDecl *Field) { 6453 // Build an initializer list that designates the appropriate member 6454 // of the transparent union. 6455 Expr *E = EResult.take(); 6456 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6457 E, SourceLocation()); 6458 Initializer->setType(UnionType); 6459 Initializer->setInitializedFieldInUnion(Field); 6460 6461 // Build a compound literal constructing a value of the transparent 6462 // union type from this initializer list. 6463 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6464 EResult = S.Owned( 6465 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6466 VK_RValue, Initializer, false)); 6467 } 6468 6469 Sema::AssignConvertType 6470 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6471 ExprResult &RHS) { 6472 QualType RHSType = RHS.get()->getType(); 6473 6474 // If the ArgType is a Union type, we want to handle a potential 6475 // transparent_union GCC extension. 6476 const RecordType *UT = ArgType->getAsUnionType(); 6477 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6478 return Incompatible; 6479 6480 // The field to initialize within the transparent union. 6481 RecordDecl *UD = UT->getDecl(); 6482 FieldDecl *InitField = 0; 6483 // It's compatible if the expression matches any of the fields. 6484 for (RecordDecl::field_iterator it = UD->field_begin(), 6485 itend = UD->field_end(); 6486 it != itend; ++it) { 6487 if (it->getType()->isPointerType()) { 6488 // If the transparent union contains a pointer type, we allow: 6489 // 1) void pointer 6490 // 2) null pointer constant 6491 if (RHSType->isPointerType()) 6492 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6493 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6494 InitField = *it; 6495 break; 6496 } 6497 6498 if (RHS.get()->isNullPointerConstant(Context, 6499 Expr::NPC_ValueDependentIsNull)) { 6500 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6501 CK_NullToPointer); 6502 InitField = *it; 6503 break; 6504 } 6505 } 6506 6507 CastKind Kind = CK_Invalid; 6508 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6509 == Compatible) { 6510 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6511 InitField = *it; 6512 break; 6513 } 6514 } 6515 6516 if (!InitField) 6517 return Incompatible; 6518 6519 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6520 return Compatible; 6521 } 6522 6523 Sema::AssignConvertType 6524 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6525 bool Diagnose, 6526 bool DiagnoseCFAudited) { 6527 if (getLangOpts().CPlusPlus) { 6528 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6529 // C++ 5.17p3: If the left operand is not of class type, the 6530 // expression is implicitly converted (C++ 4) to the 6531 // cv-unqualified type of the left operand. 6532 ExprResult Res; 6533 if (Diagnose) { 6534 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6535 AA_Assigning); 6536 } else { 6537 ImplicitConversionSequence ICS = 6538 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6539 /*SuppressUserConversions=*/false, 6540 /*AllowExplicit=*/false, 6541 /*InOverloadResolution=*/false, 6542 /*CStyle=*/false, 6543 /*AllowObjCWritebackConversion=*/false); 6544 if (ICS.isFailure()) 6545 return Incompatible; 6546 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6547 ICS, AA_Assigning); 6548 } 6549 if (Res.isInvalid()) 6550 return Incompatible; 6551 Sema::AssignConvertType result = Compatible; 6552 if (getLangOpts().ObjCAutoRefCount && 6553 !CheckObjCARCUnavailableWeakConversion(LHSType, 6554 RHS.get()->getType())) 6555 result = IncompatibleObjCWeakRef; 6556 RHS = Res; 6557 return result; 6558 } 6559 6560 // FIXME: Currently, we fall through and treat C++ classes like C 6561 // structures. 6562 // FIXME: We also fall through for atomics; not sure what should 6563 // happen there, though. 6564 } 6565 6566 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6567 // a null pointer constant. 6568 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 6569 LHSType->isBlockPointerType()) && 6570 RHS.get()->isNullPointerConstant(Context, 6571 Expr::NPC_ValueDependentIsNull)) { 6572 CastKind Kind; 6573 CXXCastPath Path; 6574 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 6575 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path); 6576 return Compatible; 6577 } 6578 6579 // This check seems unnatural, however it is necessary to ensure the proper 6580 // conversion of functions/arrays. If the conversion were done for all 6581 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6582 // expressions that suppress this implicit conversion (&, sizeof). 6583 // 6584 // Suppress this for references: C++ 8.5.3p5. 6585 if (!LHSType->isReferenceType()) { 6586 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6587 if (RHS.isInvalid()) 6588 return Incompatible; 6589 } 6590 6591 CastKind Kind = CK_Invalid; 6592 Sema::AssignConvertType result = 6593 CheckAssignmentConstraints(LHSType, RHS, Kind); 6594 6595 // C99 6.5.16.1p2: The value of the right operand is converted to the 6596 // type of the assignment expression. 6597 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6598 // so that we can use references in built-in functions even in C. 6599 // The getNonReferenceType() call makes sure that the resulting expression 6600 // does not have reference type. 6601 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6602 QualType Ty = LHSType.getNonLValueExprType(Context); 6603 Expr *E = RHS.take(); 6604 if (getLangOpts().ObjCAutoRefCount) 6605 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6606 DiagnoseCFAudited); 6607 if (getLangOpts().ObjC1 && 6608 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 6609 LHSType, E->getType(), E) || 6610 ConversionToObjCStringLiteralCheck(LHSType, E))) { 6611 RHS = Owned(E); 6612 return Compatible; 6613 } 6614 6615 RHS = ImpCastExprToType(E, Ty, Kind); 6616 } 6617 return result; 6618 } 6619 6620 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6621 ExprResult &RHS) { 6622 Diag(Loc, diag::err_typecheck_invalid_operands) 6623 << LHS.get()->getType() << RHS.get()->getType() 6624 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6625 return QualType(); 6626 } 6627 6628 static bool breakDownVectorType(QualType type, uint64_t &len, 6629 QualType &eltType) { 6630 // Vectors are simple. 6631 if (const VectorType *vecType = type->getAs<VectorType>()) { 6632 len = vecType->getNumElements(); 6633 eltType = vecType->getElementType(); 6634 assert(eltType->isScalarType()); 6635 return true; 6636 } 6637 6638 // We allow lax conversion to and from non-vector types, but only if 6639 // they're real types (i.e. non-complex, non-pointer scalar types). 6640 if (!type->isRealType()) return false; 6641 6642 len = 1; 6643 eltType = type; 6644 return true; 6645 } 6646 6647 /// Is this a legal conversion between two known vector types? 6648 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6649 assert(destTy->isVectorType() || srcTy->isVectorType()); 6650 6651 if (!Context.getLangOpts().LaxVectorConversions) 6652 return false; 6653 6654 uint64_t srcLen, destLen; 6655 QualType srcElt, destElt; 6656 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 6657 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 6658 6659 // ASTContext::getTypeSize will return the size rounded up to a 6660 // power of 2, so instead of using that, we need to use the raw 6661 // element size multiplied by the element count. 6662 uint64_t srcEltSize = Context.getTypeSize(srcElt); 6663 uint64_t destEltSize = Context.getTypeSize(destElt); 6664 6665 return (srcLen * srcEltSize == destLen * destEltSize); 6666 } 6667 6668 /// Try to convert a value of non-vector type to a vector type by 6669 /// promoting (and only promoting) the type to the element type of the 6670 /// vector and then performing a vector splat. 6671 /// 6672 /// \param scalar - if non-null, actually perform the conversions 6673 /// \return true if the operation fails (but without diagnosing the failure) 6674 static bool tryVectorPromoteAndSplat(Sema &S, ExprResult *scalar, 6675 QualType scalarTy, 6676 QualType vectorEltTy, 6677 QualType vectorTy) { 6678 // The conversion to apply to the scalar before splatting it, 6679 // if necessary. 6680 CastKind scalarCast = CK_Invalid; 6681 6682 if (vectorEltTy->isIntegralType(S.Context)) { 6683 if (!scalarTy->isIntegralType(S.Context)) return true; 6684 int order = S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy); 6685 if (order < 0) return true; 6686 if (order > 0) scalarCast = CK_IntegralCast; 6687 } else if (vectorEltTy->isRealFloatingType()) { 6688 if (scalarTy->isRealFloatingType()) { 6689 int order = S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy); 6690 if (order < 0) return true; 6691 if (order > 0) scalarCast = CK_FloatingCast; 6692 } else if (scalarTy->isIntegralType(S.Context)) { 6693 scalarCast = CK_IntegralToFloating; 6694 } else { 6695 return true; 6696 } 6697 } else { 6698 return true; 6699 } 6700 6701 // Adjust scalar if desired. 6702 if (scalar) { 6703 if (scalarCast != CK_Invalid) 6704 *scalar = S.ImpCastExprToType(scalar->take(), vectorEltTy, scalarCast); 6705 *scalar = S.ImpCastExprToType(scalar->take(), vectorTy, CK_VectorSplat); 6706 } 6707 return false; 6708 } 6709 6710 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6711 SourceLocation Loc, bool IsCompAssign) { 6712 if (!IsCompAssign) { 6713 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6714 if (LHS.isInvalid()) 6715 return QualType(); 6716 } 6717 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6718 if (RHS.isInvalid()) 6719 return QualType(); 6720 6721 // For conversion purposes, we ignore any qualifiers. 6722 // For example, "const float" and "float" are equivalent. 6723 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 6724 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 6725 6726 // If the vector types are identical, return. 6727 if (Context.hasSameType(LHSType, RHSType)) 6728 return LHSType; 6729 6730 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 6731 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 6732 assert(LHSVecType || RHSVecType); 6733 6734 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 6735 if (LHSVecType && RHSVecType && 6736 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6737 if (isa<ExtVectorType>(LHSVecType)) { 6738 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6739 return LHSType; 6740 } 6741 6742 if (!IsCompAssign) 6743 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6744 return RHSType; 6745 } 6746 6747 // If we're allowing lax vector conversions, only the total (data) size 6748 // needs to be the same. 6749 // FIXME: Should we really be allowing this? 6750 // FIXME: We really just pick the LHS type arbitrarily? 6751 if (isLaxVectorConversion(RHSType, LHSType)) { 6752 QualType resultType = LHSType; 6753 RHS = ImpCastExprToType(RHS.take(), resultType, CK_BitCast); 6754 return resultType; 6755 } 6756 6757 // If there's an ext-vector type and a scalar, try to promote (and 6758 // only promote) and splat the scalar to the vector type. 6759 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 6760 if (!tryVectorPromoteAndSplat(*this, &RHS, RHSType, 6761 LHSVecType->getElementType(), LHSType)) 6762 return LHSType; 6763 } 6764 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 6765 if (!tryVectorPromoteAndSplat(*this, (IsCompAssign ? 0 : &LHS), LHSType, 6766 RHSVecType->getElementType(), RHSType)) 6767 return RHSType; 6768 } 6769 6770 // Okay, the expression is invalid. 6771 6772 // If there's a non-vector, non-real operand, diagnose that. 6773 if ((!RHSVecType && !RHSType->isRealType()) || 6774 (!LHSVecType && !LHSType->isRealType())) { 6775 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 6776 << LHSType << RHSType 6777 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6778 return QualType(); 6779 } 6780 6781 // Otherwise, use the generic diagnostic. 6782 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6783 << LHSType << RHSType 6784 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6785 return QualType(); 6786 } 6787 6788 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6789 // expression. These are mainly cases where the null pointer is used as an 6790 // integer instead of a pointer. 6791 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6792 SourceLocation Loc, bool IsCompare) { 6793 // The canonical way to check for a GNU null is with isNullPointerConstant, 6794 // but we use a bit of a hack here for speed; this is a relatively 6795 // hot path, and isNullPointerConstant is slow. 6796 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6797 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6798 6799 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6800 6801 // Avoid analyzing cases where the result will either be invalid (and 6802 // diagnosed as such) or entirely valid and not something to warn about. 6803 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6804 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6805 return; 6806 6807 // Comparison operations would not make sense with a null pointer no matter 6808 // what the other expression is. 6809 if (!IsCompare) { 6810 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6811 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6812 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6813 return; 6814 } 6815 6816 // The rest of the operations only make sense with a null pointer 6817 // if the other expression is a pointer. 6818 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6819 NonNullType->canDecayToPointerType()) 6820 return; 6821 6822 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6823 << LHSNull /* LHS is NULL */ << NonNullType 6824 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6825 } 6826 6827 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6828 SourceLocation Loc, 6829 bool IsCompAssign, bool IsDiv) { 6830 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6831 6832 if (LHS.get()->getType()->isVectorType() || 6833 RHS.get()->getType()->isVectorType()) 6834 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6835 6836 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6837 if (LHS.isInvalid() || RHS.isInvalid()) 6838 return QualType(); 6839 6840 6841 if (compType.isNull() || !compType->isArithmeticType()) 6842 return InvalidOperands(Loc, LHS, RHS); 6843 6844 // Check for division by zero. 6845 llvm::APSInt RHSValue; 6846 if (IsDiv && !RHS.get()->isValueDependent() && 6847 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6848 DiagRuntimeBehavior(Loc, RHS.get(), 6849 PDiag(diag::warn_division_by_zero) 6850 << RHS.get()->getSourceRange()); 6851 6852 return compType; 6853 } 6854 6855 QualType Sema::CheckRemainderOperands( 6856 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6857 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6858 6859 if (LHS.get()->getType()->isVectorType() || 6860 RHS.get()->getType()->isVectorType()) { 6861 if (LHS.get()->getType()->hasIntegerRepresentation() && 6862 RHS.get()->getType()->hasIntegerRepresentation()) 6863 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6864 return InvalidOperands(Loc, LHS, RHS); 6865 } 6866 6867 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6868 if (LHS.isInvalid() || RHS.isInvalid()) 6869 return QualType(); 6870 6871 if (compType.isNull() || !compType->isIntegerType()) 6872 return InvalidOperands(Loc, LHS, RHS); 6873 6874 // Check for remainder by zero. 6875 llvm::APSInt RHSValue; 6876 if (!RHS.get()->isValueDependent() && 6877 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6878 DiagRuntimeBehavior(Loc, RHS.get(), 6879 PDiag(diag::warn_remainder_by_zero) 6880 << RHS.get()->getSourceRange()); 6881 6882 return compType; 6883 } 6884 6885 /// \brief Diagnose invalid arithmetic on two void pointers. 6886 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6887 Expr *LHSExpr, Expr *RHSExpr) { 6888 S.Diag(Loc, S.getLangOpts().CPlusPlus 6889 ? diag::err_typecheck_pointer_arith_void_type 6890 : diag::ext_gnu_void_ptr) 6891 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6892 << RHSExpr->getSourceRange(); 6893 } 6894 6895 /// \brief Diagnose invalid arithmetic on a void pointer. 6896 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6897 Expr *Pointer) { 6898 S.Diag(Loc, S.getLangOpts().CPlusPlus 6899 ? diag::err_typecheck_pointer_arith_void_type 6900 : diag::ext_gnu_void_ptr) 6901 << 0 /* one pointer */ << Pointer->getSourceRange(); 6902 } 6903 6904 /// \brief Diagnose invalid arithmetic on two function pointers. 6905 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6906 Expr *LHS, Expr *RHS) { 6907 assert(LHS->getType()->isAnyPointerType()); 6908 assert(RHS->getType()->isAnyPointerType()); 6909 S.Diag(Loc, S.getLangOpts().CPlusPlus 6910 ? diag::err_typecheck_pointer_arith_function_type 6911 : diag::ext_gnu_ptr_func_arith) 6912 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6913 // We only show the second type if it differs from the first. 6914 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6915 RHS->getType()) 6916 << RHS->getType()->getPointeeType() 6917 << LHS->getSourceRange() << RHS->getSourceRange(); 6918 } 6919 6920 /// \brief Diagnose invalid arithmetic on a function pointer. 6921 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6922 Expr *Pointer) { 6923 assert(Pointer->getType()->isAnyPointerType()); 6924 S.Diag(Loc, S.getLangOpts().CPlusPlus 6925 ? diag::err_typecheck_pointer_arith_function_type 6926 : diag::ext_gnu_ptr_func_arith) 6927 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6928 << 0 /* one pointer, so only one type */ 6929 << Pointer->getSourceRange(); 6930 } 6931 6932 /// \brief Emit error if Operand is incomplete pointer type 6933 /// 6934 /// \returns True if pointer has incomplete type 6935 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6936 Expr *Operand) { 6937 assert(Operand->getType()->isAnyPointerType() && 6938 !Operand->getType()->isDependentType()); 6939 QualType PointeeTy = Operand->getType()->getPointeeType(); 6940 return S.RequireCompleteType(Loc, PointeeTy, 6941 diag::err_typecheck_arithmetic_incomplete_type, 6942 PointeeTy, Operand->getSourceRange()); 6943 } 6944 6945 /// \brief Check the validity of an arithmetic pointer operand. 6946 /// 6947 /// If the operand has pointer type, this code will check for pointer types 6948 /// which are invalid in arithmetic operations. These will be diagnosed 6949 /// appropriately, including whether or not the use is supported as an 6950 /// extension. 6951 /// 6952 /// \returns True when the operand is valid to use (even if as an extension). 6953 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6954 Expr *Operand) { 6955 if (!Operand->getType()->isAnyPointerType()) return true; 6956 6957 QualType PointeeTy = Operand->getType()->getPointeeType(); 6958 if (PointeeTy->isVoidType()) { 6959 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6960 return !S.getLangOpts().CPlusPlus; 6961 } 6962 if (PointeeTy->isFunctionType()) { 6963 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6964 return !S.getLangOpts().CPlusPlus; 6965 } 6966 6967 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6968 6969 return true; 6970 } 6971 6972 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6973 /// operands. 6974 /// 6975 /// This routine will diagnose any invalid arithmetic on pointer operands much 6976 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 6977 /// for emitting a single diagnostic even for operations where both LHS and RHS 6978 /// are (potentially problematic) pointers. 6979 /// 6980 /// \returns True when the operand is valid to use (even if as an extension). 6981 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6982 Expr *LHSExpr, Expr *RHSExpr) { 6983 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6984 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6985 if (!isLHSPointer && !isRHSPointer) return true; 6986 6987 QualType LHSPointeeTy, RHSPointeeTy; 6988 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6989 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6990 6991 // Check for arithmetic on pointers to incomplete types. 6992 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6993 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6994 if (isLHSVoidPtr || isRHSVoidPtr) { 6995 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6996 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6997 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6998 6999 return !S.getLangOpts().CPlusPlus; 7000 } 7001 7002 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7003 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7004 if (isLHSFuncPtr || isRHSFuncPtr) { 7005 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7006 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7007 RHSExpr); 7008 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7009 7010 return !S.getLangOpts().CPlusPlus; 7011 } 7012 7013 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7014 return false; 7015 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7016 return false; 7017 7018 return true; 7019 } 7020 7021 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7022 /// literal. 7023 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7024 Expr *LHSExpr, Expr *RHSExpr) { 7025 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7026 Expr* IndexExpr = RHSExpr; 7027 if (!StrExpr) { 7028 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7029 IndexExpr = LHSExpr; 7030 } 7031 7032 bool IsStringPlusInt = StrExpr && 7033 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7034 if (!IsStringPlusInt) 7035 return; 7036 7037 llvm::APSInt index; 7038 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7039 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7040 if (index.isNonNegative() && 7041 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7042 index.isUnsigned())) 7043 return; 7044 } 7045 7046 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7047 Self.Diag(OpLoc, diag::warn_string_plus_int) 7048 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7049 7050 // Only print a fixit for "str" + int, not for int + "str". 7051 if (IndexExpr == RHSExpr) { 7052 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7053 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7054 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7055 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7056 << FixItHint::CreateInsertion(EndLoc, "]"); 7057 } else 7058 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7059 } 7060 7061 /// \brief Emit a warning when adding a char literal to a string. 7062 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7063 Expr *LHSExpr, Expr *RHSExpr) { 7064 const DeclRefExpr *StringRefExpr = 7065 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts()); 7066 const CharacterLiteral *CharExpr = 7067 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7068 if (!StringRefExpr) { 7069 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts()); 7070 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7071 } 7072 7073 if (!CharExpr || !StringRefExpr) 7074 return; 7075 7076 const QualType StringType = StringRefExpr->getType(); 7077 7078 // Return if not a PointerType. 7079 if (!StringType->isAnyPointerType()) 7080 return; 7081 7082 // Return if not a CharacterType. 7083 if (!StringType->getPointeeType()->isAnyCharacterType()) 7084 return; 7085 7086 ASTContext &Ctx = Self.getASTContext(); 7087 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7088 7089 const QualType CharType = CharExpr->getType(); 7090 if (!CharType->isAnyCharacterType() && 7091 CharType->isIntegerType() && 7092 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7093 Self.Diag(OpLoc, diag::warn_string_plus_char) 7094 << DiagRange << Ctx.CharTy; 7095 } else { 7096 Self.Diag(OpLoc, diag::warn_string_plus_char) 7097 << DiagRange << CharExpr->getType(); 7098 } 7099 7100 // Only print a fixit for str + char, not for char + str. 7101 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7102 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7103 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7104 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7105 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7106 << FixItHint::CreateInsertion(EndLoc, "]"); 7107 } else { 7108 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7109 } 7110 } 7111 7112 /// \brief Emit error when two pointers are incompatible. 7113 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7114 Expr *LHSExpr, Expr *RHSExpr) { 7115 assert(LHSExpr->getType()->isAnyPointerType()); 7116 assert(RHSExpr->getType()->isAnyPointerType()); 7117 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7118 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7119 << RHSExpr->getSourceRange(); 7120 } 7121 7122 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7123 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7124 QualType* CompLHSTy) { 7125 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7126 7127 if (LHS.get()->getType()->isVectorType() || 7128 RHS.get()->getType()->isVectorType()) { 7129 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7130 if (CompLHSTy) *CompLHSTy = compType; 7131 return compType; 7132 } 7133 7134 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7135 if (LHS.isInvalid() || RHS.isInvalid()) 7136 return QualType(); 7137 7138 // Diagnose "string literal" '+' int and string '+' "char literal". 7139 if (Opc == BO_Add) { 7140 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7141 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7142 } 7143 7144 // handle the common case first (both operands are arithmetic). 7145 if (!compType.isNull() && compType->isArithmeticType()) { 7146 if (CompLHSTy) *CompLHSTy = compType; 7147 return compType; 7148 } 7149 7150 // Type-checking. Ultimately the pointer's going to be in PExp; 7151 // note that we bias towards the LHS being the pointer. 7152 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7153 7154 bool isObjCPointer; 7155 if (PExp->getType()->isPointerType()) { 7156 isObjCPointer = false; 7157 } else if (PExp->getType()->isObjCObjectPointerType()) { 7158 isObjCPointer = true; 7159 } else { 7160 std::swap(PExp, IExp); 7161 if (PExp->getType()->isPointerType()) { 7162 isObjCPointer = false; 7163 } else if (PExp->getType()->isObjCObjectPointerType()) { 7164 isObjCPointer = true; 7165 } else { 7166 return InvalidOperands(Loc, LHS, RHS); 7167 } 7168 } 7169 assert(PExp->getType()->isAnyPointerType()); 7170 7171 if (!IExp->getType()->isIntegerType()) 7172 return InvalidOperands(Loc, LHS, RHS); 7173 7174 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7175 return QualType(); 7176 7177 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7178 return QualType(); 7179 7180 // Check array bounds for pointer arithemtic 7181 CheckArrayAccess(PExp, IExp); 7182 7183 if (CompLHSTy) { 7184 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7185 if (LHSTy.isNull()) { 7186 LHSTy = LHS.get()->getType(); 7187 if (LHSTy->isPromotableIntegerType()) 7188 LHSTy = Context.getPromotedIntegerType(LHSTy); 7189 } 7190 *CompLHSTy = LHSTy; 7191 } 7192 7193 return PExp->getType(); 7194 } 7195 7196 // C99 6.5.6 7197 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7198 SourceLocation Loc, 7199 QualType* CompLHSTy) { 7200 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7201 7202 if (LHS.get()->getType()->isVectorType() || 7203 RHS.get()->getType()->isVectorType()) { 7204 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7205 if (CompLHSTy) *CompLHSTy = compType; 7206 return compType; 7207 } 7208 7209 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7210 if (LHS.isInvalid() || RHS.isInvalid()) 7211 return QualType(); 7212 7213 // Enforce type constraints: C99 6.5.6p3. 7214 7215 // Handle the common case first (both operands are arithmetic). 7216 if (!compType.isNull() && compType->isArithmeticType()) { 7217 if (CompLHSTy) *CompLHSTy = compType; 7218 return compType; 7219 } 7220 7221 // Either ptr - int or ptr - ptr. 7222 if (LHS.get()->getType()->isAnyPointerType()) { 7223 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7224 7225 // Diagnose bad cases where we step over interface counts. 7226 if (LHS.get()->getType()->isObjCObjectPointerType() && 7227 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7228 return QualType(); 7229 7230 // The result type of a pointer-int computation is the pointer type. 7231 if (RHS.get()->getType()->isIntegerType()) { 7232 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7233 return QualType(); 7234 7235 // Check array bounds for pointer arithemtic 7236 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 7237 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7238 7239 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7240 return LHS.get()->getType(); 7241 } 7242 7243 // Handle pointer-pointer subtractions. 7244 if (const PointerType *RHSPTy 7245 = RHS.get()->getType()->getAs<PointerType>()) { 7246 QualType rpointee = RHSPTy->getPointeeType(); 7247 7248 if (getLangOpts().CPlusPlus) { 7249 // Pointee types must be the same: C++ [expr.add] 7250 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7251 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7252 } 7253 } else { 7254 // Pointee types must be compatible C99 6.5.6p3 7255 if (!Context.typesAreCompatible( 7256 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7257 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7258 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7259 return QualType(); 7260 } 7261 } 7262 7263 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7264 LHS.get(), RHS.get())) 7265 return QualType(); 7266 7267 // The pointee type may have zero size. As an extension, a structure or 7268 // union may have zero size or an array may have zero length. In this 7269 // case subtraction does not make sense. 7270 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7271 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7272 if (ElementSize.isZero()) { 7273 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7274 << rpointee.getUnqualifiedType() 7275 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7276 } 7277 } 7278 7279 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7280 return Context.getPointerDiffType(); 7281 } 7282 } 7283 7284 return InvalidOperands(Loc, LHS, RHS); 7285 } 7286 7287 static bool isScopedEnumerationType(QualType T) { 7288 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7289 return ET->getDecl()->isScoped(); 7290 return false; 7291 } 7292 7293 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7294 SourceLocation Loc, unsigned Opc, 7295 QualType LHSType) { 7296 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7297 // so skip remaining warnings as we don't want to modify values within Sema. 7298 if (S.getLangOpts().OpenCL) 7299 return; 7300 7301 llvm::APSInt Right; 7302 // Check right/shifter operand 7303 if (RHS.get()->isValueDependent() || 7304 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7305 return; 7306 7307 if (Right.isNegative()) { 7308 S.DiagRuntimeBehavior(Loc, RHS.get(), 7309 S.PDiag(diag::warn_shift_negative) 7310 << RHS.get()->getSourceRange()); 7311 return; 7312 } 7313 llvm::APInt LeftBits(Right.getBitWidth(), 7314 S.Context.getTypeSize(LHS.get()->getType())); 7315 if (Right.uge(LeftBits)) { 7316 S.DiagRuntimeBehavior(Loc, RHS.get(), 7317 S.PDiag(diag::warn_shift_gt_typewidth) 7318 << RHS.get()->getSourceRange()); 7319 return; 7320 } 7321 if (Opc != BO_Shl) 7322 return; 7323 7324 // When left shifting an ICE which is signed, we can check for overflow which 7325 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7326 // integers have defined behavior modulo one more than the maximum value 7327 // representable in the result type, so never warn for those. 7328 llvm::APSInt Left; 7329 if (LHS.get()->isValueDependent() || 7330 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7331 LHSType->hasUnsignedIntegerRepresentation()) 7332 return; 7333 llvm::APInt ResultBits = 7334 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7335 if (LeftBits.uge(ResultBits)) 7336 return; 7337 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7338 Result = Result.shl(Right); 7339 7340 // Print the bit representation of the signed integer as an unsigned 7341 // hexadecimal number. 7342 SmallString<40> HexResult; 7343 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7344 7345 // If we are only missing a sign bit, this is less likely to result in actual 7346 // bugs -- if the result is cast back to an unsigned type, it will have the 7347 // expected value. Thus we place this behind a different warning that can be 7348 // turned off separately if needed. 7349 if (LeftBits == ResultBits - 1) { 7350 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7351 << HexResult.str() << LHSType 7352 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7353 return; 7354 } 7355 7356 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7357 << HexResult.str() << Result.getMinSignedBits() << LHSType 7358 << Left.getBitWidth() << LHS.get()->getSourceRange() 7359 << RHS.get()->getSourceRange(); 7360 } 7361 7362 // C99 6.5.7 7363 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7364 SourceLocation Loc, unsigned Opc, 7365 bool IsCompAssign) { 7366 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7367 7368 // Vector shifts promote their scalar inputs to vector type. 7369 if (LHS.get()->getType()->isVectorType() || 7370 RHS.get()->getType()->isVectorType()) 7371 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7372 7373 // Shifts don't perform usual arithmetic conversions, they just do integer 7374 // promotions on each operand. C99 6.5.7p3 7375 7376 // For the LHS, do usual unary conversions, but then reset them away 7377 // if this is a compound assignment. 7378 ExprResult OldLHS = LHS; 7379 LHS = UsualUnaryConversions(LHS.take()); 7380 if (LHS.isInvalid()) 7381 return QualType(); 7382 QualType LHSType = LHS.get()->getType(); 7383 if (IsCompAssign) LHS = OldLHS; 7384 7385 // The RHS is simpler. 7386 RHS = UsualUnaryConversions(RHS.take()); 7387 if (RHS.isInvalid()) 7388 return QualType(); 7389 QualType RHSType = RHS.get()->getType(); 7390 7391 // C99 6.5.7p2: Each of the operands shall have integer type. 7392 if (!LHSType->hasIntegerRepresentation() || 7393 !RHSType->hasIntegerRepresentation()) 7394 return InvalidOperands(Loc, LHS, RHS); 7395 7396 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7397 // hasIntegerRepresentation() above instead of this. 7398 if (isScopedEnumerationType(LHSType) || 7399 isScopedEnumerationType(RHSType)) { 7400 return InvalidOperands(Loc, LHS, RHS); 7401 } 7402 // Sanity-check shift operands 7403 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7404 7405 // "The type of the result is that of the promoted left operand." 7406 return LHSType; 7407 } 7408 7409 static bool IsWithinTemplateSpecialization(Decl *D) { 7410 if (DeclContext *DC = D->getDeclContext()) { 7411 if (isa<ClassTemplateSpecializationDecl>(DC)) 7412 return true; 7413 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7414 return FD->isFunctionTemplateSpecialization(); 7415 } 7416 return false; 7417 } 7418 7419 /// If two different enums are compared, raise a warning. 7420 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7421 Expr *RHS) { 7422 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7423 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7424 7425 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7426 if (!LHSEnumType) 7427 return; 7428 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7429 if (!RHSEnumType) 7430 return; 7431 7432 // Ignore anonymous enums. 7433 if (!LHSEnumType->getDecl()->getIdentifier()) 7434 return; 7435 if (!RHSEnumType->getDecl()->getIdentifier()) 7436 return; 7437 7438 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7439 return; 7440 7441 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7442 << LHSStrippedType << RHSStrippedType 7443 << LHS->getSourceRange() << RHS->getSourceRange(); 7444 } 7445 7446 /// \brief Diagnose bad pointer comparisons. 7447 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7448 ExprResult &LHS, ExprResult &RHS, 7449 bool IsError) { 7450 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7451 : diag::ext_typecheck_comparison_of_distinct_pointers) 7452 << LHS.get()->getType() << RHS.get()->getType() 7453 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7454 } 7455 7456 /// \brief Returns false if the pointers are converted to a composite type, 7457 /// true otherwise. 7458 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7459 ExprResult &LHS, ExprResult &RHS) { 7460 // C++ [expr.rel]p2: 7461 // [...] Pointer conversions (4.10) and qualification 7462 // conversions (4.4) are performed on pointer operands (or on 7463 // a pointer operand and a null pointer constant) to bring 7464 // them to their composite pointer type. [...] 7465 // 7466 // C++ [expr.eq]p1 uses the same notion for (in)equality 7467 // comparisons of pointers. 7468 7469 // C++ [expr.eq]p2: 7470 // In addition, pointers to members can be compared, or a pointer to 7471 // member and a null pointer constant. Pointer to member conversions 7472 // (4.11) and qualification conversions (4.4) are performed to bring 7473 // them to a common type. If one operand is a null pointer constant, 7474 // the common type is the type of the other operand. Otherwise, the 7475 // common type is a pointer to member type similar (4.4) to the type 7476 // of one of the operands, with a cv-qualification signature (4.4) 7477 // that is the union of the cv-qualification signatures of the operand 7478 // types. 7479 7480 QualType LHSType = LHS.get()->getType(); 7481 QualType RHSType = RHS.get()->getType(); 7482 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7483 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7484 7485 bool NonStandardCompositeType = false; 7486 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7487 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7488 if (T.isNull()) { 7489 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7490 return true; 7491 } 7492 7493 if (NonStandardCompositeType) 7494 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7495 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7496 << RHS.get()->getSourceRange(); 7497 7498 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7499 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7500 return false; 7501 } 7502 7503 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7504 ExprResult &LHS, 7505 ExprResult &RHS, 7506 bool IsError) { 7507 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7508 : diag::ext_typecheck_comparison_of_fptr_to_void) 7509 << LHS.get()->getType() << RHS.get()->getType() 7510 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7511 } 7512 7513 static bool isObjCObjectLiteral(ExprResult &E) { 7514 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7515 case Stmt::ObjCArrayLiteralClass: 7516 case Stmt::ObjCDictionaryLiteralClass: 7517 case Stmt::ObjCStringLiteralClass: 7518 case Stmt::ObjCBoxedExprClass: 7519 return true; 7520 default: 7521 // Note that ObjCBoolLiteral is NOT an object literal! 7522 return false; 7523 } 7524 } 7525 7526 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7527 const ObjCObjectPointerType *Type = 7528 LHS->getType()->getAs<ObjCObjectPointerType>(); 7529 7530 // If this is not actually an Objective-C object, bail out. 7531 if (!Type) 7532 return false; 7533 7534 // Get the LHS object's interface type. 7535 QualType InterfaceType = Type->getPointeeType(); 7536 if (const ObjCObjectType *iQFaceTy = 7537 InterfaceType->getAsObjCQualifiedInterfaceType()) 7538 InterfaceType = iQFaceTy->getBaseType(); 7539 7540 // If the RHS isn't an Objective-C object, bail out. 7541 if (!RHS->getType()->isObjCObjectPointerType()) 7542 return false; 7543 7544 // Try to find the -isEqual: method. 7545 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7546 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7547 InterfaceType, 7548 /*instance=*/true); 7549 if (!Method) { 7550 if (Type->isObjCIdType()) { 7551 // For 'id', just check the global pool. 7552 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7553 /*receiverId=*/true, 7554 /*warn=*/false); 7555 } else { 7556 // Check protocols. 7557 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7558 /*instance=*/true); 7559 } 7560 } 7561 7562 if (!Method) 7563 return false; 7564 7565 QualType T = Method->param_begin()[0]->getType(); 7566 if (!T->isObjCObjectPointerType()) 7567 return false; 7568 7569 QualType R = Method->getReturnType(); 7570 if (!R->isScalarType()) 7571 return false; 7572 7573 return true; 7574 } 7575 7576 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7577 FromE = FromE->IgnoreParenImpCasts(); 7578 switch (FromE->getStmtClass()) { 7579 default: 7580 break; 7581 case Stmt::ObjCStringLiteralClass: 7582 // "string literal" 7583 return LK_String; 7584 case Stmt::ObjCArrayLiteralClass: 7585 // "array literal" 7586 return LK_Array; 7587 case Stmt::ObjCDictionaryLiteralClass: 7588 // "dictionary literal" 7589 return LK_Dictionary; 7590 case Stmt::BlockExprClass: 7591 return LK_Block; 7592 case Stmt::ObjCBoxedExprClass: { 7593 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7594 switch (Inner->getStmtClass()) { 7595 case Stmt::IntegerLiteralClass: 7596 case Stmt::FloatingLiteralClass: 7597 case Stmt::CharacterLiteralClass: 7598 case Stmt::ObjCBoolLiteralExprClass: 7599 case Stmt::CXXBoolLiteralExprClass: 7600 // "numeric literal" 7601 return LK_Numeric; 7602 case Stmt::ImplicitCastExprClass: { 7603 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7604 // Boolean literals can be represented by implicit casts. 7605 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7606 return LK_Numeric; 7607 break; 7608 } 7609 default: 7610 break; 7611 } 7612 return LK_Boxed; 7613 } 7614 } 7615 return LK_None; 7616 } 7617 7618 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7619 ExprResult &LHS, ExprResult &RHS, 7620 BinaryOperator::Opcode Opc){ 7621 Expr *Literal; 7622 Expr *Other; 7623 if (isObjCObjectLiteral(LHS)) { 7624 Literal = LHS.get(); 7625 Other = RHS.get(); 7626 } else { 7627 Literal = RHS.get(); 7628 Other = LHS.get(); 7629 } 7630 7631 // Don't warn on comparisons against nil. 7632 Other = Other->IgnoreParenCasts(); 7633 if (Other->isNullPointerConstant(S.getASTContext(), 7634 Expr::NPC_ValueDependentIsNotNull)) 7635 return; 7636 7637 // This should be kept in sync with warn_objc_literal_comparison. 7638 // LK_String should always be after the other literals, since it has its own 7639 // warning flag. 7640 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7641 assert(LiteralKind != Sema::LK_Block); 7642 if (LiteralKind == Sema::LK_None) { 7643 llvm_unreachable("Unknown Objective-C object literal kind"); 7644 } 7645 7646 if (LiteralKind == Sema::LK_String) 7647 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7648 << Literal->getSourceRange(); 7649 else 7650 S.Diag(Loc, diag::warn_objc_literal_comparison) 7651 << LiteralKind << Literal->getSourceRange(); 7652 7653 if (BinaryOperator::isEqualityOp(Opc) && 7654 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7655 SourceLocation Start = LHS.get()->getLocStart(); 7656 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7657 CharSourceRange OpRange = 7658 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7659 7660 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7661 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7662 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7663 << FixItHint::CreateInsertion(End, "]"); 7664 } 7665 } 7666 7667 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7668 ExprResult &RHS, 7669 SourceLocation Loc, 7670 unsigned OpaqueOpc) { 7671 // This checking requires bools. 7672 if (!S.getLangOpts().Bool) return; 7673 7674 // Check that left hand side is !something. 7675 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7676 if (!UO || UO->getOpcode() != UO_LNot) return; 7677 7678 // Only check if the right hand side is non-bool arithmetic type. 7679 if (RHS.get()->getType()->isBooleanType()) return; 7680 7681 // Make sure that the something in !something is not bool. 7682 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7683 if (SubExpr->getType()->isBooleanType()) return; 7684 7685 // Emit warning. 7686 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7687 << Loc; 7688 7689 // First note suggest !(x < y) 7690 SourceLocation FirstOpen = SubExpr->getLocStart(); 7691 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7692 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7693 if (FirstClose.isInvalid()) 7694 FirstOpen = SourceLocation(); 7695 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7696 << FixItHint::CreateInsertion(FirstOpen, "(") 7697 << FixItHint::CreateInsertion(FirstClose, ")"); 7698 7699 // Second note suggests (!x) < y 7700 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7701 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7702 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7703 if (SecondClose.isInvalid()) 7704 SecondOpen = SourceLocation(); 7705 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7706 << FixItHint::CreateInsertion(SecondOpen, "(") 7707 << FixItHint::CreateInsertion(SecondClose, ")"); 7708 } 7709 7710 // Get the decl for a simple expression: a reference to a variable, 7711 // an implicit C++ field reference, or an implicit ObjC ivar reference. 7712 static ValueDecl *getCompareDecl(Expr *E) { 7713 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7714 return DR->getDecl(); 7715 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7716 if (Ivar->isFreeIvar()) 7717 return Ivar->getDecl(); 7718 } 7719 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7720 if (Mem->isImplicitAccess()) 7721 return Mem->getMemberDecl(); 7722 } 7723 return 0; 7724 } 7725 7726 // C99 6.5.8, C++ [expr.rel] 7727 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7728 SourceLocation Loc, unsigned OpaqueOpc, 7729 bool IsRelational) { 7730 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7731 7732 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7733 7734 // Handle vector comparisons separately. 7735 if (LHS.get()->getType()->isVectorType() || 7736 RHS.get()->getType()->isVectorType()) 7737 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7738 7739 QualType LHSType = LHS.get()->getType(); 7740 QualType RHSType = RHS.get()->getType(); 7741 7742 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7743 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7744 7745 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7746 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7747 7748 if (!LHSType->hasFloatingRepresentation() && 7749 !(LHSType->isBlockPointerType() && IsRelational) && 7750 !LHS.get()->getLocStart().isMacroID() && 7751 !RHS.get()->getLocStart().isMacroID() && 7752 ActiveTemplateInstantiations.empty()) { 7753 // For non-floating point types, check for self-comparisons of the form 7754 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7755 // often indicate logic errors in the program. 7756 // 7757 // NOTE: Don't warn about comparison expressions resulting from macro 7758 // expansion. Also don't warn about comparisons which are only self 7759 // comparisons within a template specialization. The warnings should catch 7760 // obvious cases in the definition of the template anyways. The idea is to 7761 // warn when the typed comparison operator will always evaluate to the same 7762 // result. 7763 ValueDecl *DL = getCompareDecl(LHSStripped); 7764 ValueDecl *DR = getCompareDecl(RHSStripped); 7765 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7766 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7767 << 0 // self- 7768 << (Opc == BO_EQ 7769 || Opc == BO_LE 7770 || Opc == BO_GE)); 7771 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7772 !DL->getType()->isReferenceType() && 7773 !DR->getType()->isReferenceType()) { 7774 // what is it always going to eval to? 7775 char always_evals_to; 7776 switch(Opc) { 7777 case BO_EQ: // e.g. array1 == array2 7778 always_evals_to = 0; // false 7779 break; 7780 case BO_NE: // e.g. array1 != array2 7781 always_evals_to = 1; // true 7782 break; 7783 default: 7784 // best we can say is 'a constant' 7785 always_evals_to = 2; // e.g. array1 <= array2 7786 break; 7787 } 7788 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7789 << 1 // array 7790 << always_evals_to); 7791 } 7792 7793 if (isa<CastExpr>(LHSStripped)) 7794 LHSStripped = LHSStripped->IgnoreParenCasts(); 7795 if (isa<CastExpr>(RHSStripped)) 7796 RHSStripped = RHSStripped->IgnoreParenCasts(); 7797 7798 // Warn about comparisons against a string constant (unless the other 7799 // operand is null), the user probably wants strcmp. 7800 Expr *literalString = 0; 7801 Expr *literalStringStripped = 0; 7802 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7803 !RHSStripped->isNullPointerConstant(Context, 7804 Expr::NPC_ValueDependentIsNull)) { 7805 literalString = LHS.get(); 7806 literalStringStripped = LHSStripped; 7807 } else if ((isa<StringLiteral>(RHSStripped) || 7808 isa<ObjCEncodeExpr>(RHSStripped)) && 7809 !LHSStripped->isNullPointerConstant(Context, 7810 Expr::NPC_ValueDependentIsNull)) { 7811 literalString = RHS.get(); 7812 literalStringStripped = RHSStripped; 7813 } 7814 7815 if (literalString) { 7816 DiagRuntimeBehavior(Loc, 0, 7817 PDiag(diag::warn_stringcompare) 7818 << isa<ObjCEncodeExpr>(literalStringStripped) 7819 << literalString->getSourceRange()); 7820 } 7821 } 7822 7823 // C99 6.5.8p3 / C99 6.5.9p4 7824 UsualArithmeticConversions(LHS, RHS); 7825 if (LHS.isInvalid() || RHS.isInvalid()) 7826 return QualType(); 7827 7828 LHSType = LHS.get()->getType(); 7829 RHSType = RHS.get()->getType(); 7830 7831 // The result of comparisons is 'bool' in C++, 'int' in C. 7832 QualType ResultTy = Context.getLogicalOperationType(); 7833 7834 if (IsRelational) { 7835 if (LHSType->isRealType() && RHSType->isRealType()) 7836 return ResultTy; 7837 } else { 7838 // Check for comparisons of floating point operands using != and ==. 7839 if (LHSType->hasFloatingRepresentation()) 7840 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7841 7842 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7843 return ResultTy; 7844 } 7845 7846 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7847 Expr::NPC_ValueDependentIsNull); 7848 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7849 Expr::NPC_ValueDependentIsNull); 7850 7851 // All of the following pointer-related warnings are GCC extensions, except 7852 // when handling null pointer constants. 7853 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7854 QualType LCanPointeeTy = 7855 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7856 QualType RCanPointeeTy = 7857 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7858 7859 if (getLangOpts().CPlusPlus) { 7860 if (LCanPointeeTy == RCanPointeeTy) 7861 return ResultTy; 7862 if (!IsRelational && 7863 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7864 // Valid unless comparison between non-null pointer and function pointer 7865 // This is a gcc extension compatibility comparison. 7866 // In a SFINAE context, we treat this as a hard error to maintain 7867 // conformance with the C++ standard. 7868 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7869 && !LHSIsNull && !RHSIsNull) { 7870 diagnoseFunctionPointerToVoidComparison( 7871 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7872 7873 if (isSFINAEContext()) 7874 return QualType(); 7875 7876 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7877 return ResultTy; 7878 } 7879 } 7880 7881 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7882 return QualType(); 7883 else 7884 return ResultTy; 7885 } 7886 // C99 6.5.9p2 and C99 6.5.8p2 7887 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7888 RCanPointeeTy.getUnqualifiedType())) { 7889 // Valid unless a relational comparison of function pointers 7890 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7891 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7892 << LHSType << RHSType << LHS.get()->getSourceRange() 7893 << RHS.get()->getSourceRange(); 7894 } 7895 } else if (!IsRelational && 7896 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7897 // Valid unless comparison between non-null pointer and function pointer 7898 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7899 && !LHSIsNull && !RHSIsNull) 7900 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7901 /*isError*/false); 7902 } else { 7903 // Invalid 7904 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7905 } 7906 if (LCanPointeeTy != RCanPointeeTy) { 7907 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 7908 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 7909 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 7910 : CK_BitCast; 7911 if (LHSIsNull && !RHSIsNull) 7912 LHS = ImpCastExprToType(LHS.take(), RHSType, Kind); 7913 else 7914 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind); 7915 } 7916 return ResultTy; 7917 } 7918 7919 if (getLangOpts().CPlusPlus) { 7920 // Comparison of nullptr_t with itself. 7921 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7922 return ResultTy; 7923 7924 // Comparison of pointers with null pointer constants and equality 7925 // comparisons of member pointers to null pointer constants. 7926 if (RHSIsNull && 7927 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7928 (!IsRelational && 7929 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7930 RHS = ImpCastExprToType(RHS.take(), LHSType, 7931 LHSType->isMemberPointerType() 7932 ? CK_NullToMemberPointer 7933 : CK_NullToPointer); 7934 return ResultTy; 7935 } 7936 if (LHSIsNull && 7937 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7938 (!IsRelational && 7939 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7940 LHS = ImpCastExprToType(LHS.take(), RHSType, 7941 RHSType->isMemberPointerType() 7942 ? CK_NullToMemberPointer 7943 : CK_NullToPointer); 7944 return ResultTy; 7945 } 7946 7947 // Comparison of member pointers. 7948 if (!IsRelational && 7949 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7950 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7951 return QualType(); 7952 else 7953 return ResultTy; 7954 } 7955 7956 // Handle scoped enumeration types specifically, since they don't promote 7957 // to integers. 7958 if (LHS.get()->getType()->isEnumeralType() && 7959 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7960 RHS.get()->getType())) 7961 return ResultTy; 7962 } 7963 7964 // Handle block pointer types. 7965 if (!IsRelational && LHSType->isBlockPointerType() && 7966 RHSType->isBlockPointerType()) { 7967 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7968 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7969 7970 if (!LHSIsNull && !RHSIsNull && 7971 !Context.typesAreCompatible(lpointee, rpointee)) { 7972 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7973 << LHSType << RHSType << LHS.get()->getSourceRange() 7974 << RHS.get()->getSourceRange(); 7975 } 7976 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7977 return ResultTy; 7978 } 7979 7980 // Allow block pointers to be compared with null pointer constants. 7981 if (!IsRelational 7982 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7983 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7984 if (!LHSIsNull && !RHSIsNull) { 7985 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7986 ->getPointeeType()->isVoidType()) 7987 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7988 ->getPointeeType()->isVoidType()))) 7989 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7990 << LHSType << RHSType << LHS.get()->getSourceRange() 7991 << RHS.get()->getSourceRange(); 7992 } 7993 if (LHSIsNull && !RHSIsNull) 7994 LHS = ImpCastExprToType(LHS.take(), RHSType, 7995 RHSType->isPointerType() ? CK_BitCast 7996 : CK_AnyPointerToBlockPointerCast); 7997 else 7998 RHS = ImpCastExprToType(RHS.take(), LHSType, 7999 LHSType->isPointerType() ? CK_BitCast 8000 : CK_AnyPointerToBlockPointerCast); 8001 return ResultTy; 8002 } 8003 8004 if (LHSType->isObjCObjectPointerType() || 8005 RHSType->isObjCObjectPointerType()) { 8006 const PointerType *LPT = LHSType->getAs<PointerType>(); 8007 const PointerType *RPT = RHSType->getAs<PointerType>(); 8008 if (LPT || RPT) { 8009 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8010 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8011 8012 if (!LPtrToVoid && !RPtrToVoid && 8013 !Context.typesAreCompatible(LHSType, RHSType)) { 8014 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8015 /*isError*/false); 8016 } 8017 if (LHSIsNull && !RHSIsNull) { 8018 Expr *E = LHS.take(); 8019 if (getLangOpts().ObjCAutoRefCount) 8020 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8021 LHS = ImpCastExprToType(E, RHSType, 8022 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8023 } 8024 else { 8025 Expr *E = RHS.take(); 8026 if (getLangOpts().ObjCAutoRefCount) 8027 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion); 8028 RHS = ImpCastExprToType(E, LHSType, 8029 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8030 } 8031 return ResultTy; 8032 } 8033 if (LHSType->isObjCObjectPointerType() && 8034 RHSType->isObjCObjectPointerType()) { 8035 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8036 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8037 /*isError*/false); 8038 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8039 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8040 8041 if (LHSIsNull && !RHSIsNull) 8042 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 8043 else 8044 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 8045 return ResultTy; 8046 } 8047 } 8048 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8049 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8050 unsigned DiagID = 0; 8051 bool isError = false; 8052 if (LangOpts.DebuggerSupport) { 8053 // Under a debugger, allow the comparison of pointers to integers, 8054 // since users tend to want to compare addresses. 8055 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8056 (RHSIsNull && RHSType->isIntegerType())) { 8057 if (IsRelational && !getLangOpts().CPlusPlus) 8058 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8059 } else if (IsRelational && !getLangOpts().CPlusPlus) 8060 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8061 else if (getLangOpts().CPlusPlus) { 8062 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8063 isError = true; 8064 } else 8065 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8066 8067 if (DiagID) { 8068 Diag(Loc, DiagID) 8069 << LHSType << RHSType << LHS.get()->getSourceRange() 8070 << RHS.get()->getSourceRange(); 8071 if (isError) 8072 return QualType(); 8073 } 8074 8075 if (LHSType->isIntegerType()) 8076 LHS = ImpCastExprToType(LHS.take(), RHSType, 8077 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8078 else 8079 RHS = ImpCastExprToType(RHS.take(), LHSType, 8080 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8081 return ResultTy; 8082 } 8083 8084 // Handle block pointers. 8085 if (!IsRelational && RHSIsNull 8086 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8087 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 8088 return ResultTy; 8089 } 8090 if (!IsRelational && LHSIsNull 8091 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8092 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 8093 return ResultTy; 8094 } 8095 8096 return InvalidOperands(Loc, LHS, RHS); 8097 } 8098 8099 8100 // Return a signed type that is of identical size and number of elements. 8101 // For floating point vectors, return an integer type of identical size 8102 // and number of elements. 8103 QualType Sema::GetSignedVectorType(QualType V) { 8104 const VectorType *VTy = V->getAs<VectorType>(); 8105 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8106 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8107 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8108 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8109 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8110 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8111 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8112 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8113 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8114 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8115 "Unhandled vector element size in vector compare"); 8116 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8117 } 8118 8119 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 8120 /// operates on extended vector types. Instead of producing an IntTy result, 8121 /// like a scalar comparison, a vector comparison produces a vector of integer 8122 /// types. 8123 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8124 SourceLocation Loc, 8125 bool IsRelational) { 8126 // Check to make sure we're operating on vectors of the same type and width, 8127 // Allowing one side to be a scalar of element type. 8128 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8129 if (vType.isNull()) 8130 return vType; 8131 8132 QualType LHSType = LHS.get()->getType(); 8133 8134 // If AltiVec, the comparison results in a numeric type, i.e. 8135 // bool for C++, int for C 8136 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8137 return Context.getLogicalOperationType(); 8138 8139 // For non-floating point types, check for self-comparisons of the form 8140 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8141 // often indicate logic errors in the program. 8142 if (!LHSType->hasFloatingRepresentation() && 8143 ActiveTemplateInstantiations.empty()) { 8144 if (DeclRefExpr* DRL 8145 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8146 if (DeclRefExpr* DRR 8147 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8148 if (DRL->getDecl() == DRR->getDecl()) 8149 DiagRuntimeBehavior(Loc, 0, 8150 PDiag(diag::warn_comparison_always) 8151 << 0 // self- 8152 << 2 // "a constant" 8153 ); 8154 } 8155 8156 // Check for comparisons of floating point operands using != and ==. 8157 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8158 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8159 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8160 } 8161 8162 // Return a signed type for the vector. 8163 return GetSignedVectorType(LHSType); 8164 } 8165 8166 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8167 SourceLocation Loc) { 8168 // Ensure that either both operands are of the same vector type, or 8169 // one operand is of a vector type and the other is of its element type. 8170 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8171 if (vType.isNull()) 8172 return InvalidOperands(Loc, LHS, RHS); 8173 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8174 vType->hasFloatingRepresentation()) 8175 return InvalidOperands(Loc, LHS, RHS); 8176 8177 return GetSignedVectorType(LHS.get()->getType()); 8178 } 8179 8180 inline QualType Sema::CheckBitwiseOperands( 8181 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8182 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8183 8184 if (LHS.get()->getType()->isVectorType() || 8185 RHS.get()->getType()->isVectorType()) { 8186 if (LHS.get()->getType()->hasIntegerRepresentation() && 8187 RHS.get()->getType()->hasIntegerRepresentation()) 8188 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8189 8190 return InvalidOperands(Loc, LHS, RHS); 8191 } 8192 8193 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 8194 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8195 IsCompAssign); 8196 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8197 return QualType(); 8198 LHS = LHSResult.take(); 8199 RHS = RHSResult.take(); 8200 8201 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8202 return compType; 8203 return InvalidOperands(Loc, LHS, RHS); 8204 } 8205 8206 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8207 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8208 8209 // Check vector operands differently. 8210 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8211 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8212 8213 // Diagnose cases where the user write a logical and/or but probably meant a 8214 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8215 // is a constant. 8216 if (LHS.get()->getType()->isIntegerType() && 8217 !LHS.get()->getType()->isBooleanType() && 8218 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8219 // Don't warn in macros or template instantiations. 8220 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8221 // If the RHS can be constant folded, and if it constant folds to something 8222 // that isn't 0 or 1 (which indicate a potential logical operation that 8223 // happened to fold to true/false) then warn. 8224 // Parens on the RHS are ignored. 8225 llvm::APSInt Result; 8226 if (RHS.get()->EvaluateAsInt(Result, Context)) 8227 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 8228 (Result != 0 && Result != 1)) { 8229 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8230 << RHS.get()->getSourceRange() 8231 << (Opc == BO_LAnd ? "&&" : "||"); 8232 // Suggest replacing the logical operator with the bitwise version 8233 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8234 << (Opc == BO_LAnd ? "&" : "|") 8235 << FixItHint::CreateReplacement(SourceRange( 8236 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8237 getLangOpts())), 8238 Opc == BO_LAnd ? "&" : "|"); 8239 if (Opc == BO_LAnd) 8240 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8241 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8242 << FixItHint::CreateRemoval( 8243 SourceRange( 8244 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8245 0, getSourceManager(), 8246 getLangOpts()), 8247 RHS.get()->getLocEnd())); 8248 } 8249 } 8250 8251 if (!Context.getLangOpts().CPlusPlus) { 8252 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8253 // not operate on the built-in scalar and vector float types. 8254 if (Context.getLangOpts().OpenCL && 8255 Context.getLangOpts().OpenCLVersion < 120) { 8256 if (LHS.get()->getType()->isFloatingType() || 8257 RHS.get()->getType()->isFloatingType()) 8258 return InvalidOperands(Loc, LHS, RHS); 8259 } 8260 8261 LHS = UsualUnaryConversions(LHS.take()); 8262 if (LHS.isInvalid()) 8263 return QualType(); 8264 8265 RHS = UsualUnaryConversions(RHS.take()); 8266 if (RHS.isInvalid()) 8267 return QualType(); 8268 8269 if (!LHS.get()->getType()->isScalarType() || 8270 !RHS.get()->getType()->isScalarType()) 8271 return InvalidOperands(Loc, LHS, RHS); 8272 8273 return Context.IntTy; 8274 } 8275 8276 // The following is safe because we only use this method for 8277 // non-overloadable operands. 8278 8279 // C++ [expr.log.and]p1 8280 // C++ [expr.log.or]p1 8281 // The operands are both contextually converted to type bool. 8282 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8283 if (LHSRes.isInvalid()) 8284 return InvalidOperands(Loc, LHS, RHS); 8285 LHS = LHSRes; 8286 8287 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8288 if (RHSRes.isInvalid()) 8289 return InvalidOperands(Loc, LHS, RHS); 8290 RHS = RHSRes; 8291 8292 // C++ [expr.log.and]p2 8293 // C++ [expr.log.or]p2 8294 // The result is a bool. 8295 return Context.BoolTy; 8296 } 8297 8298 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8299 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8300 if (!ME) return false; 8301 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8302 ObjCMessageExpr *Base = 8303 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8304 if (!Base) return false; 8305 return Base->getMethodDecl() != 0; 8306 } 8307 8308 /// Is the given expression (which must be 'const') a reference to a 8309 /// variable which was originally non-const, but which has become 8310 /// 'const' due to being captured within a block? 8311 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8312 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8313 assert(E->isLValue() && E->getType().isConstQualified()); 8314 E = E->IgnoreParens(); 8315 8316 // Must be a reference to a declaration from an enclosing scope. 8317 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8318 if (!DRE) return NCCK_None; 8319 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8320 8321 // The declaration must be a variable which is not declared 'const'. 8322 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8323 if (!var) return NCCK_None; 8324 if (var->getType().isConstQualified()) return NCCK_None; 8325 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8326 8327 // Decide whether the first capture was for a block or a lambda. 8328 DeclContext *DC = S.CurContext, *Prev = 0; 8329 while (DC != var->getDeclContext()) { 8330 Prev = DC; 8331 DC = DC->getParent(); 8332 } 8333 // Unless we have an init-capture, we've gone one step too far. 8334 if (!var->isInitCapture()) 8335 DC = Prev; 8336 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8337 } 8338 8339 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8340 /// emit an error and return true. If so, return false. 8341 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8342 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8343 SourceLocation OrigLoc = Loc; 8344 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8345 &Loc); 8346 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8347 IsLV = Expr::MLV_InvalidMessageExpression; 8348 if (IsLV == Expr::MLV_Valid) 8349 return false; 8350 8351 unsigned Diag = 0; 8352 bool NeedType = false; 8353 switch (IsLV) { // C99 6.5.16p2 8354 case Expr::MLV_ConstQualified: 8355 Diag = diag::err_typecheck_assign_const; 8356 8357 // Use a specialized diagnostic when we're assigning to an object 8358 // from an enclosing function or block. 8359 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8360 if (NCCK == NCCK_Block) 8361 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8362 else 8363 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8364 break; 8365 } 8366 8367 // In ARC, use some specialized diagnostics for occasions where we 8368 // infer 'const'. These are always pseudo-strong variables. 8369 if (S.getLangOpts().ObjCAutoRefCount) { 8370 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8371 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8372 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8373 8374 // Use the normal diagnostic if it's pseudo-__strong but the 8375 // user actually wrote 'const'. 8376 if (var->isARCPseudoStrong() && 8377 (!var->getTypeSourceInfo() || 8378 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8379 // There are two pseudo-strong cases: 8380 // - self 8381 ObjCMethodDecl *method = S.getCurMethodDecl(); 8382 if (method && var == method->getSelfDecl()) 8383 Diag = method->isClassMethod() 8384 ? diag::err_typecheck_arc_assign_self_class_method 8385 : diag::err_typecheck_arc_assign_self; 8386 8387 // - fast enumeration variables 8388 else 8389 Diag = diag::err_typecheck_arr_assign_enumeration; 8390 8391 SourceRange Assign; 8392 if (Loc != OrigLoc) 8393 Assign = SourceRange(OrigLoc, OrigLoc); 8394 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8395 // We need to preserve the AST regardless, so migration tool 8396 // can do its job. 8397 return false; 8398 } 8399 } 8400 } 8401 8402 break; 8403 case Expr::MLV_ArrayType: 8404 case Expr::MLV_ArrayTemporary: 8405 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8406 NeedType = true; 8407 break; 8408 case Expr::MLV_NotObjectType: 8409 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8410 NeedType = true; 8411 break; 8412 case Expr::MLV_LValueCast: 8413 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8414 break; 8415 case Expr::MLV_Valid: 8416 llvm_unreachable("did not take early return for MLV_Valid"); 8417 case Expr::MLV_InvalidExpression: 8418 case Expr::MLV_MemberFunction: 8419 case Expr::MLV_ClassTemporary: 8420 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8421 break; 8422 case Expr::MLV_IncompleteType: 8423 case Expr::MLV_IncompleteVoidType: 8424 return S.RequireCompleteType(Loc, E->getType(), 8425 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8426 case Expr::MLV_DuplicateVectorComponents: 8427 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8428 break; 8429 case Expr::MLV_NoSetterProperty: 8430 llvm_unreachable("readonly properties should be processed differently"); 8431 case Expr::MLV_InvalidMessageExpression: 8432 Diag = diag::error_readonly_message_assignment; 8433 break; 8434 case Expr::MLV_SubObjCPropertySetting: 8435 Diag = diag::error_no_subobject_property_setting; 8436 break; 8437 } 8438 8439 SourceRange Assign; 8440 if (Loc != OrigLoc) 8441 Assign = SourceRange(OrigLoc, OrigLoc); 8442 if (NeedType) 8443 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8444 else 8445 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8446 return true; 8447 } 8448 8449 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8450 SourceLocation Loc, 8451 Sema &Sema) { 8452 // C / C++ fields 8453 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8454 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8455 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8456 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8457 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8458 } 8459 8460 // Objective-C instance variables 8461 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8462 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8463 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8464 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8465 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8466 if (RL && RR && RL->getDecl() == RR->getDecl()) 8467 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8468 } 8469 } 8470 8471 // C99 6.5.16.1 8472 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8473 SourceLocation Loc, 8474 QualType CompoundType) { 8475 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8476 8477 // Verify that LHS is a modifiable lvalue, and emit error if not. 8478 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8479 return QualType(); 8480 8481 QualType LHSType = LHSExpr->getType(); 8482 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8483 CompoundType; 8484 AssignConvertType ConvTy; 8485 if (CompoundType.isNull()) { 8486 Expr *RHSCheck = RHS.get(); 8487 8488 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8489 8490 QualType LHSTy(LHSType); 8491 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8492 if (RHS.isInvalid()) 8493 return QualType(); 8494 // Special case of NSObject attributes on c-style pointer types. 8495 if (ConvTy == IncompatiblePointer && 8496 ((Context.isObjCNSObjectType(LHSType) && 8497 RHSType->isObjCObjectPointerType()) || 8498 (Context.isObjCNSObjectType(RHSType) && 8499 LHSType->isObjCObjectPointerType()))) 8500 ConvTy = Compatible; 8501 8502 if (ConvTy == Compatible && 8503 LHSType->isObjCObjectType()) 8504 Diag(Loc, diag::err_objc_object_assignment) 8505 << LHSType; 8506 8507 // If the RHS is a unary plus or minus, check to see if they = and + are 8508 // right next to each other. If so, the user may have typo'd "x =+ 4" 8509 // instead of "x += 4". 8510 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8511 RHSCheck = ICE->getSubExpr(); 8512 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8513 if ((UO->getOpcode() == UO_Plus || 8514 UO->getOpcode() == UO_Minus) && 8515 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8516 // Only if the two operators are exactly adjacent. 8517 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8518 // And there is a space or other character before the subexpr of the 8519 // unary +/-. We don't want to warn on "x=-1". 8520 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8521 UO->getSubExpr()->getLocStart().isFileID()) { 8522 Diag(Loc, diag::warn_not_compound_assign) 8523 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8524 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8525 } 8526 } 8527 8528 if (ConvTy == Compatible) { 8529 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8530 // Warn about retain cycles where a block captures the LHS, but 8531 // not if the LHS is a simple variable into which the block is 8532 // being stored...unless that variable can be captured by reference! 8533 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8534 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8535 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8536 checkRetainCycles(LHSExpr, RHS.get()); 8537 8538 // It is safe to assign a weak reference into a strong variable. 8539 // Although this code can still have problems: 8540 // id x = self.weakProp; 8541 // id y = self.weakProp; 8542 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8543 // paths through the function. This should be revisited if 8544 // -Wrepeated-use-of-weak is made flow-sensitive. 8545 DiagnosticsEngine::Level Level = 8546 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8547 RHS.get()->getLocStart()); 8548 if (Level != DiagnosticsEngine::Ignored) 8549 getCurFunction()->markSafeWeakUse(RHS.get()); 8550 8551 } else if (getLangOpts().ObjCAutoRefCount) { 8552 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8553 } 8554 } 8555 } else { 8556 // Compound assignment "x += y" 8557 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8558 } 8559 8560 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8561 RHS.get(), AA_Assigning)) 8562 return QualType(); 8563 8564 CheckForNullPointerDereference(*this, LHSExpr); 8565 8566 // C99 6.5.16p3: The type of an assignment expression is the type of the 8567 // left operand unless the left operand has qualified type, in which case 8568 // it is the unqualified version of the type of the left operand. 8569 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8570 // is converted to the type of the assignment expression (above). 8571 // C++ 5.17p1: the type of the assignment expression is that of its left 8572 // operand. 8573 return (getLangOpts().CPlusPlus 8574 ? LHSType : LHSType.getUnqualifiedType()); 8575 } 8576 8577 // C99 6.5.17 8578 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8579 SourceLocation Loc) { 8580 LHS = S.CheckPlaceholderExpr(LHS.take()); 8581 RHS = S.CheckPlaceholderExpr(RHS.take()); 8582 if (LHS.isInvalid() || RHS.isInvalid()) 8583 return QualType(); 8584 8585 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8586 // operands, but not unary promotions. 8587 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8588 8589 // So we treat the LHS as a ignored value, and in C++ we allow the 8590 // containing site to determine what should be done with the RHS. 8591 LHS = S.IgnoredValueConversions(LHS.take()); 8592 if (LHS.isInvalid()) 8593 return QualType(); 8594 8595 S.DiagnoseUnusedExprResult(LHS.get()); 8596 8597 if (!S.getLangOpts().CPlusPlus) { 8598 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8599 if (RHS.isInvalid()) 8600 return QualType(); 8601 if (!RHS.get()->getType()->isVoidType()) 8602 S.RequireCompleteType(Loc, RHS.get()->getType(), 8603 diag::err_incomplete_type); 8604 } 8605 8606 return RHS.get()->getType(); 8607 } 8608 8609 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8610 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8611 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8612 ExprValueKind &VK, 8613 SourceLocation OpLoc, 8614 bool IsInc, bool IsPrefix) { 8615 if (Op->isTypeDependent()) 8616 return S.Context.DependentTy; 8617 8618 QualType ResType = Op->getType(); 8619 // Atomic types can be used for increment / decrement where the non-atomic 8620 // versions can, so ignore the _Atomic() specifier for the purpose of 8621 // checking. 8622 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8623 ResType = ResAtomicType->getValueType(); 8624 8625 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8626 8627 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8628 // Decrement of bool is not allowed. 8629 if (!IsInc) { 8630 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8631 return QualType(); 8632 } 8633 // Increment of bool sets it to true, but is deprecated. 8634 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8635 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8636 // Error on enum increments and decrements in C++ mode 8637 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8638 return QualType(); 8639 } else if (ResType->isRealType()) { 8640 // OK! 8641 } else if (ResType->isPointerType()) { 8642 // C99 6.5.2.4p2, 6.5.6p2 8643 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8644 return QualType(); 8645 } else if (ResType->isObjCObjectPointerType()) { 8646 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8647 // Otherwise, we just need a complete type. 8648 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8649 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8650 return QualType(); 8651 } else if (ResType->isAnyComplexType()) { 8652 // C99 does not support ++/-- on complex types, we allow as an extension. 8653 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8654 << ResType << Op->getSourceRange(); 8655 } else if (ResType->isPlaceholderType()) { 8656 ExprResult PR = S.CheckPlaceholderExpr(Op); 8657 if (PR.isInvalid()) return QualType(); 8658 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8659 IsInc, IsPrefix); 8660 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8661 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8662 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8663 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8664 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8665 } else { 8666 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8667 << ResType << int(IsInc) << Op->getSourceRange(); 8668 return QualType(); 8669 } 8670 // At this point, we know we have a real, complex or pointer type. 8671 // Now make sure the operand is a modifiable lvalue. 8672 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8673 return QualType(); 8674 // In C++, a prefix increment is the same type as the operand. Otherwise 8675 // (in C or with postfix), the increment is the unqualified type of the 8676 // operand. 8677 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8678 VK = VK_LValue; 8679 return ResType; 8680 } else { 8681 VK = VK_RValue; 8682 return ResType.getUnqualifiedType(); 8683 } 8684 } 8685 8686 8687 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8688 /// This routine allows us to typecheck complex/recursive expressions 8689 /// where the declaration is needed for type checking. We only need to 8690 /// handle cases when the expression references a function designator 8691 /// or is an lvalue. Here are some examples: 8692 /// - &(x) => x 8693 /// - &*****f => f for f a function designator. 8694 /// - &s.xx => s 8695 /// - &s.zz[1].yy -> s, if zz is an array 8696 /// - *(x + 1) -> x, if x is an array 8697 /// - &"123"[2] -> 0 8698 /// - & __real__ x -> x 8699 static ValueDecl *getPrimaryDecl(Expr *E) { 8700 switch (E->getStmtClass()) { 8701 case Stmt::DeclRefExprClass: 8702 return cast<DeclRefExpr>(E)->getDecl(); 8703 case Stmt::MemberExprClass: 8704 // If this is an arrow operator, the address is an offset from 8705 // the base's value, so the object the base refers to is 8706 // irrelevant. 8707 if (cast<MemberExpr>(E)->isArrow()) 8708 return 0; 8709 // Otherwise, the expression refers to a part of the base 8710 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8711 case Stmt::ArraySubscriptExprClass: { 8712 // FIXME: This code shouldn't be necessary! We should catch the implicit 8713 // promotion of register arrays earlier. 8714 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8715 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8716 if (ICE->getSubExpr()->getType()->isArrayType()) 8717 return getPrimaryDecl(ICE->getSubExpr()); 8718 } 8719 return 0; 8720 } 8721 case Stmt::UnaryOperatorClass: { 8722 UnaryOperator *UO = cast<UnaryOperator>(E); 8723 8724 switch(UO->getOpcode()) { 8725 case UO_Real: 8726 case UO_Imag: 8727 case UO_Extension: 8728 return getPrimaryDecl(UO->getSubExpr()); 8729 default: 8730 return 0; 8731 } 8732 } 8733 case Stmt::ParenExprClass: 8734 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8735 case Stmt::ImplicitCastExprClass: 8736 // If the result of an implicit cast is an l-value, we care about 8737 // the sub-expression; otherwise, the result here doesn't matter. 8738 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8739 default: 8740 return 0; 8741 } 8742 } 8743 8744 namespace { 8745 enum { 8746 AO_Bit_Field = 0, 8747 AO_Vector_Element = 1, 8748 AO_Property_Expansion = 2, 8749 AO_Register_Variable = 3, 8750 AO_No_Error = 4 8751 }; 8752 } 8753 /// \brief Diagnose invalid operand for address of operations. 8754 /// 8755 /// \param Type The type of operand which cannot have its address taken. 8756 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8757 Expr *E, unsigned Type) { 8758 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8759 } 8760 8761 /// CheckAddressOfOperand - The operand of & must be either a function 8762 /// designator or an lvalue designating an object. If it is an lvalue, the 8763 /// object cannot be declared with storage class register or be a bit field. 8764 /// Note: The usual conversions are *not* applied to the operand of the & 8765 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8766 /// In C++, the operand might be an overloaded function name, in which case 8767 /// we allow the '&' but retain the overloaded-function type. 8768 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8769 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8770 if (PTy->getKind() == BuiltinType::Overload) { 8771 Expr *E = OrigOp.get()->IgnoreParens(); 8772 if (!isa<OverloadExpr>(E)) { 8773 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8774 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8775 << OrigOp.get()->getSourceRange(); 8776 return QualType(); 8777 } 8778 8779 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8780 if (isa<UnresolvedMemberExpr>(Ovl)) 8781 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8782 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8783 << OrigOp.get()->getSourceRange(); 8784 return QualType(); 8785 } 8786 8787 return Context.OverloadTy; 8788 } 8789 8790 if (PTy->getKind() == BuiltinType::UnknownAny) 8791 return Context.UnknownAnyTy; 8792 8793 if (PTy->getKind() == BuiltinType::BoundMember) { 8794 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8795 << OrigOp.get()->getSourceRange(); 8796 return QualType(); 8797 } 8798 8799 OrigOp = CheckPlaceholderExpr(OrigOp.take()); 8800 if (OrigOp.isInvalid()) return QualType(); 8801 } 8802 8803 if (OrigOp.get()->isTypeDependent()) 8804 return Context.DependentTy; 8805 8806 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8807 8808 // Make sure to ignore parentheses in subsequent checks 8809 Expr *op = OrigOp.get()->IgnoreParens(); 8810 8811 if (getLangOpts().C99) { 8812 // Implement C99-only parts of addressof rules. 8813 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8814 if (uOp->getOpcode() == UO_Deref) 8815 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8816 // (assuming the deref expression is valid). 8817 return uOp->getSubExpr()->getType(); 8818 } 8819 // Technically, there should be a check for array subscript 8820 // expressions here, but the result of one is always an lvalue anyway. 8821 } 8822 ValueDecl *dcl = getPrimaryDecl(op); 8823 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8824 unsigned AddressOfError = AO_No_Error; 8825 8826 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8827 bool sfinae = (bool)isSFINAEContext(); 8828 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8829 : diag::ext_typecheck_addrof_temporary) 8830 << op->getType() << op->getSourceRange(); 8831 if (sfinae) 8832 return QualType(); 8833 // Materialize the temporary as an lvalue so that we can take its address. 8834 OrigOp = op = new (Context) 8835 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8836 } else if (isa<ObjCSelectorExpr>(op)) { 8837 return Context.getPointerType(op->getType()); 8838 } else if (lval == Expr::LV_MemberFunction) { 8839 // If it's an instance method, make a member pointer. 8840 // The expression must have exactly the form &A::foo. 8841 8842 // If the underlying expression isn't a decl ref, give up. 8843 if (!isa<DeclRefExpr>(op)) { 8844 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8845 << OrigOp.get()->getSourceRange(); 8846 return QualType(); 8847 } 8848 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8849 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8850 8851 // The id-expression was parenthesized. 8852 if (OrigOp.get() != DRE) { 8853 Diag(OpLoc, diag::err_parens_pointer_member_function) 8854 << OrigOp.get()->getSourceRange(); 8855 8856 // The method was named without a qualifier. 8857 } else if (!DRE->getQualifier()) { 8858 if (MD->getParent()->getName().empty()) 8859 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8860 << op->getSourceRange(); 8861 else { 8862 SmallString<32> Str; 8863 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8864 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8865 << op->getSourceRange() 8866 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8867 } 8868 } 8869 8870 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 8871 if (isa<CXXDestructorDecl>(MD)) 8872 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 8873 8874 QualType MPTy = Context.getMemberPointerType( 8875 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8876 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8877 RequireCompleteType(OpLoc, MPTy, 0); 8878 return MPTy; 8879 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8880 // C99 6.5.3.2p1 8881 // The operand must be either an l-value or a function designator 8882 if (!op->getType()->isFunctionType()) { 8883 // Use a special diagnostic for loads from property references. 8884 if (isa<PseudoObjectExpr>(op)) { 8885 AddressOfError = AO_Property_Expansion; 8886 } else { 8887 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8888 << op->getType() << op->getSourceRange(); 8889 return QualType(); 8890 } 8891 } 8892 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8893 // The operand cannot be a bit-field 8894 AddressOfError = AO_Bit_Field; 8895 } else if (op->getObjectKind() == OK_VectorComponent) { 8896 // The operand cannot be an element of a vector 8897 AddressOfError = AO_Vector_Element; 8898 } else if (dcl) { // C99 6.5.3.2p1 8899 // We have an lvalue with a decl. Make sure the decl is not declared 8900 // with the register storage-class specifier. 8901 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8902 // in C++ it is not error to take address of a register 8903 // variable (c++03 7.1.1P3) 8904 if (vd->getStorageClass() == SC_Register && 8905 !getLangOpts().CPlusPlus) { 8906 AddressOfError = AO_Register_Variable; 8907 } 8908 } else if (isa<FunctionTemplateDecl>(dcl)) { 8909 return Context.OverloadTy; 8910 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8911 // Okay: we can take the address of a field. 8912 // Could be a pointer to member, though, if there is an explicit 8913 // scope qualifier for the class. 8914 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8915 DeclContext *Ctx = dcl->getDeclContext(); 8916 if (Ctx && Ctx->isRecord()) { 8917 if (dcl->getType()->isReferenceType()) { 8918 Diag(OpLoc, 8919 diag::err_cannot_form_pointer_to_member_of_reference_type) 8920 << dcl->getDeclName() << dcl->getType(); 8921 return QualType(); 8922 } 8923 8924 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8925 Ctx = Ctx->getParent(); 8926 8927 QualType MPTy = Context.getMemberPointerType( 8928 op->getType(), 8929 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8930 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8931 RequireCompleteType(OpLoc, MPTy, 0); 8932 return MPTy; 8933 } 8934 } 8935 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8936 llvm_unreachable("Unknown/unexpected decl type"); 8937 } 8938 8939 if (AddressOfError != AO_No_Error) { 8940 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 8941 return QualType(); 8942 } 8943 8944 if (lval == Expr::LV_IncompleteVoidType) { 8945 // Taking the address of a void variable is technically illegal, but we 8946 // allow it in cases which are otherwise valid. 8947 // Example: "extern void x; void* y = &x;". 8948 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8949 } 8950 8951 // If the operand has type "type", the result has type "pointer to type". 8952 if (op->getType()->isObjCObjectType()) 8953 return Context.getObjCObjectPointerType(op->getType()); 8954 return Context.getPointerType(op->getType()); 8955 } 8956 8957 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8958 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8959 SourceLocation OpLoc) { 8960 if (Op->isTypeDependent()) 8961 return S.Context.DependentTy; 8962 8963 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8964 if (ConvResult.isInvalid()) 8965 return QualType(); 8966 Op = ConvResult.take(); 8967 QualType OpTy = Op->getType(); 8968 QualType Result; 8969 8970 if (isa<CXXReinterpretCastExpr>(Op)) { 8971 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8972 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8973 Op->getSourceRange()); 8974 } 8975 8976 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8977 // is an incomplete type or void. It would be possible to warn about 8978 // dereferencing a void pointer, but it's completely well-defined, and such a 8979 // warning is unlikely to catch any mistakes. 8980 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8981 Result = PT->getPointeeType(); 8982 else if (const ObjCObjectPointerType *OPT = 8983 OpTy->getAs<ObjCObjectPointerType>()) 8984 Result = OPT->getPointeeType(); 8985 else { 8986 ExprResult PR = S.CheckPlaceholderExpr(Op); 8987 if (PR.isInvalid()) return QualType(); 8988 if (PR.take() != Op) 8989 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8990 } 8991 8992 if (Result.isNull()) { 8993 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8994 << OpTy << Op->getSourceRange(); 8995 return QualType(); 8996 } 8997 8998 // Dereferences are usually l-values... 8999 VK = VK_LValue; 9000 9001 // ...except that certain expressions are never l-values in C. 9002 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 9003 VK = VK_RValue; 9004 9005 return Result; 9006 } 9007 9008 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 9009 tok::TokenKind Kind) { 9010 BinaryOperatorKind Opc; 9011 switch (Kind) { 9012 default: llvm_unreachable("Unknown binop!"); 9013 case tok::periodstar: Opc = BO_PtrMemD; break; 9014 case tok::arrowstar: Opc = BO_PtrMemI; break; 9015 case tok::star: Opc = BO_Mul; break; 9016 case tok::slash: Opc = BO_Div; break; 9017 case tok::percent: Opc = BO_Rem; break; 9018 case tok::plus: Opc = BO_Add; break; 9019 case tok::minus: Opc = BO_Sub; break; 9020 case tok::lessless: Opc = BO_Shl; break; 9021 case tok::greatergreater: Opc = BO_Shr; break; 9022 case tok::lessequal: Opc = BO_LE; break; 9023 case tok::less: Opc = BO_LT; break; 9024 case tok::greaterequal: Opc = BO_GE; break; 9025 case tok::greater: Opc = BO_GT; break; 9026 case tok::exclaimequal: Opc = BO_NE; break; 9027 case tok::equalequal: Opc = BO_EQ; break; 9028 case tok::amp: Opc = BO_And; break; 9029 case tok::caret: Opc = BO_Xor; break; 9030 case tok::pipe: Opc = BO_Or; break; 9031 case tok::ampamp: Opc = BO_LAnd; break; 9032 case tok::pipepipe: Opc = BO_LOr; break; 9033 case tok::equal: Opc = BO_Assign; break; 9034 case tok::starequal: Opc = BO_MulAssign; break; 9035 case tok::slashequal: Opc = BO_DivAssign; break; 9036 case tok::percentequal: Opc = BO_RemAssign; break; 9037 case tok::plusequal: Opc = BO_AddAssign; break; 9038 case tok::minusequal: Opc = BO_SubAssign; break; 9039 case tok::lesslessequal: Opc = BO_ShlAssign; break; 9040 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 9041 case tok::ampequal: Opc = BO_AndAssign; break; 9042 case tok::caretequal: Opc = BO_XorAssign; break; 9043 case tok::pipeequal: Opc = BO_OrAssign; break; 9044 case tok::comma: Opc = BO_Comma; break; 9045 } 9046 return Opc; 9047 } 9048 9049 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 9050 tok::TokenKind Kind) { 9051 UnaryOperatorKind Opc; 9052 switch (Kind) { 9053 default: llvm_unreachable("Unknown unary op!"); 9054 case tok::plusplus: Opc = UO_PreInc; break; 9055 case tok::minusminus: Opc = UO_PreDec; break; 9056 case tok::amp: Opc = UO_AddrOf; break; 9057 case tok::star: Opc = UO_Deref; break; 9058 case tok::plus: Opc = UO_Plus; break; 9059 case tok::minus: Opc = UO_Minus; break; 9060 case tok::tilde: Opc = UO_Not; break; 9061 case tok::exclaim: Opc = UO_LNot; break; 9062 case tok::kw___real: Opc = UO_Real; break; 9063 case tok::kw___imag: Opc = UO_Imag; break; 9064 case tok::kw___extension__: Opc = UO_Extension; break; 9065 } 9066 return Opc; 9067 } 9068 9069 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 9070 /// This warning is only emitted for builtin assignment operations. It is also 9071 /// suppressed in the event of macro expansions. 9072 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 9073 SourceLocation OpLoc) { 9074 if (!S.ActiveTemplateInstantiations.empty()) 9075 return; 9076 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 9077 return; 9078 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 9079 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 9080 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 9081 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 9082 if (!LHSDeclRef || !RHSDeclRef || 9083 LHSDeclRef->getLocation().isMacroID() || 9084 RHSDeclRef->getLocation().isMacroID()) 9085 return; 9086 const ValueDecl *LHSDecl = 9087 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 9088 const ValueDecl *RHSDecl = 9089 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 9090 if (LHSDecl != RHSDecl) 9091 return; 9092 if (LHSDecl->getType().isVolatileQualified()) 9093 return; 9094 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9095 if (RefTy->getPointeeType().isVolatileQualified()) 9096 return; 9097 9098 S.Diag(OpLoc, diag::warn_self_assignment) 9099 << LHSDeclRef->getType() 9100 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9101 } 9102 9103 /// Check if a bitwise-& is performed on an Objective-C pointer. This 9104 /// is usually indicative of introspection within the Objective-C pointer. 9105 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9106 SourceLocation OpLoc) { 9107 if (!S.getLangOpts().ObjC1) 9108 return; 9109 9110 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 9111 const Expr *LHS = L.get(); 9112 const Expr *RHS = R.get(); 9113 9114 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9115 ObjCPointerExpr = LHS; 9116 OtherExpr = RHS; 9117 } 9118 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9119 ObjCPointerExpr = RHS; 9120 OtherExpr = LHS; 9121 } 9122 9123 // This warning is deliberately made very specific to reduce false 9124 // positives with logic that uses '&' for hashing. This logic mainly 9125 // looks for code trying to introspect into tagged pointers, which 9126 // code should generally never do. 9127 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9128 unsigned Diag = diag::warn_objc_pointer_masking; 9129 // Determine if we are introspecting the result of performSelectorXXX. 9130 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9131 // Special case messages to -performSelector and friends, which 9132 // can return non-pointer values boxed in a pointer value. 9133 // Some clients may wish to silence warnings in this subcase. 9134 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9135 Selector S = ME->getSelector(); 9136 StringRef SelArg0 = S.getNameForSlot(0); 9137 if (SelArg0.startswith("performSelector")) 9138 Diag = diag::warn_objc_pointer_masking_performSelector; 9139 } 9140 9141 S.Diag(OpLoc, Diag) 9142 << ObjCPointerExpr->getSourceRange(); 9143 } 9144 } 9145 9146 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 9147 /// operator @p Opc at location @c TokLoc. This routine only supports 9148 /// built-in operations; ActOnBinOp handles overloaded operators. 9149 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9150 BinaryOperatorKind Opc, 9151 Expr *LHSExpr, Expr *RHSExpr) { 9152 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 9153 // The syntax only allows initializer lists on the RHS of assignment, 9154 // so we don't need to worry about accepting invalid code for 9155 // non-assignment operators. 9156 // C++11 5.17p9: 9157 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 9158 // of x = {} is x = T(). 9159 InitializationKind Kind = 9160 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 9161 InitializedEntity Entity = 9162 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 9163 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 9164 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 9165 if (Init.isInvalid()) 9166 return Init; 9167 RHSExpr = Init.take(); 9168 } 9169 9170 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 9171 QualType ResultTy; // Result type of the binary operator. 9172 // The following two variables are used for compound assignment operators 9173 QualType CompLHSTy; // Type of LHS after promotions for computation 9174 QualType CompResultTy; // Type of computation result 9175 ExprValueKind VK = VK_RValue; 9176 ExprObjectKind OK = OK_Ordinary; 9177 9178 switch (Opc) { 9179 case BO_Assign: 9180 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9181 if (getLangOpts().CPlusPlus && 9182 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9183 VK = LHS.get()->getValueKind(); 9184 OK = LHS.get()->getObjectKind(); 9185 } 9186 if (!ResultTy.isNull()) 9187 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9188 break; 9189 case BO_PtrMemD: 9190 case BO_PtrMemI: 9191 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9192 Opc == BO_PtrMemI); 9193 break; 9194 case BO_Mul: 9195 case BO_Div: 9196 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9197 Opc == BO_Div); 9198 break; 9199 case BO_Rem: 9200 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9201 break; 9202 case BO_Add: 9203 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9204 break; 9205 case BO_Sub: 9206 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9207 break; 9208 case BO_Shl: 9209 case BO_Shr: 9210 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9211 break; 9212 case BO_LE: 9213 case BO_LT: 9214 case BO_GE: 9215 case BO_GT: 9216 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9217 break; 9218 case BO_EQ: 9219 case BO_NE: 9220 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9221 break; 9222 case BO_And: 9223 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9224 case BO_Xor: 9225 case BO_Or: 9226 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9227 break; 9228 case BO_LAnd: 9229 case BO_LOr: 9230 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9231 break; 9232 case BO_MulAssign: 9233 case BO_DivAssign: 9234 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9235 Opc == BO_DivAssign); 9236 CompLHSTy = CompResultTy; 9237 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9238 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9239 break; 9240 case BO_RemAssign: 9241 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9242 CompLHSTy = CompResultTy; 9243 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9244 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9245 break; 9246 case BO_AddAssign: 9247 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9248 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9249 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9250 break; 9251 case BO_SubAssign: 9252 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9253 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9254 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9255 break; 9256 case BO_ShlAssign: 9257 case BO_ShrAssign: 9258 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9259 CompLHSTy = CompResultTy; 9260 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9261 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9262 break; 9263 case BO_AndAssign: 9264 case BO_XorAssign: 9265 case BO_OrAssign: 9266 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9267 CompLHSTy = CompResultTy; 9268 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9269 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9270 break; 9271 case BO_Comma: 9272 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9273 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9274 VK = RHS.get()->getValueKind(); 9275 OK = RHS.get()->getObjectKind(); 9276 } 9277 break; 9278 } 9279 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9280 return ExprError(); 9281 9282 // Check for array bounds violations for both sides of the BinaryOperator 9283 CheckArrayAccess(LHS.get()); 9284 CheckArrayAccess(RHS.get()); 9285 9286 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9287 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9288 &Context.Idents.get("object_setClass"), 9289 SourceLocation(), LookupOrdinaryName); 9290 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9291 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9292 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9293 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9294 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9295 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9296 } 9297 else 9298 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9299 } 9300 else if (const ObjCIvarRefExpr *OIRE = 9301 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9302 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9303 9304 if (CompResultTy.isNull()) 9305 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 9306 ResultTy, VK, OK, OpLoc, 9307 FPFeatures.fp_contract)); 9308 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9309 OK_ObjCProperty) { 9310 VK = VK_LValue; 9311 OK = LHS.get()->getObjectKind(); 9312 } 9313 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 9314 ResultTy, VK, OK, CompLHSTy, 9315 CompResultTy, OpLoc, 9316 FPFeatures.fp_contract)); 9317 } 9318 9319 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9320 /// operators are mixed in a way that suggests that the programmer forgot that 9321 /// comparison operators have higher precedence. The most typical example of 9322 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9323 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9324 SourceLocation OpLoc, Expr *LHSExpr, 9325 Expr *RHSExpr) { 9326 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9327 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9328 9329 // Check that one of the sides is a comparison operator. 9330 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9331 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9332 if (!isLeftComp && !isRightComp) 9333 return; 9334 9335 // Bitwise operations are sometimes used as eager logical ops. 9336 // Don't diagnose this. 9337 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9338 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9339 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9340 return; 9341 9342 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9343 OpLoc) 9344 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9345 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9346 SourceRange ParensRange = isLeftComp ? 9347 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9348 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9349 9350 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9351 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9352 SuggestParentheses(Self, OpLoc, 9353 Self.PDiag(diag::note_precedence_silence) << OpStr, 9354 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9355 SuggestParentheses(Self, OpLoc, 9356 Self.PDiag(diag::note_precedence_bitwise_first) 9357 << BinaryOperator::getOpcodeStr(Opc), 9358 ParensRange); 9359 } 9360 9361 /// \brief It accepts a '&' expr that is inside a '|' one. 9362 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9363 /// in parentheses. 9364 static void 9365 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9366 BinaryOperator *Bop) { 9367 assert(Bop->getOpcode() == BO_And); 9368 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9369 << Bop->getSourceRange() << OpLoc; 9370 SuggestParentheses(Self, Bop->getOperatorLoc(), 9371 Self.PDiag(diag::note_precedence_silence) 9372 << Bop->getOpcodeStr(), 9373 Bop->getSourceRange()); 9374 } 9375 9376 /// \brief It accepts a '&&' expr that is inside a '||' one. 9377 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9378 /// in parentheses. 9379 static void 9380 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9381 BinaryOperator *Bop) { 9382 assert(Bop->getOpcode() == BO_LAnd); 9383 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9384 << Bop->getSourceRange() << OpLoc; 9385 SuggestParentheses(Self, Bop->getOperatorLoc(), 9386 Self.PDiag(diag::note_precedence_silence) 9387 << Bop->getOpcodeStr(), 9388 Bop->getSourceRange()); 9389 } 9390 9391 /// \brief Returns true if the given expression can be evaluated as a constant 9392 /// 'true'. 9393 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9394 bool Res; 9395 return !E->isValueDependent() && 9396 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9397 } 9398 9399 /// \brief Returns true if the given expression can be evaluated as a constant 9400 /// 'false'. 9401 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9402 bool Res; 9403 return !E->isValueDependent() && 9404 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9405 } 9406 9407 /// \brief Look for '&&' in the left hand of a '||' expr. 9408 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9409 Expr *LHSExpr, Expr *RHSExpr) { 9410 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9411 if (Bop->getOpcode() == BO_LAnd) { 9412 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9413 if (EvaluatesAsFalse(S, RHSExpr)) 9414 return; 9415 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9416 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9417 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9418 } else if (Bop->getOpcode() == BO_LOr) { 9419 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9420 // If it's "a || b && 1 || c" we didn't warn earlier for 9421 // "a || b && 1", but warn now. 9422 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9423 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9424 } 9425 } 9426 } 9427 } 9428 9429 /// \brief Look for '&&' in the right hand of a '||' expr. 9430 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9431 Expr *LHSExpr, Expr *RHSExpr) { 9432 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9433 if (Bop->getOpcode() == BO_LAnd) { 9434 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9435 if (EvaluatesAsFalse(S, LHSExpr)) 9436 return; 9437 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9438 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9439 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9440 } 9441 } 9442 } 9443 9444 /// \brief Look for '&' in the left or right hand of a '|' expr. 9445 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9446 Expr *OrArg) { 9447 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9448 if (Bop->getOpcode() == BO_And) 9449 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9450 } 9451 } 9452 9453 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9454 Expr *SubExpr, StringRef Shift) { 9455 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9456 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9457 StringRef Op = Bop->getOpcodeStr(); 9458 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9459 << Bop->getSourceRange() << OpLoc << Shift << Op; 9460 SuggestParentheses(S, Bop->getOperatorLoc(), 9461 S.PDiag(diag::note_precedence_silence) << Op, 9462 Bop->getSourceRange()); 9463 } 9464 } 9465 } 9466 9467 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9468 Expr *LHSExpr, Expr *RHSExpr) { 9469 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9470 if (!OCE) 9471 return; 9472 9473 FunctionDecl *FD = OCE->getDirectCallee(); 9474 if (!FD || !FD->isOverloadedOperator()) 9475 return; 9476 9477 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9478 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9479 return; 9480 9481 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9482 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9483 << (Kind == OO_LessLess); 9484 SuggestParentheses(S, OCE->getOperatorLoc(), 9485 S.PDiag(diag::note_precedence_silence) 9486 << (Kind == OO_LessLess ? "<<" : ">>"), 9487 OCE->getSourceRange()); 9488 SuggestParentheses(S, OpLoc, 9489 S.PDiag(diag::note_evaluate_comparison_first), 9490 SourceRange(OCE->getArg(1)->getLocStart(), 9491 RHSExpr->getLocEnd())); 9492 } 9493 9494 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9495 /// precedence. 9496 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9497 SourceLocation OpLoc, Expr *LHSExpr, 9498 Expr *RHSExpr){ 9499 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9500 if (BinaryOperator::isBitwiseOp(Opc)) 9501 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9502 9503 // Diagnose "arg1 & arg2 | arg3" 9504 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9505 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9506 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9507 } 9508 9509 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9510 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9511 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9512 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9513 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9514 } 9515 9516 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9517 || Opc == BO_Shr) { 9518 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9519 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9520 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9521 } 9522 9523 // Warn on overloaded shift operators and comparisons, such as: 9524 // cout << 5 == 4; 9525 if (BinaryOperator::isComparisonOp(Opc)) 9526 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9527 } 9528 9529 // Binary Operators. 'Tok' is the token for the operator. 9530 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9531 tok::TokenKind Kind, 9532 Expr *LHSExpr, Expr *RHSExpr) { 9533 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9534 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9535 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9536 9537 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9538 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9539 9540 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9541 } 9542 9543 /// Build an overloaded binary operator expression in the given scope. 9544 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9545 BinaryOperatorKind Opc, 9546 Expr *LHS, Expr *RHS) { 9547 // Find all of the overloaded operators visible from this 9548 // point. We perform both an operator-name lookup from the local 9549 // scope and an argument-dependent lookup based on the types of 9550 // the arguments. 9551 UnresolvedSet<16> Functions; 9552 OverloadedOperatorKind OverOp 9553 = BinaryOperator::getOverloadedOperator(Opc); 9554 if (Sc && OverOp != OO_None) 9555 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9556 RHS->getType(), Functions); 9557 9558 // Build the (potentially-overloaded, potentially-dependent) 9559 // binary operation. 9560 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9561 } 9562 9563 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9564 BinaryOperatorKind Opc, 9565 Expr *LHSExpr, Expr *RHSExpr) { 9566 // We want to end up calling one of checkPseudoObjectAssignment 9567 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9568 // both expressions are overloadable or either is type-dependent), 9569 // or CreateBuiltinBinOp (in any other case). We also want to get 9570 // any placeholder types out of the way. 9571 9572 // Handle pseudo-objects in the LHS. 9573 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9574 // Assignments with a pseudo-object l-value need special analysis. 9575 if (pty->getKind() == BuiltinType::PseudoObject && 9576 BinaryOperator::isAssignmentOp(Opc)) 9577 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9578 9579 // Don't resolve overloads if the other type is overloadable. 9580 if (pty->getKind() == BuiltinType::Overload) { 9581 // We can't actually test that if we still have a placeholder, 9582 // though. Fortunately, none of the exceptions we see in that 9583 // code below are valid when the LHS is an overload set. Note 9584 // that an overload set can be dependently-typed, but it never 9585 // instantiates to having an overloadable type. 9586 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9587 if (resolvedRHS.isInvalid()) return ExprError(); 9588 RHSExpr = resolvedRHS.take(); 9589 9590 if (RHSExpr->isTypeDependent() || 9591 RHSExpr->getType()->isOverloadableType()) 9592 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9593 } 9594 9595 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9596 if (LHS.isInvalid()) return ExprError(); 9597 LHSExpr = LHS.take(); 9598 } 9599 9600 // Handle pseudo-objects in the RHS. 9601 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9602 // An overload in the RHS can potentially be resolved by the type 9603 // being assigned to. 9604 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9605 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9606 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9607 9608 if (LHSExpr->getType()->isOverloadableType()) 9609 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9610 9611 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9612 } 9613 9614 // Don't resolve overloads if the other type is overloadable. 9615 if (pty->getKind() == BuiltinType::Overload && 9616 LHSExpr->getType()->isOverloadableType()) 9617 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9618 9619 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9620 if (!resolvedRHS.isUsable()) return ExprError(); 9621 RHSExpr = resolvedRHS.take(); 9622 } 9623 9624 if (getLangOpts().CPlusPlus) { 9625 // If either expression is type-dependent, always build an 9626 // overloaded op. 9627 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9628 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9629 9630 // Otherwise, build an overloaded op if either expression has an 9631 // overloadable type. 9632 if (LHSExpr->getType()->isOverloadableType() || 9633 RHSExpr->getType()->isOverloadableType()) 9634 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9635 } 9636 9637 // Build a built-in binary operation. 9638 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9639 } 9640 9641 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9642 UnaryOperatorKind Opc, 9643 Expr *InputExpr) { 9644 ExprResult Input = Owned(InputExpr); 9645 ExprValueKind VK = VK_RValue; 9646 ExprObjectKind OK = OK_Ordinary; 9647 QualType resultType; 9648 switch (Opc) { 9649 case UO_PreInc: 9650 case UO_PreDec: 9651 case UO_PostInc: 9652 case UO_PostDec: 9653 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9654 Opc == UO_PreInc || 9655 Opc == UO_PostInc, 9656 Opc == UO_PreInc || 9657 Opc == UO_PreDec); 9658 break; 9659 case UO_AddrOf: 9660 resultType = CheckAddressOfOperand(Input, OpLoc); 9661 break; 9662 case UO_Deref: { 9663 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9664 if (Input.isInvalid()) return ExprError(); 9665 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9666 break; 9667 } 9668 case UO_Plus: 9669 case UO_Minus: 9670 Input = UsualUnaryConversions(Input.take()); 9671 if (Input.isInvalid()) return ExprError(); 9672 resultType = Input.get()->getType(); 9673 if (resultType->isDependentType()) 9674 break; 9675 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9676 resultType->isVectorType()) 9677 break; 9678 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9679 Opc == UO_Plus && 9680 resultType->isPointerType()) 9681 break; 9682 9683 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9684 << resultType << Input.get()->getSourceRange()); 9685 9686 case UO_Not: // bitwise complement 9687 Input = UsualUnaryConversions(Input.take()); 9688 if (Input.isInvalid()) 9689 return ExprError(); 9690 resultType = Input.get()->getType(); 9691 if (resultType->isDependentType()) 9692 break; 9693 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9694 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9695 // C99 does not support '~' for complex conjugation. 9696 Diag(OpLoc, diag::ext_integer_complement_complex) 9697 << resultType << Input.get()->getSourceRange(); 9698 else if (resultType->hasIntegerRepresentation()) 9699 break; 9700 else if (resultType->isExtVectorType()) { 9701 if (Context.getLangOpts().OpenCL) { 9702 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9703 // on vector float types. 9704 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9705 if (!T->isIntegerType()) 9706 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9707 << resultType << Input.get()->getSourceRange()); 9708 } 9709 break; 9710 } else { 9711 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9712 << resultType << Input.get()->getSourceRange()); 9713 } 9714 break; 9715 9716 case UO_LNot: // logical negation 9717 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9718 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9719 if (Input.isInvalid()) return ExprError(); 9720 resultType = Input.get()->getType(); 9721 9722 // Though we still have to promote half FP to float... 9723 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9724 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9725 resultType = Context.FloatTy; 9726 } 9727 9728 if (resultType->isDependentType()) 9729 break; 9730 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 9731 // C99 6.5.3.3p1: ok, fallthrough; 9732 if (Context.getLangOpts().CPlusPlus) { 9733 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9734 // operand contextually converted to bool. 9735 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9736 ScalarTypeToBooleanCastKind(resultType)); 9737 } else if (Context.getLangOpts().OpenCL && 9738 Context.getLangOpts().OpenCLVersion < 120) { 9739 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9740 // operate on scalar float types. 9741 if (!resultType->isIntegerType()) 9742 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9743 << resultType << Input.get()->getSourceRange()); 9744 } 9745 } else if (resultType->isExtVectorType()) { 9746 if (Context.getLangOpts().OpenCL && 9747 Context.getLangOpts().OpenCLVersion < 120) { 9748 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9749 // operate on vector float types. 9750 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9751 if (!T->isIntegerType()) 9752 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9753 << resultType << Input.get()->getSourceRange()); 9754 } 9755 // Vector logical not returns the signed variant of the operand type. 9756 resultType = GetSignedVectorType(resultType); 9757 break; 9758 } else { 9759 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9760 << resultType << Input.get()->getSourceRange()); 9761 } 9762 9763 // LNot always has type int. C99 6.5.3.3p5. 9764 // In C++, it's bool. C++ 5.3.1p8 9765 resultType = Context.getLogicalOperationType(); 9766 break; 9767 case UO_Real: 9768 case UO_Imag: 9769 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9770 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9771 // complex l-values to ordinary l-values and all other values to r-values. 9772 if (Input.isInvalid()) return ExprError(); 9773 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9774 if (Input.get()->getValueKind() != VK_RValue && 9775 Input.get()->getObjectKind() == OK_Ordinary) 9776 VK = Input.get()->getValueKind(); 9777 } else if (!getLangOpts().CPlusPlus) { 9778 // In C, a volatile scalar is read by __imag. In C++, it is not. 9779 Input = DefaultLvalueConversion(Input.take()); 9780 } 9781 break; 9782 case UO_Extension: 9783 resultType = Input.get()->getType(); 9784 VK = Input.get()->getValueKind(); 9785 OK = Input.get()->getObjectKind(); 9786 break; 9787 } 9788 if (resultType.isNull() || Input.isInvalid()) 9789 return ExprError(); 9790 9791 // Check for array bounds violations in the operand of the UnaryOperator, 9792 // except for the '*' and '&' operators that have to be handled specially 9793 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9794 // that are explicitly defined as valid by the standard). 9795 if (Opc != UO_AddrOf && Opc != UO_Deref) 9796 CheckArrayAccess(Input.get()); 9797 9798 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9799 VK, OK, OpLoc)); 9800 } 9801 9802 /// \brief Determine whether the given expression is a qualified member 9803 /// access expression, of a form that could be turned into a pointer to member 9804 /// with the address-of operator. 9805 static bool isQualifiedMemberAccess(Expr *E) { 9806 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9807 if (!DRE->getQualifier()) 9808 return false; 9809 9810 ValueDecl *VD = DRE->getDecl(); 9811 if (!VD->isCXXClassMember()) 9812 return false; 9813 9814 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9815 return true; 9816 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9817 return Method->isInstance(); 9818 9819 return false; 9820 } 9821 9822 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9823 if (!ULE->getQualifier()) 9824 return false; 9825 9826 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9827 DEnd = ULE->decls_end(); 9828 D != DEnd; ++D) { 9829 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9830 if (Method->isInstance()) 9831 return true; 9832 } else { 9833 // Overload set does not contain methods. 9834 break; 9835 } 9836 } 9837 9838 return false; 9839 } 9840 9841 return false; 9842 } 9843 9844 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9845 UnaryOperatorKind Opc, Expr *Input) { 9846 // First things first: handle placeholders so that the 9847 // overloaded-operator check considers the right type. 9848 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9849 // Increment and decrement of pseudo-object references. 9850 if (pty->getKind() == BuiltinType::PseudoObject && 9851 UnaryOperator::isIncrementDecrementOp(Opc)) 9852 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9853 9854 // extension is always a builtin operator. 9855 if (Opc == UO_Extension) 9856 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9857 9858 // & gets special logic for several kinds of placeholder. 9859 // The builtin code knows what to do. 9860 if (Opc == UO_AddrOf && 9861 (pty->getKind() == BuiltinType::Overload || 9862 pty->getKind() == BuiltinType::UnknownAny || 9863 pty->getKind() == BuiltinType::BoundMember)) 9864 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9865 9866 // Anything else needs to be handled now. 9867 ExprResult Result = CheckPlaceholderExpr(Input); 9868 if (Result.isInvalid()) return ExprError(); 9869 Input = Result.take(); 9870 } 9871 9872 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9873 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9874 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9875 // Find all of the overloaded operators visible from this 9876 // point. We perform both an operator-name lookup from the local 9877 // scope and an argument-dependent lookup based on the types of 9878 // the arguments. 9879 UnresolvedSet<16> Functions; 9880 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9881 if (S && OverOp != OO_None) 9882 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9883 Functions); 9884 9885 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9886 } 9887 9888 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9889 } 9890 9891 // Unary Operators. 'Tok' is the token for the operator. 9892 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9893 tok::TokenKind Op, Expr *Input) { 9894 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9895 } 9896 9897 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9898 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9899 LabelDecl *TheDecl) { 9900 TheDecl->markUsed(Context); 9901 // Create the AST node. The address of a label always has type 'void*'. 9902 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9903 Context.getPointerType(Context.VoidTy))); 9904 } 9905 9906 /// Given the last statement in a statement-expression, check whether 9907 /// the result is a producing expression (like a call to an 9908 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9909 /// release out of the full-expression. Otherwise, return null. 9910 /// Cannot fail. 9911 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9912 // Should always be wrapped with one of these. 9913 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9914 if (!cleanups) return 0; 9915 9916 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9917 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9918 return 0; 9919 9920 // Splice out the cast. This shouldn't modify any interesting 9921 // features of the statement. 9922 Expr *producer = cast->getSubExpr(); 9923 assert(producer->getType() == cast->getType()); 9924 assert(producer->getValueKind() == cast->getValueKind()); 9925 cleanups->setSubExpr(producer); 9926 return cleanups; 9927 } 9928 9929 void Sema::ActOnStartStmtExpr() { 9930 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9931 } 9932 9933 void Sema::ActOnStmtExprError() { 9934 // Note that function is also called by TreeTransform when leaving a 9935 // StmtExpr scope without rebuilding anything. 9936 9937 DiscardCleanupsInEvaluationContext(); 9938 PopExpressionEvaluationContext(); 9939 } 9940 9941 ExprResult 9942 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9943 SourceLocation RPLoc) { // "({..})" 9944 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9945 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9946 9947 if (hasAnyUnrecoverableErrorsInThisFunction()) 9948 DiscardCleanupsInEvaluationContext(); 9949 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9950 PopExpressionEvaluationContext(); 9951 9952 bool isFileScope 9953 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9954 if (isFileScope) 9955 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9956 9957 // FIXME: there are a variety of strange constraints to enforce here, for 9958 // example, it is not possible to goto into a stmt expression apparently. 9959 // More semantic analysis is needed. 9960 9961 // If there are sub-stmts in the compound stmt, take the type of the last one 9962 // as the type of the stmtexpr. 9963 QualType Ty = Context.VoidTy; 9964 bool StmtExprMayBindToTemp = false; 9965 if (!Compound->body_empty()) { 9966 Stmt *LastStmt = Compound->body_back(); 9967 LabelStmt *LastLabelStmt = 0; 9968 // If LastStmt is a label, skip down through into the body. 9969 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9970 LastLabelStmt = Label; 9971 LastStmt = Label->getSubStmt(); 9972 } 9973 9974 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9975 // Do function/array conversion on the last expression, but not 9976 // lvalue-to-rvalue. However, initialize an unqualified type. 9977 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9978 if (LastExpr.isInvalid()) 9979 return ExprError(); 9980 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9981 9982 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9983 // In ARC, if the final expression ends in a consume, splice 9984 // the consume out and bind it later. In the alternate case 9985 // (when dealing with a retainable type), the result 9986 // initialization will create a produce. In both cases the 9987 // result will be +1, and we'll need to balance that out with 9988 // a bind. 9989 if (Expr *rebuiltLastStmt 9990 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9991 LastExpr = rebuiltLastStmt; 9992 } else { 9993 LastExpr = PerformCopyInitialization( 9994 InitializedEntity::InitializeResult(LPLoc, 9995 Ty, 9996 false), 9997 SourceLocation(), 9998 LastExpr); 9999 } 10000 10001 if (LastExpr.isInvalid()) 10002 return ExprError(); 10003 if (LastExpr.get() != 0) { 10004 if (!LastLabelStmt) 10005 Compound->setLastStmt(LastExpr.take()); 10006 else 10007 LastLabelStmt->setSubStmt(LastExpr.take()); 10008 StmtExprMayBindToTemp = true; 10009 } 10010 } 10011 } 10012 } 10013 10014 // FIXME: Check that expression type is complete/non-abstract; statement 10015 // expressions are not lvalues. 10016 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 10017 if (StmtExprMayBindToTemp) 10018 return MaybeBindToTemporary(ResStmtExpr); 10019 return Owned(ResStmtExpr); 10020 } 10021 10022 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 10023 TypeSourceInfo *TInfo, 10024 OffsetOfComponent *CompPtr, 10025 unsigned NumComponents, 10026 SourceLocation RParenLoc) { 10027 QualType ArgTy = TInfo->getType(); 10028 bool Dependent = ArgTy->isDependentType(); 10029 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 10030 10031 // We must have at least one component that refers to the type, and the first 10032 // one is known to be a field designator. Verify that the ArgTy represents 10033 // a struct/union/class. 10034 if (!Dependent && !ArgTy->isRecordType()) 10035 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 10036 << ArgTy << TypeRange); 10037 10038 // Type must be complete per C99 7.17p3 because a declaring a variable 10039 // with an incomplete type would be ill-formed. 10040 if (!Dependent 10041 && RequireCompleteType(BuiltinLoc, ArgTy, 10042 diag::err_offsetof_incomplete_type, TypeRange)) 10043 return ExprError(); 10044 10045 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 10046 // GCC extension, diagnose them. 10047 // FIXME: This diagnostic isn't actually visible because the location is in 10048 // a system header! 10049 if (NumComponents != 1) 10050 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 10051 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 10052 10053 bool DidWarnAboutNonPOD = false; 10054 QualType CurrentType = ArgTy; 10055 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 10056 SmallVector<OffsetOfNode, 4> Comps; 10057 SmallVector<Expr*, 4> Exprs; 10058 for (unsigned i = 0; i != NumComponents; ++i) { 10059 const OffsetOfComponent &OC = CompPtr[i]; 10060 if (OC.isBrackets) { 10061 // Offset of an array sub-field. TODO: Should we allow vector elements? 10062 if (!CurrentType->isDependentType()) { 10063 const ArrayType *AT = Context.getAsArrayType(CurrentType); 10064 if(!AT) 10065 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 10066 << CurrentType); 10067 CurrentType = AT->getElementType(); 10068 } else 10069 CurrentType = Context.DependentTy; 10070 10071 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 10072 if (IdxRval.isInvalid()) 10073 return ExprError(); 10074 Expr *Idx = IdxRval.take(); 10075 10076 // The expression must be an integral expression. 10077 // FIXME: An integral constant expression? 10078 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 10079 !Idx->getType()->isIntegerType()) 10080 return ExprError(Diag(Idx->getLocStart(), 10081 diag::err_typecheck_subscript_not_integer) 10082 << Idx->getSourceRange()); 10083 10084 // Record this array index. 10085 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 10086 Exprs.push_back(Idx); 10087 continue; 10088 } 10089 10090 // Offset of a field. 10091 if (CurrentType->isDependentType()) { 10092 // We have the offset of a field, but we can't look into the dependent 10093 // type. Just record the identifier of the field. 10094 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10095 CurrentType = Context.DependentTy; 10096 continue; 10097 } 10098 10099 // We need to have a complete type to look into. 10100 if (RequireCompleteType(OC.LocStart, CurrentType, 10101 diag::err_offsetof_incomplete_type)) 10102 return ExprError(); 10103 10104 // Look for the designated field. 10105 const RecordType *RC = CurrentType->getAs<RecordType>(); 10106 if (!RC) 10107 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10108 << CurrentType); 10109 RecordDecl *RD = RC->getDecl(); 10110 10111 // C++ [lib.support.types]p5: 10112 // The macro offsetof accepts a restricted set of type arguments in this 10113 // International Standard. type shall be a POD structure or a POD union 10114 // (clause 9). 10115 // C++11 [support.types]p4: 10116 // If type is not a standard-layout class (Clause 9), the results are 10117 // undefined. 10118 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10119 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10120 unsigned DiagID = 10121 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 10122 : diag::warn_offsetof_non_pod_type; 10123 10124 if (!IsSafe && !DidWarnAboutNonPOD && 10125 DiagRuntimeBehavior(BuiltinLoc, 0, 10126 PDiag(DiagID) 10127 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10128 << CurrentType)) 10129 DidWarnAboutNonPOD = true; 10130 } 10131 10132 // Look for the field. 10133 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10134 LookupQualifiedName(R, RD); 10135 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 10136 IndirectFieldDecl *IndirectMemberDecl = 0; 10137 if (!MemberDecl) { 10138 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 10139 MemberDecl = IndirectMemberDecl->getAnonField(); 10140 } 10141 10142 if (!MemberDecl) 10143 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 10144 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 10145 OC.LocEnd)); 10146 10147 // C99 7.17p3: 10148 // (If the specified member is a bit-field, the behavior is undefined.) 10149 // 10150 // We diagnose this as an error. 10151 if (MemberDecl->isBitField()) { 10152 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 10153 << MemberDecl->getDeclName() 10154 << SourceRange(BuiltinLoc, RParenLoc); 10155 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 10156 return ExprError(); 10157 } 10158 10159 RecordDecl *Parent = MemberDecl->getParent(); 10160 if (IndirectMemberDecl) 10161 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 10162 10163 // If the member was found in a base class, introduce OffsetOfNodes for 10164 // the base class indirections. 10165 CXXBasePaths Paths; 10166 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 10167 if (Paths.getDetectedVirtual()) { 10168 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 10169 << MemberDecl->getDeclName() 10170 << SourceRange(BuiltinLoc, RParenLoc); 10171 return ExprError(); 10172 } 10173 10174 CXXBasePath &Path = Paths.front(); 10175 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10176 B != BEnd; ++B) 10177 Comps.push_back(OffsetOfNode(B->Base)); 10178 } 10179 10180 if (IndirectMemberDecl) { 10181 for (IndirectFieldDecl::chain_iterator FI = 10182 IndirectMemberDecl->chain_begin(), 10183 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 10184 assert(isa<FieldDecl>(*FI)); 10185 Comps.push_back(OffsetOfNode(OC.LocStart, 10186 cast<FieldDecl>(*FI), OC.LocEnd)); 10187 } 10188 } else 10189 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10190 10191 CurrentType = MemberDecl->getType().getNonReferenceType(); 10192 } 10193 10194 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 10195 TInfo, Comps, Exprs, RParenLoc)); 10196 } 10197 10198 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10199 SourceLocation BuiltinLoc, 10200 SourceLocation TypeLoc, 10201 ParsedType ParsedArgTy, 10202 OffsetOfComponent *CompPtr, 10203 unsigned NumComponents, 10204 SourceLocation RParenLoc) { 10205 10206 TypeSourceInfo *ArgTInfo; 10207 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10208 if (ArgTy.isNull()) 10209 return ExprError(); 10210 10211 if (!ArgTInfo) 10212 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10213 10214 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10215 RParenLoc); 10216 } 10217 10218 10219 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10220 Expr *CondExpr, 10221 Expr *LHSExpr, Expr *RHSExpr, 10222 SourceLocation RPLoc) { 10223 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10224 10225 ExprValueKind VK = VK_RValue; 10226 ExprObjectKind OK = OK_Ordinary; 10227 QualType resType; 10228 bool ValueDependent = false; 10229 bool CondIsTrue = false; 10230 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10231 resType = Context.DependentTy; 10232 ValueDependent = true; 10233 } else { 10234 // The conditional expression is required to be a constant expression. 10235 llvm::APSInt condEval(32); 10236 ExprResult CondICE 10237 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10238 diag::err_typecheck_choose_expr_requires_constant, false); 10239 if (CondICE.isInvalid()) 10240 return ExprError(); 10241 CondExpr = CondICE.take(); 10242 CondIsTrue = condEval.getZExtValue(); 10243 10244 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10245 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10246 10247 resType = ActiveExpr->getType(); 10248 ValueDependent = ActiveExpr->isValueDependent(); 10249 VK = ActiveExpr->getValueKind(); 10250 OK = ActiveExpr->getObjectKind(); 10251 } 10252 10253 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 10254 resType, VK, OK, RPLoc, CondIsTrue, 10255 resType->isDependentType(), 10256 ValueDependent)); 10257 } 10258 10259 //===----------------------------------------------------------------------===// 10260 // Clang Extensions. 10261 //===----------------------------------------------------------------------===// 10262 10263 /// ActOnBlockStart - This callback is invoked when a block literal is started. 10264 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10265 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10266 10267 if (LangOpts.CPlusPlus) { 10268 Decl *ManglingContextDecl; 10269 if (MangleNumberingContext *MCtx = 10270 getCurrentMangleNumberContext(Block->getDeclContext(), 10271 ManglingContextDecl)) { 10272 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10273 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10274 } 10275 } 10276 10277 PushBlockScope(CurScope, Block); 10278 CurContext->addDecl(Block); 10279 if (CurScope) 10280 PushDeclContext(CurScope, Block); 10281 else 10282 CurContext = Block; 10283 10284 getCurBlock()->HasImplicitReturnType = true; 10285 10286 // Enter a new evaluation context to insulate the block from any 10287 // cleanups from the enclosing full-expression. 10288 PushExpressionEvaluationContext(PotentiallyEvaluated); 10289 } 10290 10291 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10292 Scope *CurScope) { 10293 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 10294 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10295 BlockScopeInfo *CurBlock = getCurBlock(); 10296 10297 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10298 QualType T = Sig->getType(); 10299 10300 // FIXME: We should allow unexpanded parameter packs here, but that would, 10301 // in turn, make the block expression contain unexpanded parameter packs. 10302 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10303 // Drop the parameters. 10304 FunctionProtoType::ExtProtoInfo EPI; 10305 EPI.HasTrailingReturn = false; 10306 EPI.TypeQuals |= DeclSpec::TQ_const; 10307 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10308 Sig = Context.getTrivialTypeSourceInfo(T); 10309 } 10310 10311 // GetTypeForDeclarator always produces a function type for a block 10312 // literal signature. Furthermore, it is always a FunctionProtoType 10313 // unless the function was written with a typedef. 10314 assert(T->isFunctionType() && 10315 "GetTypeForDeclarator made a non-function block signature"); 10316 10317 // Look for an explicit signature in that function type. 10318 FunctionProtoTypeLoc ExplicitSignature; 10319 10320 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10321 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10322 10323 // Check whether that explicit signature was synthesized by 10324 // GetTypeForDeclarator. If so, don't save that as part of the 10325 // written signature. 10326 if (ExplicitSignature.getLocalRangeBegin() == 10327 ExplicitSignature.getLocalRangeEnd()) { 10328 // This would be much cheaper if we stored TypeLocs instead of 10329 // TypeSourceInfos. 10330 TypeLoc Result = ExplicitSignature.getReturnLoc(); 10331 unsigned Size = Result.getFullDataSize(); 10332 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10333 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10334 10335 ExplicitSignature = FunctionProtoTypeLoc(); 10336 } 10337 } 10338 10339 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10340 CurBlock->FunctionType = T; 10341 10342 const FunctionType *Fn = T->getAs<FunctionType>(); 10343 QualType RetTy = Fn->getReturnType(); 10344 bool isVariadic = 10345 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10346 10347 CurBlock->TheDecl->setIsVariadic(isVariadic); 10348 10349 // Context.DependentTy is used as a placeholder for a missing block 10350 // return type. TODO: what should we do with declarators like: 10351 // ^ * { ... } 10352 // If the answer is "apply template argument deduction".... 10353 if (RetTy != Context.DependentTy) { 10354 CurBlock->ReturnType = RetTy; 10355 CurBlock->TheDecl->setBlockMissingReturnType(false); 10356 CurBlock->HasImplicitReturnType = false; 10357 } 10358 10359 // Push block parameters from the declarator if we had them. 10360 SmallVector<ParmVarDecl*, 8> Params; 10361 if (ExplicitSignature) { 10362 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 10363 ParmVarDecl *Param = ExplicitSignature.getParam(I); 10364 if (Param->getIdentifier() == 0 && 10365 !Param->isImplicit() && 10366 !Param->isInvalidDecl() && 10367 !getLangOpts().CPlusPlus) 10368 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10369 Params.push_back(Param); 10370 } 10371 10372 // Fake up parameter variables if we have a typedef, like 10373 // ^ fntype { ... } 10374 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10375 for (FunctionProtoType::param_type_iterator I = Fn->param_type_begin(), 10376 E = Fn->param_type_end(); 10377 I != E; ++I) { 10378 ParmVarDecl *Param = 10379 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 10380 ParamInfo.getLocStart(), 10381 *I); 10382 Params.push_back(Param); 10383 } 10384 } 10385 10386 // Set the parameters on the block decl. 10387 if (!Params.empty()) { 10388 CurBlock->TheDecl->setParams(Params); 10389 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10390 CurBlock->TheDecl->param_end(), 10391 /*CheckParameterNames=*/false); 10392 } 10393 10394 // Finally we can process decl attributes. 10395 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10396 10397 // Put the parameter variables in scope. 10398 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 10399 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 10400 (*AI)->setOwningFunction(CurBlock->TheDecl); 10401 10402 // If this has an identifier, add it to the scope stack. 10403 if ((*AI)->getIdentifier()) { 10404 CheckShadow(CurBlock->TheScope, *AI); 10405 10406 PushOnScopeChains(*AI, CurBlock->TheScope); 10407 } 10408 } 10409 } 10410 10411 /// ActOnBlockError - If there is an error parsing a block, this callback 10412 /// is invoked to pop the information about the block from the action impl. 10413 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10414 // Leave the expression-evaluation context. 10415 DiscardCleanupsInEvaluationContext(); 10416 PopExpressionEvaluationContext(); 10417 10418 // Pop off CurBlock, handle nested blocks. 10419 PopDeclContext(); 10420 PopFunctionScopeInfo(); 10421 } 10422 10423 /// ActOnBlockStmtExpr - This is called when the body of a block statement 10424 /// literal was successfully completed. ^(int x){...} 10425 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10426 Stmt *Body, Scope *CurScope) { 10427 // If blocks are disabled, emit an error. 10428 if (!LangOpts.Blocks) 10429 Diag(CaretLoc, diag::err_blocks_disable); 10430 10431 // Leave the expression-evaluation context. 10432 if (hasAnyUnrecoverableErrorsInThisFunction()) 10433 DiscardCleanupsInEvaluationContext(); 10434 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10435 PopExpressionEvaluationContext(); 10436 10437 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10438 10439 if (BSI->HasImplicitReturnType) 10440 deduceClosureReturnType(*BSI); 10441 10442 PopDeclContext(); 10443 10444 QualType RetTy = Context.VoidTy; 10445 if (!BSI->ReturnType.isNull()) 10446 RetTy = BSI->ReturnType; 10447 10448 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 10449 QualType BlockTy; 10450 10451 // Set the captured variables on the block. 10452 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10453 SmallVector<BlockDecl::Capture, 4> Captures; 10454 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10455 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10456 if (Cap.isThisCapture()) 10457 continue; 10458 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10459 Cap.isNested(), Cap.getInitExpr()); 10460 Captures.push_back(NewCap); 10461 } 10462 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10463 BSI->CXXThisCaptureIndex != 0); 10464 10465 // If the user wrote a function type in some form, try to use that. 10466 if (!BSI->FunctionType.isNull()) { 10467 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10468 10469 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10470 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10471 10472 // Turn protoless block types into nullary block types. 10473 if (isa<FunctionNoProtoType>(FTy)) { 10474 FunctionProtoType::ExtProtoInfo EPI; 10475 EPI.ExtInfo = Ext; 10476 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10477 10478 // Otherwise, if we don't need to change anything about the function type, 10479 // preserve its sugar structure. 10480 } else if (FTy->getReturnType() == RetTy && 10481 (!NoReturn || FTy->getNoReturnAttr())) { 10482 BlockTy = BSI->FunctionType; 10483 10484 // Otherwise, make the minimal modifications to the function type. 10485 } else { 10486 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10487 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10488 EPI.TypeQuals = 0; // FIXME: silently? 10489 EPI.ExtInfo = Ext; 10490 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 10491 } 10492 10493 // If we don't have a function type, just build one from nothing. 10494 } else { 10495 FunctionProtoType::ExtProtoInfo EPI; 10496 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10497 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10498 } 10499 10500 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10501 BSI->TheDecl->param_end()); 10502 BlockTy = Context.getBlockPointerType(BlockTy); 10503 10504 // If needed, diagnose invalid gotos and switches in the block. 10505 if (getCurFunction()->NeedsScopeChecking() && 10506 !hasAnyUnrecoverableErrorsInThisFunction() && 10507 !PP.isCodeCompletionEnabled()) 10508 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10509 10510 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10511 10512 // Try to apply the named return value optimization. We have to check again 10513 // if we can do this, though, because blocks keep return statements around 10514 // to deduce an implicit return type. 10515 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10516 !BSI->TheDecl->isDependentContext()) 10517 computeNRVO(Body, getCurBlock()); 10518 10519 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10520 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10521 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10522 10523 // If the block isn't obviously global, i.e. it captures anything at 10524 // all, then we need to do a few things in the surrounding context: 10525 if (Result->getBlockDecl()->hasCaptures()) { 10526 // First, this expression has a new cleanup object. 10527 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10528 ExprNeedsCleanups = true; 10529 10530 // It also gets a branch-protected scope if any of the captured 10531 // variables needs destruction. 10532 for (BlockDecl::capture_const_iterator 10533 ci = Result->getBlockDecl()->capture_begin(), 10534 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10535 const VarDecl *var = ci->getVariable(); 10536 if (var->getType().isDestructedType() != QualType::DK_none) { 10537 getCurFunction()->setHasBranchProtectedScope(); 10538 break; 10539 } 10540 } 10541 } 10542 10543 return Owned(Result); 10544 } 10545 10546 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10547 Expr *E, ParsedType Ty, 10548 SourceLocation RPLoc) { 10549 TypeSourceInfo *TInfo; 10550 GetTypeFromParser(Ty, &TInfo); 10551 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10552 } 10553 10554 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10555 Expr *E, TypeSourceInfo *TInfo, 10556 SourceLocation RPLoc) { 10557 Expr *OrigExpr = E; 10558 10559 // Get the va_list type 10560 QualType VaListType = Context.getBuiltinVaListType(); 10561 if (VaListType->isArrayType()) { 10562 // Deal with implicit array decay; for example, on x86-64, 10563 // va_list is an array, but it's supposed to decay to 10564 // a pointer for va_arg. 10565 VaListType = Context.getArrayDecayedType(VaListType); 10566 // Make sure the input expression also decays appropriately. 10567 ExprResult Result = UsualUnaryConversions(E); 10568 if (Result.isInvalid()) 10569 return ExprError(); 10570 E = Result.take(); 10571 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10572 // If va_list is a record type and we are compiling in C++ mode, 10573 // check the argument using reference binding. 10574 InitializedEntity Entity 10575 = InitializedEntity::InitializeParameter(Context, 10576 Context.getLValueReferenceType(VaListType), false); 10577 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10578 if (Init.isInvalid()) 10579 return ExprError(); 10580 E = Init.takeAs<Expr>(); 10581 } else { 10582 // Otherwise, the va_list argument must be an l-value because 10583 // it is modified by va_arg. 10584 if (!E->isTypeDependent() && 10585 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10586 return ExprError(); 10587 } 10588 10589 if (!E->isTypeDependent() && 10590 !Context.hasSameType(VaListType, E->getType())) { 10591 return ExprError(Diag(E->getLocStart(), 10592 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10593 << OrigExpr->getType() << E->getSourceRange()); 10594 } 10595 10596 if (!TInfo->getType()->isDependentType()) { 10597 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10598 diag::err_second_parameter_to_va_arg_incomplete, 10599 TInfo->getTypeLoc())) 10600 return ExprError(); 10601 10602 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10603 TInfo->getType(), 10604 diag::err_second_parameter_to_va_arg_abstract, 10605 TInfo->getTypeLoc())) 10606 return ExprError(); 10607 10608 if (!TInfo->getType().isPODType(Context)) { 10609 Diag(TInfo->getTypeLoc().getBeginLoc(), 10610 TInfo->getType()->isObjCLifetimeType() 10611 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10612 : diag::warn_second_parameter_to_va_arg_not_pod) 10613 << TInfo->getType() 10614 << TInfo->getTypeLoc().getSourceRange(); 10615 } 10616 10617 // Check for va_arg where arguments of the given type will be promoted 10618 // (i.e. this va_arg is guaranteed to have undefined behavior). 10619 QualType PromoteType; 10620 if (TInfo->getType()->isPromotableIntegerType()) { 10621 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10622 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10623 PromoteType = QualType(); 10624 } 10625 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10626 PromoteType = Context.DoubleTy; 10627 if (!PromoteType.isNull()) 10628 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10629 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10630 << TInfo->getType() 10631 << PromoteType 10632 << TInfo->getTypeLoc().getSourceRange()); 10633 } 10634 10635 QualType T = TInfo->getType().getNonLValueExprType(Context); 10636 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10637 } 10638 10639 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10640 // The type of __null will be int or long, depending on the size of 10641 // pointers on the target. 10642 QualType Ty; 10643 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10644 if (pw == Context.getTargetInfo().getIntWidth()) 10645 Ty = Context.IntTy; 10646 else if (pw == Context.getTargetInfo().getLongWidth()) 10647 Ty = Context.LongTy; 10648 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10649 Ty = Context.LongLongTy; 10650 else { 10651 llvm_unreachable("I don't know size of pointer!"); 10652 } 10653 10654 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10655 } 10656 10657 bool 10658 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 10659 if (!getLangOpts().ObjC1) 10660 return false; 10661 10662 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10663 if (!PT) 10664 return false; 10665 10666 if (!PT->isObjCIdType()) { 10667 // Check if the destination is the 'NSString' interface. 10668 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10669 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10670 return false; 10671 } 10672 10673 // Ignore any parens, implicit casts (should only be 10674 // array-to-pointer decays), and not-so-opaque values. The last is 10675 // important for making this trigger for property assignments. 10676 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 10677 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10678 if (OV->getSourceExpr()) 10679 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10680 10681 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10682 if (!SL || !SL->isAscii()) 10683 return false; 10684 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 10685 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10686 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).take(); 10687 return true; 10688 } 10689 10690 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10691 SourceLocation Loc, 10692 QualType DstType, QualType SrcType, 10693 Expr *SrcExpr, AssignmentAction Action, 10694 bool *Complained) { 10695 if (Complained) 10696 *Complained = false; 10697 10698 // Decode the result (notice that AST's are still created for extensions). 10699 bool CheckInferredResultType = false; 10700 bool isInvalid = false; 10701 unsigned DiagKind = 0; 10702 FixItHint Hint; 10703 ConversionFixItGenerator ConvHints; 10704 bool MayHaveConvFixit = false; 10705 bool MayHaveFunctionDiff = false; 10706 10707 switch (ConvTy) { 10708 case Compatible: 10709 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10710 return false; 10711 10712 case PointerToInt: 10713 DiagKind = diag::ext_typecheck_convert_pointer_int; 10714 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10715 MayHaveConvFixit = true; 10716 break; 10717 case IntToPointer: 10718 DiagKind = diag::ext_typecheck_convert_int_pointer; 10719 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10720 MayHaveConvFixit = true; 10721 break; 10722 case IncompatiblePointer: 10723 DiagKind = 10724 (Action == AA_Passing_CFAudited ? 10725 diag::err_arc_typecheck_convert_incompatible_pointer : 10726 diag::ext_typecheck_convert_incompatible_pointer); 10727 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10728 SrcType->isObjCObjectPointerType(); 10729 if (Hint.isNull() && !CheckInferredResultType) { 10730 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10731 } 10732 else if (CheckInferredResultType) { 10733 SrcType = SrcType.getUnqualifiedType(); 10734 DstType = DstType.getUnqualifiedType(); 10735 } 10736 MayHaveConvFixit = true; 10737 break; 10738 case IncompatiblePointerSign: 10739 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10740 break; 10741 case FunctionVoidPointer: 10742 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10743 break; 10744 case IncompatiblePointerDiscardsQualifiers: { 10745 // Perform array-to-pointer decay if necessary. 10746 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10747 10748 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10749 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10750 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10751 DiagKind = diag::err_typecheck_incompatible_address_space; 10752 break; 10753 10754 10755 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10756 DiagKind = diag::err_typecheck_incompatible_ownership; 10757 break; 10758 } 10759 10760 llvm_unreachable("unknown error case for discarding qualifiers!"); 10761 // fallthrough 10762 } 10763 case CompatiblePointerDiscardsQualifiers: 10764 // If the qualifiers lost were because we were applying the 10765 // (deprecated) C++ conversion from a string literal to a char* 10766 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10767 // Ideally, this check would be performed in 10768 // checkPointerTypesForAssignment. However, that would require a 10769 // bit of refactoring (so that the second argument is an 10770 // expression, rather than a type), which should be done as part 10771 // of a larger effort to fix checkPointerTypesForAssignment for 10772 // C++ semantics. 10773 if (getLangOpts().CPlusPlus && 10774 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10775 return false; 10776 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10777 break; 10778 case IncompatibleNestedPointerQualifiers: 10779 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10780 break; 10781 case IntToBlockPointer: 10782 DiagKind = diag::err_int_to_block_pointer; 10783 break; 10784 case IncompatibleBlockPointer: 10785 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10786 break; 10787 case IncompatibleObjCQualifiedId: 10788 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10789 // it can give a more specific diagnostic. 10790 DiagKind = diag::warn_incompatible_qualified_id; 10791 break; 10792 case IncompatibleVectors: 10793 DiagKind = diag::warn_incompatible_vectors; 10794 break; 10795 case IncompatibleObjCWeakRef: 10796 DiagKind = diag::err_arc_weak_unavailable_assign; 10797 break; 10798 case Incompatible: 10799 DiagKind = diag::err_typecheck_convert_incompatible; 10800 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10801 MayHaveConvFixit = true; 10802 isInvalid = true; 10803 MayHaveFunctionDiff = true; 10804 break; 10805 } 10806 10807 QualType FirstType, SecondType; 10808 switch (Action) { 10809 case AA_Assigning: 10810 case AA_Initializing: 10811 // The destination type comes first. 10812 FirstType = DstType; 10813 SecondType = SrcType; 10814 break; 10815 10816 case AA_Returning: 10817 case AA_Passing: 10818 case AA_Passing_CFAudited: 10819 case AA_Converting: 10820 case AA_Sending: 10821 case AA_Casting: 10822 // The source type comes first. 10823 FirstType = SrcType; 10824 SecondType = DstType; 10825 break; 10826 } 10827 10828 PartialDiagnostic FDiag = PDiag(DiagKind); 10829 if (Action == AA_Passing_CFAudited) 10830 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 10831 else 10832 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10833 10834 // If we can fix the conversion, suggest the FixIts. 10835 assert(ConvHints.isNull() || Hint.isNull()); 10836 if (!ConvHints.isNull()) { 10837 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10838 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10839 FDiag << *HI; 10840 } else { 10841 FDiag << Hint; 10842 } 10843 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10844 10845 if (MayHaveFunctionDiff) 10846 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10847 10848 Diag(Loc, FDiag); 10849 10850 if (SecondType == Context.OverloadTy) 10851 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10852 FirstType); 10853 10854 if (CheckInferredResultType) 10855 EmitRelatedResultTypeNote(SrcExpr); 10856 10857 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10858 EmitRelatedResultTypeNoteForReturn(DstType); 10859 10860 if (Complained) 10861 *Complained = true; 10862 return isInvalid; 10863 } 10864 10865 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10866 llvm::APSInt *Result) { 10867 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10868 public: 10869 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10870 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10871 } 10872 } Diagnoser; 10873 10874 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10875 } 10876 10877 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10878 llvm::APSInt *Result, 10879 unsigned DiagID, 10880 bool AllowFold) { 10881 class IDDiagnoser : public VerifyICEDiagnoser { 10882 unsigned DiagID; 10883 10884 public: 10885 IDDiagnoser(unsigned DiagID) 10886 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10887 10888 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10889 S.Diag(Loc, DiagID) << SR; 10890 } 10891 } Diagnoser(DiagID); 10892 10893 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10894 } 10895 10896 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10897 SourceRange SR) { 10898 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10899 } 10900 10901 ExprResult 10902 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10903 VerifyICEDiagnoser &Diagnoser, 10904 bool AllowFold) { 10905 SourceLocation DiagLoc = E->getLocStart(); 10906 10907 if (getLangOpts().CPlusPlus11) { 10908 // C++11 [expr.const]p5: 10909 // If an expression of literal class type is used in a context where an 10910 // integral constant expression is required, then that class type shall 10911 // have a single non-explicit conversion function to an integral or 10912 // unscoped enumeration type 10913 ExprResult Converted; 10914 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10915 public: 10916 CXX11ConvertDiagnoser(bool Silent) 10917 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10918 Silent, true) {} 10919 10920 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10921 QualType T) { 10922 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10923 } 10924 10925 virtual SemaDiagnosticBuilder diagnoseIncomplete( 10926 Sema &S, SourceLocation Loc, QualType T) { 10927 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10928 } 10929 10930 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 10931 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10932 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10933 } 10934 10935 virtual SemaDiagnosticBuilder noteExplicitConv( 10936 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10937 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10938 << ConvTy->isEnumeralType() << ConvTy; 10939 } 10940 10941 virtual SemaDiagnosticBuilder diagnoseAmbiguous( 10942 Sema &S, SourceLocation Loc, QualType T) { 10943 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10944 } 10945 10946 virtual SemaDiagnosticBuilder noteAmbiguous( 10947 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10948 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10949 << ConvTy->isEnumeralType() << ConvTy; 10950 } 10951 10952 virtual SemaDiagnosticBuilder diagnoseConversion( 10953 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10954 llvm_unreachable("conversion functions are permitted"); 10955 } 10956 } ConvertDiagnoser(Diagnoser.Suppress); 10957 10958 Converted = PerformContextualImplicitConversion(DiagLoc, E, 10959 ConvertDiagnoser); 10960 if (Converted.isInvalid()) 10961 return Converted; 10962 E = Converted.take(); 10963 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10964 return ExprError(); 10965 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10966 // An ICE must be of integral or unscoped enumeration type. 10967 if (!Diagnoser.Suppress) 10968 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10969 return ExprError(); 10970 } 10971 10972 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10973 // in the non-ICE case. 10974 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10975 if (Result) 10976 *Result = E->EvaluateKnownConstInt(Context); 10977 return Owned(E); 10978 } 10979 10980 Expr::EvalResult EvalResult; 10981 SmallVector<PartialDiagnosticAt, 8> Notes; 10982 EvalResult.Diag = &Notes; 10983 10984 // Try to evaluate the expression, and produce diagnostics explaining why it's 10985 // not a constant expression as a side-effect. 10986 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10987 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10988 10989 // In C++11, we can rely on diagnostics being produced for any expression 10990 // which is not a constant expression. If no diagnostics were produced, then 10991 // this is a constant expression. 10992 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10993 if (Result) 10994 *Result = EvalResult.Val.getInt(); 10995 return Owned(E); 10996 } 10997 10998 // If our only note is the usual "invalid subexpression" note, just point 10999 // the caret at its location rather than producing an essentially 11000 // redundant note. 11001 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11002 diag::note_invalid_subexpr_in_const_expr) { 11003 DiagLoc = Notes[0].first; 11004 Notes.clear(); 11005 } 11006 11007 if (!Folded || !AllowFold) { 11008 if (!Diagnoser.Suppress) { 11009 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11010 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11011 Diag(Notes[I].first, Notes[I].second); 11012 } 11013 11014 return ExprError(); 11015 } 11016 11017 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 11018 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11019 Diag(Notes[I].first, Notes[I].second); 11020 11021 if (Result) 11022 *Result = EvalResult.Val.getInt(); 11023 return Owned(E); 11024 } 11025 11026 namespace { 11027 // Handle the case where we conclude a expression which we speculatively 11028 // considered to be unevaluated is actually evaluated. 11029 class TransformToPE : public TreeTransform<TransformToPE> { 11030 typedef TreeTransform<TransformToPE> BaseTransform; 11031 11032 public: 11033 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 11034 11035 // Make sure we redo semantic analysis 11036 bool AlwaysRebuild() { return true; } 11037 11038 // Make sure we handle LabelStmts correctly. 11039 // FIXME: This does the right thing, but maybe we need a more general 11040 // fix to TreeTransform? 11041 StmtResult TransformLabelStmt(LabelStmt *S) { 11042 S->getDecl()->setStmt(0); 11043 return BaseTransform::TransformLabelStmt(S); 11044 } 11045 11046 // We need to special-case DeclRefExprs referring to FieldDecls which 11047 // are not part of a member pointer formation; normal TreeTransforming 11048 // doesn't catch this case because of the way we represent them in the AST. 11049 // FIXME: This is a bit ugly; is it really the best way to handle this 11050 // case? 11051 // 11052 // Error on DeclRefExprs referring to FieldDecls. 11053 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 11054 if (isa<FieldDecl>(E->getDecl()) && 11055 !SemaRef.isUnevaluatedContext()) 11056 return SemaRef.Diag(E->getLocation(), 11057 diag::err_invalid_non_static_member_use) 11058 << E->getDecl() << E->getSourceRange(); 11059 11060 return BaseTransform::TransformDeclRefExpr(E); 11061 } 11062 11063 // Exception: filter out member pointer formation 11064 ExprResult TransformUnaryOperator(UnaryOperator *E) { 11065 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 11066 return E; 11067 11068 return BaseTransform::TransformUnaryOperator(E); 11069 } 11070 11071 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11072 // Lambdas never need to be transformed. 11073 return E; 11074 } 11075 }; 11076 } 11077 11078 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 11079 assert(isUnevaluatedContext() && 11080 "Should only transform unevaluated expressions"); 11081 ExprEvalContexts.back().Context = 11082 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 11083 if (isUnevaluatedContext()) 11084 return E; 11085 return TransformToPE(*this).TransformExpr(E); 11086 } 11087 11088 void 11089 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11090 Decl *LambdaContextDecl, 11091 bool IsDecltype) { 11092 ExprEvalContexts.push_back( 11093 ExpressionEvaluationContextRecord(NewContext, 11094 ExprCleanupObjects.size(), 11095 ExprNeedsCleanups, 11096 LambdaContextDecl, 11097 IsDecltype)); 11098 ExprNeedsCleanups = false; 11099 if (!MaybeODRUseExprs.empty()) 11100 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11101 } 11102 11103 void 11104 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11105 ReuseLambdaContextDecl_t, 11106 bool IsDecltype) { 11107 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11108 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11109 } 11110 11111 void Sema::PopExpressionEvaluationContext() { 11112 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11113 11114 if (!Rec.Lambdas.empty()) { 11115 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11116 unsigned D; 11117 if (Rec.isUnevaluated()) { 11118 // C++11 [expr.prim.lambda]p2: 11119 // A lambda-expression shall not appear in an unevaluated operand 11120 // (Clause 5). 11121 D = diag::err_lambda_unevaluated_operand; 11122 } else { 11123 // C++1y [expr.const]p2: 11124 // A conditional-expression e is a core constant expression unless the 11125 // evaluation of e, following the rules of the abstract machine, would 11126 // evaluate [...] a lambda-expression. 11127 D = diag::err_lambda_in_constant_expression; 11128 } 11129 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 11130 Diag(Rec.Lambdas[I]->getLocStart(), D); 11131 } else { 11132 // Mark the capture expressions odr-used. This was deferred 11133 // during lambda expression creation. 11134 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 11135 LambdaExpr *Lambda = Rec.Lambdas[I]; 11136 for (LambdaExpr::capture_init_iterator 11137 C = Lambda->capture_init_begin(), 11138 CEnd = Lambda->capture_init_end(); 11139 C != CEnd; ++C) { 11140 MarkDeclarationsReferencedInExpr(*C); 11141 } 11142 } 11143 } 11144 } 11145 11146 // When are coming out of an unevaluated context, clear out any 11147 // temporaries that we may have created as part of the evaluation of 11148 // the expression in that context: they aren't relevant because they 11149 // will never be constructed. 11150 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11151 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 11152 ExprCleanupObjects.end()); 11153 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 11154 CleanupVarDeclMarking(); 11155 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 11156 // Otherwise, merge the contexts together. 11157 } else { 11158 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 11159 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 11160 Rec.SavedMaybeODRUseExprs.end()); 11161 } 11162 11163 // Pop the current expression evaluation context off the stack. 11164 ExprEvalContexts.pop_back(); 11165 } 11166 11167 void Sema::DiscardCleanupsInEvaluationContext() { 11168 ExprCleanupObjects.erase( 11169 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 11170 ExprCleanupObjects.end()); 11171 ExprNeedsCleanups = false; 11172 MaybeODRUseExprs.clear(); 11173 } 11174 11175 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 11176 if (!E->getType()->isVariablyModifiedType()) 11177 return E; 11178 return TransformToPotentiallyEvaluated(E); 11179 } 11180 11181 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11182 // Do not mark anything as "used" within a dependent context; wait for 11183 // an instantiation. 11184 if (SemaRef.CurContext->isDependentContext()) 11185 return false; 11186 11187 switch (SemaRef.ExprEvalContexts.back().Context) { 11188 case Sema::Unevaluated: 11189 case Sema::UnevaluatedAbstract: 11190 // We are in an expression that is not potentially evaluated; do nothing. 11191 // (Depending on how you read the standard, we actually do need to do 11192 // something here for null pointer constants, but the standard's 11193 // definition of a null pointer constant is completely crazy.) 11194 return false; 11195 11196 case Sema::ConstantEvaluated: 11197 case Sema::PotentiallyEvaluated: 11198 // We are in a potentially evaluated expression (or a constant-expression 11199 // in C++03); we need to do implicit template instantiation, implicitly 11200 // define class members, and mark most declarations as used. 11201 return true; 11202 11203 case Sema::PotentiallyEvaluatedIfUsed: 11204 // Referenced declarations will only be used if the construct in the 11205 // containing expression is used. 11206 return false; 11207 } 11208 llvm_unreachable("Invalid context"); 11209 } 11210 11211 /// \brief Mark a function referenced, and check whether it is odr-used 11212 /// (C++ [basic.def.odr]p2, C99 6.9p3) 11213 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 11214 assert(Func && "No function?"); 11215 11216 Func->setReferenced(); 11217 11218 // C++11 [basic.def.odr]p3: 11219 // A function whose name appears as a potentially-evaluated expression is 11220 // odr-used if it is the unique lookup result or the selected member of a 11221 // set of overloaded functions [...]. 11222 // 11223 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11224 // can just check that here. Skip the rest of this function if we've already 11225 // marked the function as used. 11226 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11227 // C++11 [temp.inst]p3: 11228 // Unless a function template specialization has been explicitly 11229 // instantiated or explicitly specialized, the function template 11230 // specialization is implicitly instantiated when the specialization is 11231 // referenced in a context that requires a function definition to exist. 11232 // 11233 // We consider constexpr function templates to be referenced in a context 11234 // that requires a definition to exist whenever they are referenced. 11235 // 11236 // FIXME: This instantiates constexpr functions too frequently. If this is 11237 // really an unevaluated context (and we're not just in the definition of a 11238 // function template or overload resolution or other cases which we 11239 // incorrectly consider to be unevaluated contexts), and we're not in a 11240 // subexpression which we actually need to evaluate (for instance, a 11241 // template argument, array bound or an expression in a braced-init-list), 11242 // we are not permitted to instantiate this constexpr function definition. 11243 // 11244 // FIXME: This also implicitly defines special members too frequently. They 11245 // are only supposed to be implicitly defined if they are odr-used, but they 11246 // are not odr-used from constant expressions in unevaluated contexts. 11247 // However, they cannot be referenced if they are deleted, and they are 11248 // deleted whenever the implicit definition of the special member would 11249 // fail. 11250 if (!Func->isConstexpr() || Func->getBody()) 11251 return; 11252 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11253 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11254 return; 11255 } 11256 11257 // Note that this declaration has been used. 11258 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11259 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 11260 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11261 if (Constructor->isDefaultConstructor()) { 11262 if (Constructor->isTrivial()) 11263 return; 11264 DefineImplicitDefaultConstructor(Loc, Constructor); 11265 } else if (Constructor->isCopyConstructor()) { 11266 DefineImplicitCopyConstructor(Loc, Constructor); 11267 } else if (Constructor->isMoveConstructor()) { 11268 DefineImplicitMoveConstructor(Loc, Constructor); 11269 } 11270 } else if (Constructor->getInheritedConstructor()) { 11271 DefineInheritingConstructor(Loc, Constructor); 11272 } 11273 11274 MarkVTableUsed(Loc, Constructor->getParent()); 11275 } else if (CXXDestructorDecl *Destructor = 11276 dyn_cast<CXXDestructorDecl>(Func)) { 11277 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 11278 if (Destructor->isDefaulted() && !Destructor->isDeleted()) 11279 DefineImplicitDestructor(Loc, Destructor); 11280 if (Destructor->isVirtual()) 11281 MarkVTableUsed(Loc, Destructor->getParent()); 11282 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11283 if (MethodDecl->isOverloadedOperator() && 11284 MethodDecl->getOverloadedOperator() == OO_Equal) { 11285 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 11286 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 11287 if (MethodDecl->isCopyAssignmentOperator()) 11288 DefineImplicitCopyAssignment(Loc, MethodDecl); 11289 else 11290 DefineImplicitMoveAssignment(Loc, MethodDecl); 11291 } 11292 } else if (isa<CXXConversionDecl>(MethodDecl) && 11293 MethodDecl->getParent()->isLambda()) { 11294 CXXConversionDecl *Conversion = 11295 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 11296 if (Conversion->isLambdaToBlockPointerConversion()) 11297 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11298 else 11299 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11300 } else if (MethodDecl->isVirtual()) 11301 MarkVTableUsed(Loc, MethodDecl->getParent()); 11302 } 11303 11304 // Recursive functions should be marked when used from another function. 11305 // FIXME: Is this really right? 11306 if (CurContext == Func) return; 11307 11308 // Resolve the exception specification for any function which is 11309 // used: CodeGen will need it. 11310 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11311 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11312 ResolveExceptionSpec(Loc, FPT); 11313 11314 // Implicit instantiation of function templates and member functions of 11315 // class templates. 11316 if (Func->isImplicitlyInstantiable()) { 11317 bool AlreadyInstantiated = false; 11318 SourceLocation PointOfInstantiation = Loc; 11319 if (FunctionTemplateSpecializationInfo *SpecInfo 11320 = Func->getTemplateSpecializationInfo()) { 11321 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11322 SpecInfo->setPointOfInstantiation(Loc); 11323 else if (SpecInfo->getTemplateSpecializationKind() 11324 == TSK_ImplicitInstantiation) { 11325 AlreadyInstantiated = true; 11326 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11327 } 11328 } else if (MemberSpecializationInfo *MSInfo 11329 = Func->getMemberSpecializationInfo()) { 11330 if (MSInfo->getPointOfInstantiation().isInvalid()) 11331 MSInfo->setPointOfInstantiation(Loc); 11332 else if (MSInfo->getTemplateSpecializationKind() 11333 == TSK_ImplicitInstantiation) { 11334 AlreadyInstantiated = true; 11335 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11336 } 11337 } 11338 11339 if (!AlreadyInstantiated || Func->isConstexpr()) { 11340 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11341 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11342 ActiveTemplateInstantiations.size()) 11343 PendingLocalImplicitInstantiations.push_back( 11344 std::make_pair(Func, PointOfInstantiation)); 11345 else if (Func->isConstexpr()) 11346 // Do not defer instantiations of constexpr functions, to avoid the 11347 // expression evaluator needing to call back into Sema if it sees a 11348 // call to such a function. 11349 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11350 else { 11351 PendingInstantiations.push_back(std::make_pair(Func, 11352 PointOfInstantiation)); 11353 // Notify the consumer that a function was implicitly instantiated. 11354 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11355 } 11356 } 11357 } else { 11358 // Walk redefinitions, as some of them may be instantiable. 11359 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 11360 e(Func->redecls_end()); i != e; ++i) { 11361 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11362 MarkFunctionReferenced(Loc, *i); 11363 } 11364 } 11365 11366 // Keep track of used but undefined functions. 11367 if (!Func->isDefined()) { 11368 if (mightHaveNonExternalLinkage(Func)) 11369 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11370 else if (Func->getMostRecentDecl()->isInlined() && 11371 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11372 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11373 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11374 } 11375 11376 // Normally the most current decl is marked used while processing the use and 11377 // any subsequent decls are marked used by decl merging. This fails with 11378 // template instantiation since marking can happen at the end of the file 11379 // and, because of the two phase lookup, this function is called with at 11380 // decl in the middle of a decl chain. We loop to maintain the invariant 11381 // that once a decl is used, all decls after it are also used. 11382 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11383 F->markUsed(Context); 11384 if (F == Func) 11385 break; 11386 } 11387 } 11388 11389 static void 11390 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11391 VarDecl *var, DeclContext *DC) { 11392 DeclContext *VarDC = var->getDeclContext(); 11393 11394 // If the parameter still belongs to the translation unit, then 11395 // we're actually just using one parameter in the declaration of 11396 // the next. 11397 if (isa<ParmVarDecl>(var) && 11398 isa<TranslationUnitDecl>(VarDC)) 11399 return; 11400 11401 // For C code, don't diagnose about capture if we're not actually in code 11402 // right now; it's impossible to write a non-constant expression outside of 11403 // function context, so we'll get other (more useful) diagnostics later. 11404 // 11405 // For C++, things get a bit more nasty... it would be nice to suppress this 11406 // diagnostic for certain cases like using a local variable in an array bound 11407 // for a member of a local class, but the correct predicate is not obvious. 11408 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11409 return; 11410 11411 if (isa<CXXMethodDecl>(VarDC) && 11412 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11413 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11414 << var->getIdentifier(); 11415 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11416 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11417 << var->getIdentifier() << fn->getDeclName(); 11418 } else if (isa<BlockDecl>(VarDC)) { 11419 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11420 << var->getIdentifier(); 11421 } else { 11422 // FIXME: Is there any other context where a local variable can be 11423 // declared? 11424 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11425 << var->getIdentifier(); 11426 } 11427 11428 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 11429 << var->getIdentifier(); 11430 11431 // FIXME: Add additional diagnostic info about class etc. which prevents 11432 // capture. 11433 } 11434 11435 11436 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11437 bool &SubCapturesAreNested, 11438 QualType &CaptureType, 11439 QualType &DeclRefType) { 11440 // Check whether we've already captured it. 11441 if (CSI->CaptureMap.count(Var)) { 11442 // If we found a capture, any subcaptures are nested. 11443 SubCapturesAreNested = true; 11444 11445 // Retrieve the capture type for this variable. 11446 CaptureType = CSI->getCapture(Var).getCaptureType(); 11447 11448 // Compute the type of an expression that refers to this variable. 11449 DeclRefType = CaptureType.getNonReferenceType(); 11450 11451 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11452 if (Cap.isCopyCapture() && 11453 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11454 DeclRefType.addConst(); 11455 return true; 11456 } 11457 return false; 11458 } 11459 11460 // Only block literals, captured statements, and lambda expressions can 11461 // capture; other scopes don't work. 11462 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11463 SourceLocation Loc, 11464 const bool Diagnose, Sema &S) { 11465 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 11466 return getLambdaAwareParentOfDeclContext(DC); 11467 else { 11468 if (Diagnose) 11469 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11470 } 11471 return 0; 11472 } 11473 11474 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11475 // certain types of variables (unnamed, variably modified types etc.) 11476 // so check for eligibility. 11477 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11478 SourceLocation Loc, 11479 const bool Diagnose, Sema &S) { 11480 11481 bool IsBlock = isa<BlockScopeInfo>(CSI); 11482 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11483 11484 // Lambdas are not allowed to capture unnamed variables 11485 // (e.g. anonymous unions). 11486 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11487 // assuming that's the intent. 11488 if (IsLambda && !Var->getDeclName()) { 11489 if (Diagnose) { 11490 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11491 S.Diag(Var->getLocation(), diag::note_declared_at); 11492 } 11493 return false; 11494 } 11495 11496 // Prohibit variably-modified types; they're difficult to deal with. 11497 if (Var->getType()->isVariablyModifiedType()) { 11498 if (Diagnose) { 11499 if (IsBlock) 11500 S.Diag(Loc, diag::err_ref_vm_type); 11501 else 11502 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11503 S.Diag(Var->getLocation(), diag::note_previous_decl) 11504 << Var->getDeclName(); 11505 } 11506 return false; 11507 } 11508 // Prohibit structs with flexible array members too. 11509 // We cannot capture what is in the tail end of the struct. 11510 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11511 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11512 if (Diagnose) { 11513 if (IsBlock) 11514 S.Diag(Loc, diag::err_ref_flexarray_type); 11515 else 11516 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11517 << Var->getDeclName(); 11518 S.Diag(Var->getLocation(), diag::note_previous_decl) 11519 << Var->getDeclName(); 11520 } 11521 return false; 11522 } 11523 } 11524 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11525 // Lambdas and captured statements are not allowed to capture __block 11526 // variables; they don't support the expected semantics. 11527 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11528 if (Diagnose) { 11529 S.Diag(Loc, diag::err_capture_block_variable) 11530 << Var->getDeclName() << !IsLambda; 11531 S.Diag(Var->getLocation(), diag::note_previous_decl) 11532 << Var->getDeclName(); 11533 } 11534 return false; 11535 } 11536 11537 return true; 11538 } 11539 11540 // Returns true if the capture by block was successful. 11541 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11542 SourceLocation Loc, 11543 const bool BuildAndDiagnose, 11544 QualType &CaptureType, 11545 QualType &DeclRefType, 11546 const bool Nested, 11547 Sema &S) { 11548 Expr *CopyExpr = 0; 11549 bool ByRef = false; 11550 11551 // Blocks are not allowed to capture arrays. 11552 if (CaptureType->isArrayType()) { 11553 if (BuildAndDiagnose) { 11554 S.Diag(Loc, diag::err_ref_array_type); 11555 S.Diag(Var->getLocation(), diag::note_previous_decl) 11556 << Var->getDeclName(); 11557 } 11558 return false; 11559 } 11560 11561 // Forbid the block-capture of autoreleasing variables. 11562 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11563 if (BuildAndDiagnose) { 11564 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11565 << /*block*/ 0; 11566 S.Diag(Var->getLocation(), diag::note_previous_decl) 11567 << Var->getDeclName(); 11568 } 11569 return false; 11570 } 11571 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11572 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11573 // Block capture by reference does not change the capture or 11574 // declaration reference types. 11575 ByRef = true; 11576 } else { 11577 // Block capture by copy introduces 'const'. 11578 CaptureType = CaptureType.getNonReferenceType().withConst(); 11579 DeclRefType = CaptureType; 11580 11581 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11582 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11583 // The capture logic needs the destructor, so make sure we mark it. 11584 // Usually this is unnecessary because most local variables have 11585 // their destructors marked at declaration time, but parameters are 11586 // an exception because it's technically only the call site that 11587 // actually requires the destructor. 11588 if (isa<ParmVarDecl>(Var)) 11589 S.FinalizeVarWithDestructor(Var, Record); 11590 11591 // Enter a new evaluation context to insulate the copy 11592 // full-expression. 11593 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11594 11595 // According to the blocks spec, the capture of a variable from 11596 // the stack requires a const copy constructor. This is not true 11597 // of the copy/move done to move a __block variable to the heap. 11598 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11599 DeclRefType.withConst(), 11600 VK_LValue, Loc); 11601 11602 ExprResult Result 11603 = S.PerformCopyInitialization( 11604 InitializedEntity::InitializeBlock(Var->getLocation(), 11605 CaptureType, false), 11606 Loc, S.Owned(DeclRef)); 11607 11608 // Build a full-expression copy expression if initialization 11609 // succeeded and used a non-trivial constructor. Recover from 11610 // errors by pretending that the copy isn't necessary. 11611 if (!Result.isInvalid() && 11612 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11613 ->isTrivial()) { 11614 Result = S.MaybeCreateExprWithCleanups(Result); 11615 CopyExpr = Result.take(); 11616 } 11617 } 11618 } 11619 } 11620 11621 // Actually capture the variable. 11622 if (BuildAndDiagnose) 11623 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11624 SourceLocation(), CaptureType, CopyExpr); 11625 11626 return true; 11627 11628 } 11629 11630 11631 /// \brief Capture the given variable in the captured region. 11632 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11633 VarDecl *Var, 11634 SourceLocation Loc, 11635 const bool BuildAndDiagnose, 11636 QualType &CaptureType, 11637 QualType &DeclRefType, 11638 const bool RefersToEnclosingLocal, 11639 Sema &S) { 11640 11641 // By default, capture variables by reference. 11642 bool ByRef = true; 11643 // Using an LValue reference type is consistent with Lambdas (see below). 11644 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11645 Expr *CopyExpr = 0; 11646 if (BuildAndDiagnose) { 11647 // The current implementation assumes that all variables are captured 11648 // by references. Since there is no capture by copy, no expression evaluation 11649 // will be needed. 11650 // 11651 RecordDecl *RD = RSI->TheRecordDecl; 11652 11653 FieldDecl *Field 11654 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType, 11655 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11656 0, false, ICIS_NoInit); 11657 Field->setImplicit(true); 11658 Field->setAccess(AS_private); 11659 RD->addDecl(Field); 11660 11661 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11662 DeclRefType, VK_LValue, Loc); 11663 Var->setReferenced(true); 11664 Var->markUsed(S.Context); 11665 } 11666 11667 // Actually capture the variable. 11668 if (BuildAndDiagnose) 11669 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11670 SourceLocation(), CaptureType, CopyExpr); 11671 11672 11673 return true; 11674 } 11675 11676 /// \brief Create a field within the lambda class for the variable 11677 /// being captured. Handle Array captures. 11678 static ExprResult addAsFieldToClosureType(Sema &S, 11679 LambdaScopeInfo *LSI, 11680 VarDecl *Var, QualType FieldType, 11681 QualType DeclRefType, 11682 SourceLocation Loc, 11683 bool RefersToEnclosingLocal) { 11684 CXXRecordDecl *Lambda = LSI->Lambda; 11685 11686 // Build the non-static data member. 11687 FieldDecl *Field 11688 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11689 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11690 0, false, ICIS_NoInit); 11691 Field->setImplicit(true); 11692 Field->setAccess(AS_private); 11693 Lambda->addDecl(Field); 11694 11695 // C++11 [expr.prim.lambda]p21: 11696 // When the lambda-expression is evaluated, the entities that 11697 // are captured by copy are used to direct-initialize each 11698 // corresponding non-static data member of the resulting closure 11699 // object. (For array members, the array elements are 11700 // direct-initialized in increasing subscript order.) These 11701 // initializations are performed in the (unspecified) order in 11702 // which the non-static data members are declared. 11703 11704 // Introduce a new evaluation context for the initialization, so 11705 // that temporaries introduced as part of the capture are retained 11706 // to be re-"exported" from the lambda expression itself. 11707 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11708 11709 // C++ [expr.prim.labda]p12: 11710 // An entity captured by a lambda-expression is odr-used (3.2) in 11711 // the scope containing the lambda-expression. 11712 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11713 DeclRefType, VK_LValue, Loc); 11714 Var->setReferenced(true); 11715 Var->markUsed(S.Context); 11716 11717 // When the field has array type, create index variables for each 11718 // dimension of the array. We use these index variables to subscript 11719 // the source array, and other clients (e.g., CodeGen) will perform 11720 // the necessary iteration with these index variables. 11721 SmallVector<VarDecl *, 4> IndexVariables; 11722 QualType BaseType = FieldType; 11723 QualType SizeType = S.Context.getSizeType(); 11724 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11725 while (const ConstantArrayType *Array 11726 = S.Context.getAsConstantArrayType(BaseType)) { 11727 // Create the iteration variable for this array index. 11728 IdentifierInfo *IterationVarName = 0; 11729 { 11730 SmallString<8> Str; 11731 llvm::raw_svector_ostream OS(Str); 11732 OS << "__i" << IndexVariables.size(); 11733 IterationVarName = &S.Context.Idents.get(OS.str()); 11734 } 11735 VarDecl *IterationVar 11736 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11737 IterationVarName, SizeType, 11738 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11739 SC_None); 11740 IndexVariables.push_back(IterationVar); 11741 LSI->ArrayIndexVars.push_back(IterationVar); 11742 11743 // Create a reference to the iteration variable. 11744 ExprResult IterationVarRef 11745 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11746 assert(!IterationVarRef.isInvalid() && 11747 "Reference to invented variable cannot fail!"); 11748 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11749 assert(!IterationVarRef.isInvalid() && 11750 "Conversion of invented variable cannot fail!"); 11751 11752 // Subscript the array with this iteration variable. 11753 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11754 Ref, Loc, IterationVarRef.take(), Loc); 11755 if (Subscript.isInvalid()) { 11756 S.CleanupVarDeclMarking(); 11757 S.DiscardCleanupsInEvaluationContext(); 11758 return ExprError(); 11759 } 11760 11761 Ref = Subscript.take(); 11762 BaseType = Array->getElementType(); 11763 } 11764 11765 // Construct the entity that we will be initializing. For an array, this 11766 // will be first element in the array, which may require several levels 11767 // of array-subscript entities. 11768 SmallVector<InitializedEntity, 4> Entities; 11769 Entities.reserve(1 + IndexVariables.size()); 11770 Entities.push_back( 11771 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(), 11772 Field->getType(), Loc)); 11773 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11774 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11775 0, 11776 Entities.back())); 11777 11778 InitializationKind InitKind 11779 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11780 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11781 ExprResult Result(true); 11782 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11783 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11784 11785 // If this initialization requires any cleanups (e.g., due to a 11786 // default argument to a copy constructor), note that for the 11787 // lambda. 11788 if (S.ExprNeedsCleanups) 11789 LSI->ExprNeedsCleanups = true; 11790 11791 // Exit the expression evaluation context used for the capture. 11792 S.CleanupVarDeclMarking(); 11793 S.DiscardCleanupsInEvaluationContext(); 11794 return Result; 11795 } 11796 11797 11798 11799 /// \brief Capture the given variable in the lambda. 11800 static bool captureInLambda(LambdaScopeInfo *LSI, 11801 VarDecl *Var, 11802 SourceLocation Loc, 11803 const bool BuildAndDiagnose, 11804 QualType &CaptureType, 11805 QualType &DeclRefType, 11806 const bool RefersToEnclosingLocal, 11807 const Sema::TryCaptureKind Kind, 11808 SourceLocation EllipsisLoc, 11809 const bool IsTopScope, 11810 Sema &S) { 11811 11812 // Determine whether we are capturing by reference or by value. 11813 bool ByRef = false; 11814 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11815 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11816 } else { 11817 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11818 } 11819 11820 // Compute the type of the field that will capture this variable. 11821 if (ByRef) { 11822 // C++11 [expr.prim.lambda]p15: 11823 // An entity is captured by reference if it is implicitly or 11824 // explicitly captured but not captured by copy. It is 11825 // unspecified whether additional unnamed non-static data 11826 // members are declared in the closure type for entities 11827 // captured by reference. 11828 // 11829 // FIXME: It is not clear whether we want to build an lvalue reference 11830 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11831 // to do the former, while EDG does the latter. Core issue 1249 will 11832 // clarify, but for now we follow GCC because it's a more permissive and 11833 // easily defensible position. 11834 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11835 } else { 11836 // C++11 [expr.prim.lambda]p14: 11837 // For each entity captured by copy, an unnamed non-static 11838 // data member is declared in the closure type. The 11839 // declaration order of these members is unspecified. The type 11840 // of such a data member is the type of the corresponding 11841 // captured entity if the entity is not a reference to an 11842 // object, or the referenced type otherwise. [Note: If the 11843 // captured entity is a reference to a function, the 11844 // corresponding data member is also a reference to a 11845 // function. - end note ] 11846 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11847 if (!RefType->getPointeeType()->isFunctionType()) 11848 CaptureType = RefType->getPointeeType(); 11849 } 11850 11851 // Forbid the lambda copy-capture of autoreleasing variables. 11852 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11853 if (BuildAndDiagnose) { 11854 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11855 S.Diag(Var->getLocation(), diag::note_previous_decl) 11856 << Var->getDeclName(); 11857 } 11858 return false; 11859 } 11860 11861 // Make sure that by-copy captures are of a complete and non-abstract type. 11862 if (BuildAndDiagnose) { 11863 if (!CaptureType->isDependentType() && 11864 S.RequireCompleteType(Loc, CaptureType, 11865 diag::err_capture_of_incomplete_type, 11866 Var->getDeclName())) 11867 return false; 11868 11869 if (S.RequireNonAbstractType(Loc, CaptureType, 11870 diag::err_capture_of_abstract_type)) 11871 return false; 11872 } 11873 } 11874 11875 // Capture this variable in the lambda. 11876 Expr *CopyExpr = 0; 11877 if (BuildAndDiagnose) { 11878 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 11879 CaptureType, DeclRefType, Loc, 11880 RefersToEnclosingLocal); 11881 if (!Result.isInvalid()) 11882 CopyExpr = Result.take(); 11883 } 11884 11885 // Compute the type of a reference to this captured variable. 11886 if (ByRef) 11887 DeclRefType = CaptureType.getNonReferenceType(); 11888 else { 11889 // C++ [expr.prim.lambda]p5: 11890 // The closure type for a lambda-expression has a public inline 11891 // function call operator [...]. This function call operator is 11892 // declared const (9.3.1) if and only if the lambda-expression’s 11893 // parameter-declaration-clause is not followed by mutable. 11894 DeclRefType = CaptureType.getNonReferenceType(); 11895 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11896 DeclRefType.addConst(); 11897 } 11898 11899 // Add the capture. 11900 if (BuildAndDiagnose) 11901 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 11902 Loc, EllipsisLoc, CaptureType, CopyExpr); 11903 11904 return true; 11905 } 11906 11907 11908 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 11909 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11910 bool BuildAndDiagnose, 11911 QualType &CaptureType, 11912 QualType &DeclRefType, 11913 const unsigned *const FunctionScopeIndexToStopAt) { 11914 bool Nested = false; 11915 11916 DeclContext *DC = CurContext; 11917 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 11918 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 11919 // We need to sync up the Declaration Context with the 11920 // FunctionScopeIndexToStopAt 11921 if (FunctionScopeIndexToStopAt) { 11922 unsigned FSIndex = FunctionScopes.size() - 1; 11923 while (FSIndex != MaxFunctionScopesIndex) { 11924 DC = getLambdaAwareParentOfDeclContext(DC); 11925 --FSIndex; 11926 } 11927 } 11928 11929 11930 // If the variable is declared in the current context (and is not an 11931 // init-capture), there is no need to capture it. 11932 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 11933 if (!Var->hasLocalStorage()) return true; 11934 11935 // Walk up the stack to determine whether we can capture the variable, 11936 // performing the "simple" checks that don't depend on type. We stop when 11937 // we've either hit the declared scope of the variable or find an existing 11938 // capture of that variable. We start from the innermost capturing-entity 11939 // (the DC) and ensure that all intervening capturing-entities 11940 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 11941 // declcontext can either capture the variable or have already captured 11942 // the variable. 11943 CaptureType = Var->getType(); 11944 DeclRefType = CaptureType.getNonReferenceType(); 11945 bool Explicit = (Kind != TryCapture_Implicit); 11946 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 11947 do { 11948 // Only block literals, captured statements, and lambda expressions can 11949 // capture; other scopes don't work. 11950 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 11951 ExprLoc, 11952 BuildAndDiagnose, 11953 *this); 11954 if (!ParentDC) return true; 11955 11956 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 11957 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 11958 11959 11960 // Check whether we've already captured it. 11961 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 11962 DeclRefType)) 11963 break; 11964 // If we are instantiating a generic lambda call operator body, 11965 // we do not want to capture new variables. What was captured 11966 // during either a lambdas transformation or initial parsing 11967 // should be used. 11968 if (isGenericLambdaCallOperatorSpecialization(DC)) { 11969 if (BuildAndDiagnose) { 11970 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11971 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 11972 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 11973 Diag(Var->getLocation(), diag::note_previous_decl) 11974 << Var->getDeclName(); 11975 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 11976 } else 11977 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 11978 } 11979 return true; 11980 } 11981 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11982 // certain types of variables (unnamed, variably modified types etc.) 11983 // so check for eligibility. 11984 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 11985 return true; 11986 11987 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 11988 // No capture-default, and this is not an explicit capture 11989 // so cannot capture this variable. 11990 if (BuildAndDiagnose) { 11991 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 11992 Diag(Var->getLocation(), diag::note_previous_decl) 11993 << Var->getDeclName(); 11994 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 11995 diag::note_lambda_decl); 11996 // FIXME: If we error out because an outer lambda can not implicitly 11997 // capture a variable that an inner lambda explicitly captures, we 11998 // should have the inner lambda do the explicit capture - because 11999 // it makes for cleaner diagnostics later. This would purely be done 12000 // so that the diagnostic does not misleadingly claim that a variable 12001 // can not be captured by a lambda implicitly even though it is captured 12002 // explicitly. Suggestion: 12003 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 12004 // at the function head 12005 // - cache the StartingDeclContext - this must be a lambda 12006 // - captureInLambda in the innermost lambda the variable. 12007 } 12008 return true; 12009 } 12010 12011 FunctionScopesIndex--; 12012 DC = ParentDC; 12013 Explicit = false; 12014 } while (!Var->getDeclContext()->Equals(DC)); 12015 12016 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 12017 // computing the type of the capture at each step, checking type-specific 12018 // requirements, and adding captures if requested. 12019 // If the variable had already been captured previously, we start capturing 12020 // at the lambda nested within that one. 12021 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 12022 ++I) { 12023 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 12024 12025 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 12026 if (!captureInBlock(BSI, Var, ExprLoc, 12027 BuildAndDiagnose, CaptureType, 12028 DeclRefType, Nested, *this)) 12029 return true; 12030 Nested = true; 12031 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 12032 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 12033 BuildAndDiagnose, CaptureType, 12034 DeclRefType, Nested, *this)) 12035 return true; 12036 Nested = true; 12037 } else { 12038 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12039 if (!captureInLambda(LSI, Var, ExprLoc, 12040 BuildAndDiagnose, CaptureType, 12041 DeclRefType, Nested, Kind, EllipsisLoc, 12042 /*IsTopScope*/I == N - 1, *this)) 12043 return true; 12044 Nested = true; 12045 } 12046 } 12047 return false; 12048 } 12049 12050 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 12051 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 12052 QualType CaptureType; 12053 QualType DeclRefType; 12054 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 12055 /*BuildAndDiagnose=*/true, CaptureType, 12056 DeclRefType, 0); 12057 } 12058 12059 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 12060 QualType CaptureType; 12061 QualType DeclRefType; 12062 12063 // Determine whether we can capture this variable. 12064 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 12065 /*BuildAndDiagnose=*/false, CaptureType, 12066 DeclRefType, 0)) 12067 return QualType(); 12068 12069 return DeclRefType; 12070 } 12071 12072 12073 12074 // If either the type of the variable or the initializer is dependent, 12075 // return false. Otherwise, determine whether the variable is a constant 12076 // expression. Use this if you need to know if a variable that might or 12077 // might not be dependent is truly a constant expression. 12078 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 12079 ASTContext &Context) { 12080 12081 if (Var->getType()->isDependentType()) 12082 return false; 12083 const VarDecl *DefVD = 0; 12084 Var->getAnyInitializer(DefVD); 12085 if (!DefVD) 12086 return false; 12087 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 12088 Expr *Init = cast<Expr>(Eval->Value); 12089 if (Init->isValueDependent()) 12090 return false; 12091 return IsVariableAConstantExpression(Var, Context); 12092 } 12093 12094 12095 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 12096 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 12097 // an object that satisfies the requirements for appearing in a 12098 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 12099 // is immediately applied." This function handles the lvalue-to-rvalue 12100 // conversion part. 12101 MaybeODRUseExprs.erase(E->IgnoreParens()); 12102 12103 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 12104 // to a variable that is a constant expression, and if so, identify it as 12105 // a reference to a variable that does not involve an odr-use of that 12106 // variable. 12107 if (LambdaScopeInfo *LSI = getCurLambda()) { 12108 Expr *SansParensExpr = E->IgnoreParens(); 12109 VarDecl *Var = 0; 12110 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 12111 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 12112 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 12113 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 12114 12115 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 12116 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 12117 } 12118 } 12119 12120 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 12121 if (!Res.isUsable()) 12122 return Res; 12123 12124 // If a constant-expression is a reference to a variable where we delay 12125 // deciding whether it is an odr-use, just assume we will apply the 12126 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 12127 // (a non-type template argument), we have special handling anyway. 12128 UpdateMarkingForLValueToRValue(Res.get()); 12129 return Res; 12130 } 12131 12132 void Sema::CleanupVarDeclMarking() { 12133 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 12134 e = MaybeODRUseExprs.end(); 12135 i != e; ++i) { 12136 VarDecl *Var; 12137 SourceLocation Loc; 12138 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 12139 Var = cast<VarDecl>(DRE->getDecl()); 12140 Loc = DRE->getLocation(); 12141 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 12142 Var = cast<VarDecl>(ME->getMemberDecl()); 12143 Loc = ME->getMemberLoc(); 12144 } else { 12145 llvm_unreachable("Unexpcted expression"); 12146 } 12147 12148 MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0); 12149 } 12150 12151 MaybeODRUseExprs.clear(); 12152 } 12153 12154 12155 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 12156 VarDecl *Var, Expr *E) { 12157 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 12158 "Invalid Expr argument to DoMarkVarDeclReferenced"); 12159 Var->setReferenced(); 12160 12161 // If the context is not potentially evaluated, this is not an odr-use and 12162 // does not trigger instantiation. 12163 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 12164 if (SemaRef.isUnevaluatedContext()) 12165 return; 12166 12167 // If we don't yet know whether this context is going to end up being an 12168 // evaluated context, and we're referencing a variable from an enclosing 12169 // scope, add a potential capture. 12170 // 12171 // FIXME: Is this necessary? These contexts are only used for default 12172 // arguments, where local variables can't be used. 12173 const bool RefersToEnclosingScope = 12174 (SemaRef.CurContext != Var->getDeclContext() && 12175 Var->getDeclContext()->isFunctionOrMethod() && 12176 Var->hasLocalStorage()); 12177 if (!RefersToEnclosingScope) 12178 return; 12179 12180 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 12181 // If a variable could potentially be odr-used, defer marking it so 12182 // until we finish analyzing the full expression for any lvalue-to-rvalue 12183 // or discarded value conversions that would obviate odr-use. 12184 // Add it to the list of potential captures that will be analyzed 12185 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 12186 // unless the variable is a reference that was initialized by a constant 12187 // expression (this will never need to be captured or odr-used). 12188 assert(E && "Capture variable should be used in an expression."); 12189 if (!Var->getType()->isReferenceType() || 12190 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 12191 LSI->addPotentialCapture(E->IgnoreParens()); 12192 } 12193 return; 12194 } 12195 12196 VarTemplateSpecializationDecl *VarSpec = 12197 dyn_cast<VarTemplateSpecializationDecl>(Var); 12198 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 12199 "Can't instantiate a partial template specialization."); 12200 12201 // Perform implicit instantiation of static data members, static data member 12202 // templates of class templates, and variable template specializations. Delay 12203 // instantiations of variable templates, except for those that could be used 12204 // in a constant expression. 12205 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 12206 if (isTemplateInstantiation(TSK)) { 12207 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 12208 12209 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 12210 if (Var->getPointOfInstantiation().isInvalid()) { 12211 // This is a modification of an existing AST node. Notify listeners. 12212 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 12213 L->StaticDataMemberInstantiated(Var); 12214 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 12215 // Don't bother trying to instantiate it again, unless we might need 12216 // its initializer before we get to the end of the TU. 12217 TryInstantiating = false; 12218 } 12219 12220 if (Var->getPointOfInstantiation().isInvalid()) 12221 Var->setTemplateSpecializationKind(TSK, Loc); 12222 12223 if (TryInstantiating) { 12224 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 12225 bool InstantiationDependent = false; 12226 bool IsNonDependent = 12227 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 12228 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 12229 : true; 12230 12231 // Do not instantiate specializations that are still type-dependent. 12232 if (IsNonDependent) { 12233 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 12234 // Do not defer instantiations of variables which could be used in a 12235 // constant expression. 12236 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 12237 } else { 12238 SemaRef.PendingInstantiations 12239 .push_back(std::make_pair(Var, PointOfInstantiation)); 12240 } 12241 } 12242 } 12243 } 12244 12245 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 12246 // the requirements for appearing in a constant expression (5.19) and, if 12247 // it is an object, the lvalue-to-rvalue conversion (4.1) 12248 // is immediately applied." We check the first part here, and 12249 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 12250 // Note that we use the C++11 definition everywhere because nothing in 12251 // C++03 depends on whether we get the C++03 version correct. The second 12252 // part does not apply to references, since they are not objects. 12253 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 12254 // A reference initialized by a constant expression can never be 12255 // odr-used, so simply ignore it. 12256 if (!Var->getType()->isReferenceType()) 12257 SemaRef.MaybeODRUseExprs.insert(E); 12258 } else 12259 MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0); 12260 } 12261 12262 /// \brief Mark a variable referenced, and check whether it is odr-used 12263 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 12264 /// used directly for normal expressions referring to VarDecl. 12265 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 12266 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 12267 } 12268 12269 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 12270 Decl *D, Expr *E, bool OdrUse) { 12271 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 12272 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 12273 return; 12274 } 12275 12276 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 12277 12278 // If this is a call to a method via a cast, also mark the method in the 12279 // derived class used in case codegen can devirtualize the call. 12280 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12281 if (!ME) 12282 return; 12283 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12284 if (!MD) 12285 return; 12286 const Expr *Base = ME->getBase(); 12287 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12288 if (!MostDerivedClassDecl) 12289 return; 12290 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12291 if (!DM || DM->isPure()) 12292 return; 12293 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12294 } 12295 12296 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12297 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12298 // TODO: update this with DR# once a defect report is filed. 12299 // C++11 defect. The address of a pure member should not be an ODR use, even 12300 // if it's a qualified reference. 12301 bool OdrUse = true; 12302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12303 if (Method->isVirtual()) 12304 OdrUse = false; 12305 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12306 } 12307 12308 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12309 void Sema::MarkMemberReferenced(MemberExpr *E) { 12310 // C++11 [basic.def.odr]p2: 12311 // A non-overloaded function whose name appears as a potentially-evaluated 12312 // expression or a member of a set of candidate functions, if selected by 12313 // overload resolution when referred to from a potentially-evaluated 12314 // expression, is odr-used, unless it is a pure virtual function and its 12315 // name is not explicitly qualified. 12316 bool OdrUse = true; 12317 if (!E->hasQualifier()) { 12318 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12319 if (Method->isPure()) 12320 OdrUse = false; 12321 } 12322 SourceLocation Loc = E->getMemberLoc().isValid() ? 12323 E->getMemberLoc() : E->getLocStart(); 12324 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12325 } 12326 12327 /// \brief Perform marking for a reference to an arbitrary declaration. It 12328 /// marks the declaration referenced, and performs odr-use checking for functions 12329 /// and variables. This method should not be used when building an normal 12330 /// expression which refers to a variable. 12331 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12332 if (OdrUse) { 12333 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12334 MarkVariableReferenced(Loc, VD); 12335 return; 12336 } 12337 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12338 MarkFunctionReferenced(Loc, FD); 12339 return; 12340 } 12341 } 12342 D->setReferenced(); 12343 } 12344 12345 namespace { 12346 // Mark all of the declarations referenced 12347 // FIXME: Not fully implemented yet! We need to have a better understanding 12348 // of when we're entering 12349 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12350 Sema &S; 12351 SourceLocation Loc; 12352 12353 public: 12354 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12355 12356 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12357 12358 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12359 bool TraverseRecordType(RecordType *T); 12360 }; 12361 } 12362 12363 bool MarkReferencedDecls::TraverseTemplateArgument( 12364 const TemplateArgument &Arg) { 12365 if (Arg.getKind() == TemplateArgument::Declaration) { 12366 if (Decl *D = Arg.getAsDecl()) 12367 S.MarkAnyDeclReferenced(Loc, D, true); 12368 } 12369 12370 return Inherited::TraverseTemplateArgument(Arg); 12371 } 12372 12373 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12374 if (ClassTemplateSpecializationDecl *Spec 12375 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12376 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12377 return TraverseTemplateArguments(Args.data(), Args.size()); 12378 } 12379 12380 return true; 12381 } 12382 12383 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12384 MarkReferencedDecls Marker(*this, Loc); 12385 Marker.TraverseType(Context.getCanonicalType(T)); 12386 } 12387 12388 namespace { 12389 /// \brief Helper class that marks all of the declarations referenced by 12390 /// potentially-evaluated subexpressions as "referenced". 12391 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12392 Sema &S; 12393 bool SkipLocalVariables; 12394 12395 public: 12396 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12397 12398 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12399 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12400 12401 void VisitDeclRefExpr(DeclRefExpr *E) { 12402 // If we were asked not to visit local variables, don't. 12403 if (SkipLocalVariables) { 12404 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12405 if (VD->hasLocalStorage()) 12406 return; 12407 } 12408 12409 S.MarkDeclRefReferenced(E); 12410 } 12411 12412 void VisitMemberExpr(MemberExpr *E) { 12413 S.MarkMemberReferenced(E); 12414 Inherited::VisitMemberExpr(E); 12415 } 12416 12417 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12418 S.MarkFunctionReferenced(E->getLocStart(), 12419 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12420 Visit(E->getSubExpr()); 12421 } 12422 12423 void VisitCXXNewExpr(CXXNewExpr *E) { 12424 if (E->getOperatorNew()) 12425 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12426 if (E->getOperatorDelete()) 12427 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12428 Inherited::VisitCXXNewExpr(E); 12429 } 12430 12431 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12432 if (E->getOperatorDelete()) 12433 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12434 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12435 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12436 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12437 S.MarkFunctionReferenced(E->getLocStart(), 12438 S.LookupDestructor(Record)); 12439 } 12440 12441 Inherited::VisitCXXDeleteExpr(E); 12442 } 12443 12444 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12445 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12446 Inherited::VisitCXXConstructExpr(E); 12447 } 12448 12449 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12450 Visit(E->getExpr()); 12451 } 12452 12453 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12454 Inherited::VisitImplicitCastExpr(E); 12455 12456 if (E->getCastKind() == CK_LValueToRValue) 12457 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12458 } 12459 }; 12460 } 12461 12462 /// \brief Mark any declarations that appear within this expression or any 12463 /// potentially-evaluated subexpressions as "referenced". 12464 /// 12465 /// \param SkipLocalVariables If true, don't mark local variables as 12466 /// 'referenced'. 12467 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12468 bool SkipLocalVariables) { 12469 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12470 } 12471 12472 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 12473 /// of the program being compiled. 12474 /// 12475 /// This routine emits the given diagnostic when the code currently being 12476 /// type-checked is "potentially evaluated", meaning that there is a 12477 /// possibility that the code will actually be executable. Code in sizeof() 12478 /// expressions, code used only during overload resolution, etc., are not 12479 /// potentially evaluated. This routine will suppress such diagnostics or, 12480 /// in the absolutely nutty case of potentially potentially evaluated 12481 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 12482 /// later. 12483 /// 12484 /// This routine should be used for all diagnostics that describe the run-time 12485 /// behavior of a program, such as passing a non-POD value through an ellipsis. 12486 /// Failure to do so will likely result in spurious diagnostics or failures 12487 /// during overload resolution or within sizeof/alignof/typeof/typeid. 12488 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12489 const PartialDiagnostic &PD) { 12490 switch (ExprEvalContexts.back().Context) { 12491 case Unevaluated: 12492 case UnevaluatedAbstract: 12493 // The argument will never be evaluated, so don't complain. 12494 break; 12495 12496 case ConstantEvaluated: 12497 // Relevant diagnostics should be produced by constant evaluation. 12498 break; 12499 12500 case PotentiallyEvaluated: 12501 case PotentiallyEvaluatedIfUsed: 12502 if (Statement && getCurFunctionOrMethodDecl()) { 12503 FunctionScopes.back()->PossiblyUnreachableDiags. 12504 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12505 } 12506 else 12507 Diag(Loc, PD); 12508 12509 return true; 12510 } 12511 12512 return false; 12513 } 12514 12515 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12516 CallExpr *CE, FunctionDecl *FD) { 12517 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12518 return false; 12519 12520 // If we're inside a decltype's expression, don't check for a valid return 12521 // type or construct temporaries until we know whether this is the last call. 12522 if (ExprEvalContexts.back().IsDecltype) { 12523 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12524 return false; 12525 } 12526 12527 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12528 FunctionDecl *FD; 12529 CallExpr *CE; 12530 12531 public: 12532 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12533 : FD(FD), CE(CE) { } 12534 12535 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 12536 if (!FD) { 12537 S.Diag(Loc, diag::err_call_incomplete_return) 12538 << T << CE->getSourceRange(); 12539 return; 12540 } 12541 12542 S.Diag(Loc, diag::err_call_function_incomplete_return) 12543 << CE->getSourceRange() << FD->getDeclName() << T; 12544 S.Diag(FD->getLocation(), 12545 diag::note_function_with_incomplete_return_type_declared_here) 12546 << FD->getDeclName(); 12547 } 12548 } Diagnoser(FD, CE); 12549 12550 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12551 return true; 12552 12553 return false; 12554 } 12555 12556 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12557 // will prevent this condition from triggering, which is what we want. 12558 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12559 SourceLocation Loc; 12560 12561 unsigned diagnostic = diag::warn_condition_is_assignment; 12562 bool IsOrAssign = false; 12563 12564 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12565 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12566 return; 12567 12568 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12569 12570 // Greylist some idioms by putting them into a warning subcategory. 12571 if (ObjCMessageExpr *ME 12572 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12573 Selector Sel = ME->getSelector(); 12574 12575 // self = [<foo> init...] 12576 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12577 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12578 12579 // <foo> = [<bar> nextObject] 12580 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12581 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12582 } 12583 12584 Loc = Op->getOperatorLoc(); 12585 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12586 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12587 return; 12588 12589 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12590 Loc = Op->getOperatorLoc(); 12591 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12592 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12593 else { 12594 // Not an assignment. 12595 return; 12596 } 12597 12598 Diag(Loc, diagnostic) << E->getSourceRange(); 12599 12600 SourceLocation Open = E->getLocStart(); 12601 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12602 Diag(Loc, diag::note_condition_assign_silence) 12603 << FixItHint::CreateInsertion(Open, "(") 12604 << FixItHint::CreateInsertion(Close, ")"); 12605 12606 if (IsOrAssign) 12607 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12608 << FixItHint::CreateReplacement(Loc, "!="); 12609 else 12610 Diag(Loc, diag::note_condition_assign_to_comparison) 12611 << FixItHint::CreateReplacement(Loc, "=="); 12612 } 12613 12614 /// \brief Redundant parentheses over an equality comparison can indicate 12615 /// that the user intended an assignment used as condition. 12616 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12617 // Don't warn if the parens came from a macro. 12618 SourceLocation parenLoc = ParenE->getLocStart(); 12619 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12620 return; 12621 // Don't warn for dependent expressions. 12622 if (ParenE->isTypeDependent()) 12623 return; 12624 12625 Expr *E = ParenE->IgnoreParens(); 12626 12627 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12628 if (opE->getOpcode() == BO_EQ && 12629 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12630 == Expr::MLV_Valid) { 12631 SourceLocation Loc = opE->getOperatorLoc(); 12632 12633 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12634 SourceRange ParenERange = ParenE->getSourceRange(); 12635 Diag(Loc, diag::note_equality_comparison_silence) 12636 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12637 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12638 Diag(Loc, diag::note_equality_comparison_to_assign) 12639 << FixItHint::CreateReplacement(Loc, "="); 12640 } 12641 } 12642 12643 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12644 DiagnoseAssignmentAsCondition(E); 12645 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12646 DiagnoseEqualityWithExtraParens(parenE); 12647 12648 ExprResult result = CheckPlaceholderExpr(E); 12649 if (result.isInvalid()) return ExprError(); 12650 E = result.take(); 12651 12652 if (!E->isTypeDependent()) { 12653 if (getLangOpts().CPlusPlus) 12654 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12655 12656 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12657 if (ERes.isInvalid()) 12658 return ExprError(); 12659 E = ERes.take(); 12660 12661 QualType T = E->getType(); 12662 if (!T->isScalarType()) { // C99 6.8.4.1p1 12663 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12664 << T << E->getSourceRange(); 12665 return ExprError(); 12666 } 12667 } 12668 12669 return Owned(E); 12670 } 12671 12672 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12673 Expr *SubExpr) { 12674 if (!SubExpr) 12675 return ExprError(); 12676 12677 return CheckBooleanCondition(SubExpr, Loc); 12678 } 12679 12680 namespace { 12681 /// A visitor for rebuilding a call to an __unknown_any expression 12682 /// to have an appropriate type. 12683 struct RebuildUnknownAnyFunction 12684 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12685 12686 Sema &S; 12687 12688 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12689 12690 ExprResult VisitStmt(Stmt *S) { 12691 llvm_unreachable("unexpected statement!"); 12692 } 12693 12694 ExprResult VisitExpr(Expr *E) { 12695 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12696 << E->getSourceRange(); 12697 return ExprError(); 12698 } 12699 12700 /// Rebuild an expression which simply semantically wraps another 12701 /// expression which it shares the type and value kind of. 12702 template <class T> ExprResult rebuildSugarExpr(T *E) { 12703 ExprResult SubResult = Visit(E->getSubExpr()); 12704 if (SubResult.isInvalid()) return ExprError(); 12705 12706 Expr *SubExpr = SubResult.take(); 12707 E->setSubExpr(SubExpr); 12708 E->setType(SubExpr->getType()); 12709 E->setValueKind(SubExpr->getValueKind()); 12710 assert(E->getObjectKind() == OK_Ordinary); 12711 return E; 12712 } 12713 12714 ExprResult VisitParenExpr(ParenExpr *E) { 12715 return rebuildSugarExpr(E); 12716 } 12717 12718 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12719 return rebuildSugarExpr(E); 12720 } 12721 12722 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12723 ExprResult SubResult = Visit(E->getSubExpr()); 12724 if (SubResult.isInvalid()) return ExprError(); 12725 12726 Expr *SubExpr = SubResult.take(); 12727 E->setSubExpr(SubExpr); 12728 E->setType(S.Context.getPointerType(SubExpr->getType())); 12729 assert(E->getValueKind() == VK_RValue); 12730 assert(E->getObjectKind() == OK_Ordinary); 12731 return E; 12732 } 12733 12734 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12735 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12736 12737 E->setType(VD->getType()); 12738 12739 assert(E->getValueKind() == VK_RValue); 12740 if (S.getLangOpts().CPlusPlus && 12741 !(isa<CXXMethodDecl>(VD) && 12742 cast<CXXMethodDecl>(VD)->isInstance())) 12743 E->setValueKind(VK_LValue); 12744 12745 return E; 12746 } 12747 12748 ExprResult VisitMemberExpr(MemberExpr *E) { 12749 return resolveDecl(E, E->getMemberDecl()); 12750 } 12751 12752 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12753 return resolveDecl(E, E->getDecl()); 12754 } 12755 }; 12756 } 12757 12758 /// Given a function expression of unknown-any type, try to rebuild it 12759 /// to have a function type. 12760 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12761 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12762 if (Result.isInvalid()) return ExprError(); 12763 return S.DefaultFunctionArrayConversion(Result.take()); 12764 } 12765 12766 namespace { 12767 /// A visitor for rebuilding an expression of type __unknown_anytype 12768 /// into one which resolves the type directly on the referring 12769 /// expression. Strict preservation of the original source 12770 /// structure is not a goal. 12771 struct RebuildUnknownAnyExpr 12772 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12773 12774 Sema &S; 12775 12776 /// The current destination type. 12777 QualType DestType; 12778 12779 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12780 : S(S), DestType(CastType) {} 12781 12782 ExprResult VisitStmt(Stmt *S) { 12783 llvm_unreachable("unexpected statement!"); 12784 } 12785 12786 ExprResult VisitExpr(Expr *E) { 12787 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12788 << E->getSourceRange(); 12789 return ExprError(); 12790 } 12791 12792 ExprResult VisitCallExpr(CallExpr *E); 12793 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12794 12795 /// Rebuild an expression which simply semantically wraps another 12796 /// expression which it shares the type and value kind of. 12797 template <class T> ExprResult rebuildSugarExpr(T *E) { 12798 ExprResult SubResult = Visit(E->getSubExpr()); 12799 if (SubResult.isInvalid()) return ExprError(); 12800 Expr *SubExpr = SubResult.take(); 12801 E->setSubExpr(SubExpr); 12802 E->setType(SubExpr->getType()); 12803 E->setValueKind(SubExpr->getValueKind()); 12804 assert(E->getObjectKind() == OK_Ordinary); 12805 return E; 12806 } 12807 12808 ExprResult VisitParenExpr(ParenExpr *E) { 12809 return rebuildSugarExpr(E); 12810 } 12811 12812 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12813 return rebuildSugarExpr(E); 12814 } 12815 12816 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12817 const PointerType *Ptr = DestType->getAs<PointerType>(); 12818 if (!Ptr) { 12819 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12820 << E->getSourceRange(); 12821 return ExprError(); 12822 } 12823 assert(E->getValueKind() == VK_RValue); 12824 assert(E->getObjectKind() == OK_Ordinary); 12825 E->setType(DestType); 12826 12827 // Build the sub-expression as if it were an object of the pointee type. 12828 DestType = Ptr->getPointeeType(); 12829 ExprResult SubResult = Visit(E->getSubExpr()); 12830 if (SubResult.isInvalid()) return ExprError(); 12831 E->setSubExpr(SubResult.take()); 12832 return E; 12833 } 12834 12835 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12836 12837 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12838 12839 ExprResult VisitMemberExpr(MemberExpr *E) { 12840 return resolveDecl(E, E->getMemberDecl()); 12841 } 12842 12843 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12844 return resolveDecl(E, E->getDecl()); 12845 } 12846 }; 12847 } 12848 12849 /// Rebuilds a call expression which yielded __unknown_anytype. 12850 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12851 Expr *CalleeExpr = E->getCallee(); 12852 12853 enum FnKind { 12854 FK_MemberFunction, 12855 FK_FunctionPointer, 12856 FK_BlockPointer 12857 }; 12858 12859 FnKind Kind; 12860 QualType CalleeType = CalleeExpr->getType(); 12861 if (CalleeType == S.Context.BoundMemberTy) { 12862 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12863 Kind = FK_MemberFunction; 12864 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12865 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12866 CalleeType = Ptr->getPointeeType(); 12867 Kind = FK_FunctionPointer; 12868 } else { 12869 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12870 Kind = FK_BlockPointer; 12871 } 12872 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12873 12874 // Verify that this is a legal result type of a function. 12875 if (DestType->isArrayType() || DestType->isFunctionType()) { 12876 unsigned diagID = diag::err_func_returning_array_function; 12877 if (Kind == FK_BlockPointer) 12878 diagID = diag::err_block_returning_array_function; 12879 12880 S.Diag(E->getExprLoc(), diagID) 12881 << DestType->isFunctionType() << DestType; 12882 return ExprError(); 12883 } 12884 12885 // Otherwise, go ahead and set DestType as the call's result. 12886 E->setType(DestType.getNonLValueExprType(S.Context)); 12887 E->setValueKind(Expr::getValueKindForType(DestType)); 12888 assert(E->getObjectKind() == OK_Ordinary); 12889 12890 // Rebuild the function type, replacing the result type with DestType. 12891 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12892 if (Proto) { 12893 // __unknown_anytype(...) is a special case used by the debugger when 12894 // it has no idea what a function's signature is. 12895 // 12896 // We want to build this call essentially under the K&R 12897 // unprototyped rules, but making a FunctionNoProtoType in C++ 12898 // would foul up all sorts of assumptions. However, we cannot 12899 // simply pass all arguments as variadic arguments, nor can we 12900 // portably just call the function under a non-variadic type; see 12901 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12902 // However, it turns out that in practice it is generally safe to 12903 // call a function declared as "A foo(B,C,D);" under the prototype 12904 // "A foo(B,C,D,...);". The only known exception is with the 12905 // Windows ABI, where any variadic function is implicitly cdecl 12906 // regardless of its normal CC. Therefore we change the parameter 12907 // types to match the types of the arguments. 12908 // 12909 // This is a hack, but it is far superior to moving the 12910 // corresponding target-specific code from IR-gen to Sema/AST. 12911 12912 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 12913 SmallVector<QualType, 8> ArgTypes; 12914 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12915 ArgTypes.reserve(E->getNumArgs()); 12916 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12917 Expr *Arg = E->getArg(i); 12918 QualType ArgType = Arg->getType(); 12919 if (E->isLValue()) { 12920 ArgType = S.Context.getLValueReferenceType(ArgType); 12921 } else if (E->isXValue()) { 12922 ArgType = S.Context.getRValueReferenceType(ArgType); 12923 } 12924 ArgTypes.push_back(ArgType); 12925 } 12926 ParamTypes = ArgTypes; 12927 } 12928 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12929 Proto->getExtProtoInfo()); 12930 } else { 12931 DestType = S.Context.getFunctionNoProtoType(DestType, 12932 FnType->getExtInfo()); 12933 } 12934 12935 // Rebuild the appropriate pointer-to-function type. 12936 switch (Kind) { 12937 case FK_MemberFunction: 12938 // Nothing to do. 12939 break; 12940 12941 case FK_FunctionPointer: 12942 DestType = S.Context.getPointerType(DestType); 12943 break; 12944 12945 case FK_BlockPointer: 12946 DestType = S.Context.getBlockPointerType(DestType); 12947 break; 12948 } 12949 12950 // Finally, we can recurse. 12951 ExprResult CalleeResult = Visit(CalleeExpr); 12952 if (!CalleeResult.isUsable()) return ExprError(); 12953 E->setCallee(CalleeResult.take()); 12954 12955 // Bind a temporary if necessary. 12956 return S.MaybeBindToTemporary(E); 12957 } 12958 12959 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12960 // Verify that this is a legal result type of a call. 12961 if (DestType->isArrayType() || DestType->isFunctionType()) { 12962 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 12963 << DestType->isFunctionType() << DestType; 12964 return ExprError(); 12965 } 12966 12967 // Rewrite the method result type if available. 12968 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 12969 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 12970 Method->setReturnType(DestType); 12971 } 12972 12973 // Change the type of the message. 12974 E->setType(DestType.getNonReferenceType()); 12975 E->setValueKind(Expr::getValueKindForType(DestType)); 12976 12977 return S.MaybeBindToTemporary(E); 12978 } 12979 12980 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 12981 // The only case we should ever see here is a function-to-pointer decay. 12982 if (E->getCastKind() == CK_FunctionToPointerDecay) { 12983 assert(E->getValueKind() == VK_RValue); 12984 assert(E->getObjectKind() == OK_Ordinary); 12985 12986 E->setType(DestType); 12987 12988 // Rebuild the sub-expression as the pointee (function) type. 12989 DestType = DestType->castAs<PointerType>()->getPointeeType(); 12990 12991 ExprResult Result = Visit(E->getSubExpr()); 12992 if (!Result.isUsable()) return ExprError(); 12993 12994 E->setSubExpr(Result.take()); 12995 return S.Owned(E); 12996 } else if (E->getCastKind() == CK_LValueToRValue) { 12997 assert(E->getValueKind() == VK_RValue); 12998 assert(E->getObjectKind() == OK_Ordinary); 12999 13000 assert(isa<BlockPointerType>(E->getType())); 13001 13002 E->setType(DestType); 13003 13004 // The sub-expression has to be a lvalue reference, so rebuild it as such. 13005 DestType = S.Context.getLValueReferenceType(DestType); 13006 13007 ExprResult Result = Visit(E->getSubExpr()); 13008 if (!Result.isUsable()) return ExprError(); 13009 13010 E->setSubExpr(Result.take()); 13011 return S.Owned(E); 13012 } else { 13013 llvm_unreachable("Unhandled cast type!"); 13014 } 13015 } 13016 13017 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 13018 ExprValueKind ValueKind = VK_LValue; 13019 QualType Type = DestType; 13020 13021 // We know how to make this work for certain kinds of decls: 13022 13023 // - functions 13024 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 13025 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 13026 DestType = Ptr->getPointeeType(); 13027 ExprResult Result = resolveDecl(E, VD); 13028 if (Result.isInvalid()) return ExprError(); 13029 return S.ImpCastExprToType(Result.take(), Type, 13030 CK_FunctionToPointerDecay, VK_RValue); 13031 } 13032 13033 if (!Type->isFunctionType()) { 13034 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 13035 << VD << E->getSourceRange(); 13036 return ExprError(); 13037 } 13038 13039 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 13040 if (MD->isInstance()) { 13041 ValueKind = VK_RValue; 13042 Type = S.Context.BoundMemberTy; 13043 } 13044 13045 // Function references aren't l-values in C. 13046 if (!S.getLangOpts().CPlusPlus) 13047 ValueKind = VK_RValue; 13048 13049 // - variables 13050 } else if (isa<VarDecl>(VD)) { 13051 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 13052 Type = RefTy->getPointeeType(); 13053 } else if (Type->isFunctionType()) { 13054 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 13055 << VD << E->getSourceRange(); 13056 return ExprError(); 13057 } 13058 13059 // - nothing else 13060 } else { 13061 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 13062 << VD << E->getSourceRange(); 13063 return ExprError(); 13064 } 13065 13066 // Modifying the declaration like this is friendly to IR-gen but 13067 // also really dangerous. 13068 VD->setType(DestType); 13069 E->setType(Type); 13070 E->setValueKind(ValueKind); 13071 return S.Owned(E); 13072 } 13073 13074 /// Check a cast of an unknown-any type. We intentionally only 13075 /// trigger this for C-style casts. 13076 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 13077 Expr *CastExpr, CastKind &CastKind, 13078 ExprValueKind &VK, CXXCastPath &Path) { 13079 // Rewrite the casted expression from scratch. 13080 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 13081 if (!result.isUsable()) return ExprError(); 13082 13083 CastExpr = result.take(); 13084 VK = CastExpr->getValueKind(); 13085 CastKind = CK_NoOp; 13086 13087 return CastExpr; 13088 } 13089 13090 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 13091 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 13092 } 13093 13094 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 13095 Expr *arg, QualType ¶mType) { 13096 // If the syntactic form of the argument is not an explicit cast of 13097 // any sort, just do default argument promotion. 13098 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 13099 if (!castArg) { 13100 ExprResult result = DefaultArgumentPromotion(arg); 13101 if (result.isInvalid()) return ExprError(); 13102 paramType = result.get()->getType(); 13103 return result; 13104 } 13105 13106 // Otherwise, use the type that was written in the explicit cast. 13107 assert(!arg->hasPlaceholderType()); 13108 paramType = castArg->getTypeAsWritten(); 13109 13110 // Copy-initialize a parameter of that type. 13111 InitializedEntity entity = 13112 InitializedEntity::InitializeParameter(Context, paramType, 13113 /*consumed*/ false); 13114 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 13115 } 13116 13117 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 13118 Expr *orig = E; 13119 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 13120 while (true) { 13121 E = E->IgnoreParenImpCasts(); 13122 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 13123 E = call->getCallee(); 13124 diagID = diag::err_uncasted_call_of_unknown_any; 13125 } else { 13126 break; 13127 } 13128 } 13129 13130 SourceLocation loc; 13131 NamedDecl *d; 13132 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 13133 loc = ref->getLocation(); 13134 d = ref->getDecl(); 13135 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 13136 loc = mem->getMemberLoc(); 13137 d = mem->getMemberDecl(); 13138 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 13139 diagID = diag::err_uncasted_call_of_unknown_any; 13140 loc = msg->getSelectorStartLoc(); 13141 d = msg->getMethodDecl(); 13142 if (!d) { 13143 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 13144 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 13145 << orig->getSourceRange(); 13146 return ExprError(); 13147 } 13148 } else { 13149 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13150 << E->getSourceRange(); 13151 return ExprError(); 13152 } 13153 13154 S.Diag(loc, diagID) << d << orig->getSourceRange(); 13155 13156 // Never recoverable. 13157 return ExprError(); 13158 } 13159 13160 /// Check for operands with placeholder types and complain if found. 13161 /// Returns true if there was an error and no recovery was possible. 13162 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 13163 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 13164 if (!placeholderType) return Owned(E); 13165 13166 switch (placeholderType->getKind()) { 13167 13168 // Overloaded expressions. 13169 case BuiltinType::Overload: { 13170 // Try to resolve a single function template specialization. 13171 // This is obligatory. 13172 ExprResult result = Owned(E); 13173 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 13174 return result; 13175 13176 // If that failed, try to recover with a call. 13177 } else { 13178 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 13179 /*complain*/ true); 13180 return result; 13181 } 13182 } 13183 13184 // Bound member functions. 13185 case BuiltinType::BoundMember: { 13186 ExprResult result = Owned(E); 13187 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 13188 /*complain*/ true); 13189 return result; 13190 } 13191 13192 // ARC unbridged casts. 13193 case BuiltinType::ARCUnbridgedCast: { 13194 Expr *realCast = stripARCUnbridgedCast(E); 13195 diagnoseARCUnbridgedCast(realCast); 13196 return Owned(realCast); 13197 } 13198 13199 // Expressions of unknown type. 13200 case BuiltinType::UnknownAny: 13201 return diagnoseUnknownAnyExpr(*this, E); 13202 13203 // Pseudo-objects. 13204 case BuiltinType::PseudoObject: 13205 return checkPseudoObjectRValue(E); 13206 13207 case BuiltinType::BuiltinFn: 13208 Diag(E->getLocStart(), diag::err_builtin_fn_use); 13209 return ExprError(); 13210 13211 // Everything else should be impossible. 13212 #define BUILTIN_TYPE(Id, SingletonId) \ 13213 case BuiltinType::Id: 13214 #define PLACEHOLDER_TYPE(Id, SingletonId) 13215 #include "clang/AST/BuiltinTypes.def" 13216 break; 13217 } 13218 13219 llvm_unreachable("invalid placeholder type!"); 13220 } 13221 13222 bool Sema::CheckCaseExpression(Expr *E) { 13223 if (E->isTypeDependent()) 13224 return true; 13225 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 13226 return E->getType()->isIntegralOrEnumerationType(); 13227 return false; 13228 } 13229 13230 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 13231 ExprResult 13232 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 13233 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 13234 "Unknown Objective-C Boolean value!"); 13235 QualType BoolT = Context.ObjCBuiltinBoolTy; 13236 if (!Context.getBOOLDecl()) { 13237 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 13238 Sema::LookupOrdinaryName); 13239 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 13240 NamedDecl *ND = Result.getFoundDecl(); 13241 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 13242 Context.setBOOLDecl(TD); 13243 } 13244 } 13245 if (Context.getBOOLDecl()) 13246 BoolT = Context.getBOOLType(); 13247 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 13248 BoolT, OpLoc)); 13249 } 13250