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/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/AnalysisBasedWarnings.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/DelayedDiagnostic.h" 36 #include "clang/Sema/Designator.h" 37 #include "clang/Sema/Initialization.h" 38 #include "clang/Sema/Lookup.h" 39 #include "clang/Sema/ParsedTemplate.h" 40 #include "clang/Sema/Scope.h" 41 #include "clang/Sema/ScopeInfo.h" 42 #include "clang/Sema/SemaFixItUtils.h" 43 #include "clang/Sema/Template.h" 44 using namespace clang; 45 using namespace sema; 46 47 /// \brief Determine whether the use of this declaration is valid, without 48 /// emitting diagnostics. 49 bool Sema::CanUseDecl(NamedDecl *D) { 50 // See if this is an auto-typed variable whose initializer we are parsing. 51 if (ParsingInitForAutoVars.count(D)) 52 return false; 53 54 // See if this is a deleted function. 55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 56 if (FD->isDeleted()) 57 return false; 58 59 // If the function has a deduced return type, and we can't deduce it, 60 // then we can't use it either. 61 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 62 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false)) 63 return false; 64 } 65 66 // See if this function is unavailable. 67 if (D->getAvailability() == AR_Unavailable && 68 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 69 return false; 70 71 return true; 72 } 73 74 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 75 // Warn if this is used but marked unused. 76 if (D->hasAttr<UnusedAttr>()) { 77 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 78 if (!DC->hasAttr<UnusedAttr>()) 79 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 80 } 81 } 82 83 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 84 NamedDecl *D, SourceLocation Loc, 85 const ObjCInterfaceDecl *UnknownObjCClass) { 86 // See if this declaration is unavailable or deprecated. 87 std::string Message; 88 AvailabilityResult Result = D->getAvailability(&Message); 89 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 90 if (Result == AR_Available) { 91 const DeclContext *DC = ECD->getDeclContext(); 92 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 93 Result = TheEnumDecl->getAvailability(&Message); 94 } 95 96 const ObjCPropertyDecl *ObjCPDecl = 0; 97 if (Result == AR_Deprecated || Result == AR_Unavailable) { 98 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 99 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 100 AvailabilityResult PDeclResult = PD->getAvailability(0); 101 if (PDeclResult == Result) 102 ObjCPDecl = PD; 103 } 104 } 105 } 106 107 switch (Result) { 108 case AR_Available: 109 case AR_NotYetIntroduced: 110 break; 111 112 case AR_Deprecated: 113 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl); 114 break; 115 116 case AR_Unavailable: 117 if (S.getCurContextAvailability() != AR_Unavailable) { 118 if (Message.empty()) { 119 if (!UnknownObjCClass) { 120 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 121 if (ObjCPDecl) 122 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 123 << ObjCPDecl->getDeclName() << 1; 124 } 125 else 126 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 127 << D->getDeclName(); 128 } 129 else 130 S.Diag(Loc, diag::err_unavailable_message) 131 << D->getDeclName() << Message; 132 S.Diag(D->getLocation(), diag::note_unavailable_here) 133 << isa<FunctionDecl>(D) << false; 134 if (ObjCPDecl) 135 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 136 << ObjCPDecl->getDeclName() << 1; 137 } 138 break; 139 } 140 return Result; 141 } 142 143 /// \brief Emit a note explaining that this function is deleted or unavailable. 144 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 145 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 146 147 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) { 148 // If the method was explicitly defaulted, point at that declaration. 149 if (!Method->isImplicit()) 150 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 151 152 // Try to diagnose why this special member function was implicitly 153 // deleted. This might fail, if that reason no longer applies. 154 CXXSpecialMember CSM = getSpecialMember(Method); 155 if (CSM != CXXInvalid) 156 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 157 158 return; 159 } 160 161 Diag(Decl->getLocation(), diag::note_unavailable_here) 162 << 1 << Decl->isDeleted(); 163 } 164 165 /// \brief Determine whether a FunctionDecl was ever declared with an 166 /// explicit storage class. 167 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 168 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 169 E = D->redecls_end(); 170 I != E; ++I) { 171 if (I->getStorageClass() != SC_None) 172 return true; 173 } 174 return false; 175 } 176 177 /// \brief Check whether we're in an extern inline function and referring to a 178 /// variable or function with internal linkage (C11 6.7.4p3). 179 /// 180 /// This is only a warning because we used to silently accept this code, but 181 /// in many cases it will not behave correctly. This is not enabled in C++ mode 182 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 183 /// and so while there may still be user mistakes, most of the time we can't 184 /// prove that there are errors. 185 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 186 const NamedDecl *D, 187 SourceLocation Loc) { 188 // This is disabled under C++; there are too many ways for this to fire in 189 // contexts where the warning is a false positive, or where it is technically 190 // correct but benign. 191 if (S.getLangOpts().CPlusPlus) 192 return; 193 194 // Check if this is an inlined function or method. 195 FunctionDecl *Current = S.getCurFunctionDecl(); 196 if (!Current) 197 return; 198 if (!Current->isInlined()) 199 return; 200 if (Current->getLinkage() != ExternalLinkage) 201 return; 202 203 // Check if the decl has internal linkage. 204 if (D->getLinkage() != InternalLinkage) 205 return; 206 207 // Downgrade from ExtWarn to Extension if 208 // (1) the supposedly external inline function is in the main file, 209 // and probably won't be included anywhere else. 210 // (2) the thing we're referencing is a pure function. 211 // (3) the thing we're referencing is another inline function. 212 // This last can give us false negatives, but it's better than warning on 213 // wrappers for simple C library functions. 214 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 215 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc); 216 if (!DowngradeWarning && UsedFn) 217 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 218 219 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 220 : diag::warn_internal_in_extern_inline) 221 << /*IsVar=*/!UsedFn << D; 222 223 S.MaybeSuggestAddingStaticToDecl(Current); 224 225 S.Diag(D->getCanonicalDecl()->getLocation(), 226 diag::note_internal_decl_declared_here) 227 << D; 228 } 229 230 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 231 const FunctionDecl *First = Cur->getFirstDeclaration(); 232 233 // Suggest "static" on the function, if possible. 234 if (!hasAnyExplicitStorageClass(First)) { 235 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 236 Diag(DeclBegin, diag::note_convert_inline_to_static) 237 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 238 } 239 } 240 241 /// \brief Determine whether the use of this declaration is valid, and 242 /// emit any corresponding diagnostics. 243 /// 244 /// This routine diagnoses various problems with referencing 245 /// declarations that can occur when using a declaration. For example, 246 /// it might warn if a deprecated or unavailable declaration is being 247 /// used, or produce an error (and return true) if a C++0x deleted 248 /// function is being used. 249 /// 250 /// \returns true if there was an error (this declaration cannot be 251 /// referenced), false otherwise. 252 /// 253 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 254 const ObjCInterfaceDecl *UnknownObjCClass) { 255 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 256 // If there were any diagnostics suppressed by template argument deduction, 257 // emit them now. 258 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 259 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 260 if (Pos != SuppressedDiagnostics.end()) { 261 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 262 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 263 Diag(Suppressed[I].first, Suppressed[I].second); 264 265 // Clear out the list of suppressed diagnostics, so that we don't emit 266 // them again for this specialization. However, we don't obsolete this 267 // entry from the table, because we want to avoid ever emitting these 268 // diagnostics again. 269 Suppressed.clear(); 270 } 271 } 272 273 // See if this is an auto-typed variable whose initializer we are parsing. 274 if (ParsingInitForAutoVars.count(D)) { 275 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 276 << D->getDeclName(); 277 return true; 278 } 279 280 // See if this is a deleted function. 281 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 282 if (FD->isDeleted()) { 283 Diag(Loc, diag::err_deleted_function_use); 284 NoteDeletedFunction(FD); 285 return true; 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 } 294 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 295 296 DiagnoseUnusedOfDecl(*this, D, Loc); 297 298 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 299 300 return false; 301 } 302 303 /// \brief Retrieve the message suffix that should be added to a 304 /// diagnostic complaining about the given function being deleted or 305 /// unavailable. 306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 307 std::string Message; 308 if (FD->getAvailability(&Message)) 309 return ": " + Message; 310 311 return std::string(); 312 } 313 314 /// DiagnoseSentinelCalls - This routine checks whether a call or 315 /// message-send is to a declaration with the sentinel attribute, and 316 /// if so, it checks that the requirements of the sentinel are 317 /// satisfied. 318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 319 Expr **args, unsigned numArgs) { 320 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 321 if (!attr) 322 return; 323 324 // The number of formal parameters of the declaration. 325 unsigned numFormalParams; 326 327 // The kind of declaration. This is also an index into a %select in 328 // the diagnostic. 329 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 330 331 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 332 numFormalParams = MD->param_size(); 333 calleeType = CT_Method; 334 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 335 numFormalParams = FD->param_size(); 336 calleeType = CT_Function; 337 } else if (isa<VarDecl>(D)) { 338 QualType type = cast<ValueDecl>(D)->getType(); 339 const FunctionType *fn = 0; 340 if (const PointerType *ptr = type->getAs<PointerType>()) { 341 fn = ptr->getPointeeType()->getAs<FunctionType>(); 342 if (!fn) return; 343 calleeType = CT_Function; 344 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 345 fn = ptr->getPointeeType()->castAs<FunctionType>(); 346 calleeType = CT_Block; 347 } else { 348 return; 349 } 350 351 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 352 numFormalParams = proto->getNumArgs(); 353 } else { 354 numFormalParams = 0; 355 } 356 } else { 357 return; 358 } 359 360 // "nullPos" is the number of formal parameters at the end which 361 // effectively count as part of the variadic arguments. This is 362 // useful if you would prefer to not have *any* formal parameters, 363 // but the language forces you to have at least one. 364 unsigned nullPos = attr->getNullPos(); 365 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 366 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 367 368 // The number of arguments which should follow the sentinel. 369 unsigned numArgsAfterSentinel = attr->getSentinel(); 370 371 // If there aren't enough arguments for all the formal parameters, 372 // the sentinel, and the args after the sentinel, complain. 373 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) { 374 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 375 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 376 return; 377 } 378 379 // Otherwise, find the sentinel expression. 380 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1]; 381 if (!sentinelExpr) return; 382 if (sentinelExpr->isValueDependent()) return; 383 if (Context.isSentinelNullExpr(sentinelExpr)) return; 384 385 // Pick a reasonable string to insert. Optimistically use 'nil' or 386 // 'NULL' if those are actually defined in the context. Only use 387 // 'nil' for ObjC methods, where it's much more likely that the 388 // variadic arguments form a list of object pointers. 389 SourceLocation MissingNilLoc 390 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 391 std::string NullValue; 392 if (calleeType == CT_Method && 393 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 394 NullValue = "nil"; 395 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 396 NullValue = "NULL"; 397 else 398 NullValue = "(void*) 0"; 399 400 if (MissingNilLoc.isInvalid()) 401 Diag(Loc, diag::warn_missing_sentinel) << calleeType; 402 else 403 Diag(MissingNilLoc, diag::warn_missing_sentinel) 404 << calleeType 405 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 406 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 407 } 408 409 SourceRange Sema::getExprRange(Expr *E) const { 410 return E ? E->getSourceRange() : SourceRange(); 411 } 412 413 //===----------------------------------------------------------------------===// 414 // Standard Promotions and Conversions 415 //===----------------------------------------------------------------------===// 416 417 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 418 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 419 // Handle any placeholder expressions which made it here. 420 if (E->getType()->isPlaceholderType()) { 421 ExprResult result = CheckPlaceholderExpr(E); 422 if (result.isInvalid()) return ExprError(); 423 E = result.take(); 424 } 425 426 QualType Ty = E->getType(); 427 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 428 429 if (Ty->isFunctionType()) 430 E = ImpCastExprToType(E, Context.getPointerType(Ty), 431 CK_FunctionToPointerDecay).take(); 432 else if (Ty->isArrayType()) { 433 // In C90 mode, arrays only promote to pointers if the array expression is 434 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 435 // type 'array of type' is converted to an expression that has type 'pointer 436 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 437 // that has type 'array of type' ...". The relevant change is "an lvalue" 438 // (C90) to "an expression" (C99). 439 // 440 // C++ 4.2p1: 441 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 442 // T" can be converted to an rvalue of type "pointer to T". 443 // 444 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 445 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 446 CK_ArrayToPointerDecay).take(); 447 } 448 return Owned(E); 449 } 450 451 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 452 // Check to see if we are dereferencing a null pointer. If so, 453 // and if not volatile-qualified, this is undefined behavior that the 454 // optimizer will delete, so warn about it. People sometimes try to use this 455 // to get a deterministic trap and are surprised by clang's behavior. This 456 // only handles the pattern "*null", which is a very syntactic check. 457 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 458 if (UO->getOpcode() == UO_Deref && 459 UO->getSubExpr()->IgnoreParenCasts()-> 460 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 461 !UO->getType().isVolatileQualified()) { 462 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 463 S.PDiag(diag::warn_indirection_through_null) 464 << UO->getSubExpr()->getSourceRange()); 465 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 466 S.PDiag(diag::note_indirection_through_null)); 467 } 468 } 469 470 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 471 SourceLocation AssignLoc, 472 const Expr* RHS) { 473 const ObjCIvarDecl *IV = OIRE->getDecl(); 474 if (!IV) 475 return; 476 477 DeclarationName MemberName = IV->getDeclName(); 478 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 479 if (!Member || !Member->isStr("isa")) 480 return; 481 482 const Expr *Base = OIRE->getBase(); 483 QualType BaseType = Base->getType(); 484 if (OIRE->isArrow()) 485 BaseType = BaseType->getPointeeType(); 486 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 487 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 488 ObjCInterfaceDecl *ClassDeclared = 0; 489 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 490 if (!ClassDeclared->getSuperClass() 491 && (*ClassDeclared->ivar_begin()) == IV) { 492 if (RHS) { 493 NamedDecl *ObjectSetClass = 494 S.LookupSingleName(S.TUScope, 495 &S.Context.Idents.get("object_setClass"), 496 SourceLocation(), S.LookupOrdinaryName); 497 if (ObjectSetClass) { 498 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 499 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 500 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 501 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 502 AssignLoc), ",") << 503 FixItHint::CreateInsertion(RHSLocEnd, ")"); 504 } 505 else 506 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 507 } else { 508 NamedDecl *ObjectGetClass = 509 S.LookupSingleName(S.TUScope, 510 &S.Context.Idents.get("object_getClass"), 511 SourceLocation(), S.LookupOrdinaryName); 512 if (ObjectGetClass) 513 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 514 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 515 FixItHint::CreateReplacement( 516 SourceRange(OIRE->getOpLoc(), 517 OIRE->getLocEnd()), ")"); 518 else 519 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 520 } 521 S.Diag(IV->getLocation(), diag::note_ivar_decl); 522 } 523 } 524 } 525 526 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 527 // Handle any placeholder expressions which made it here. 528 if (E->getType()->isPlaceholderType()) { 529 ExprResult result = CheckPlaceholderExpr(E); 530 if (result.isInvalid()) return ExprError(); 531 E = result.take(); 532 } 533 534 // C++ [conv.lval]p1: 535 // A glvalue of a non-function, non-array type T can be 536 // converted to a prvalue. 537 if (!E->isGLValue()) return Owned(E); 538 539 QualType T = E->getType(); 540 assert(!T.isNull() && "r-value conversion on typeless expression?"); 541 542 // We don't want to throw lvalue-to-rvalue casts on top of 543 // expressions of certain types in C++. 544 if (getLangOpts().CPlusPlus && 545 (E->getType() == Context.OverloadTy || 546 T->isDependentType() || 547 T->isRecordType())) 548 return Owned(E); 549 550 // The C standard is actually really unclear on this point, and 551 // DR106 tells us what the result should be but not why. It's 552 // generally best to say that void types just doesn't undergo 553 // lvalue-to-rvalue at all. Note that expressions of unqualified 554 // 'void' type are never l-values, but qualified void can be. 555 if (T->isVoidType()) 556 return Owned(E); 557 558 // OpenCL usually rejects direct accesses to values of 'half' type. 559 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 560 T->isHalfType()) { 561 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 562 << 0 << T; 563 return ExprError(); 564 } 565 566 CheckForNullPointerDereference(*this, E); 567 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 568 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 569 &Context.Idents.get("object_getClass"), 570 SourceLocation(), LookupOrdinaryName); 571 if (ObjectGetClass) 572 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 573 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 574 FixItHint::CreateReplacement( 575 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 576 else 577 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 578 } 579 else if (const ObjCIvarRefExpr *OIRE = 580 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 581 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 582 583 // C++ [conv.lval]p1: 584 // [...] If T is a non-class type, the type of the prvalue is the 585 // cv-unqualified version of T. Otherwise, the type of the 586 // rvalue is T. 587 // 588 // C99 6.3.2.1p2: 589 // If the lvalue has qualified type, the value has the unqualified 590 // version of the type of the lvalue; otherwise, the value has the 591 // type of the lvalue. 592 if (T.hasQualifiers()) 593 T = T.getUnqualifiedType(); 594 595 UpdateMarkingForLValueToRValue(E); 596 597 // Loading a __weak object implicitly retains the value, so we need a cleanup to 598 // balance that. 599 if (getLangOpts().ObjCAutoRefCount && 600 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 601 ExprNeedsCleanups = true; 602 603 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 604 E, 0, VK_RValue)); 605 606 // C11 6.3.2.1p2: 607 // ... if the lvalue has atomic type, the value has the non-atomic version 608 // of the type of the lvalue ... 609 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 610 T = Atomic->getValueType().getUnqualifiedType(); 611 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 612 Res.get(), 0, VK_RValue)); 613 } 614 615 return Res; 616 } 617 618 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 619 ExprResult Res = DefaultFunctionArrayConversion(E); 620 if (Res.isInvalid()) 621 return ExprError(); 622 Res = DefaultLvalueConversion(Res.take()); 623 if (Res.isInvalid()) 624 return ExprError(); 625 return Res; 626 } 627 628 629 /// UsualUnaryConversions - Performs various conversions that are common to most 630 /// operators (C99 6.3). The conversions of array and function types are 631 /// sometimes suppressed. For example, the array->pointer conversion doesn't 632 /// apply if the array is an argument to the sizeof or address (&) operators. 633 /// In these instances, this routine should *not* be called. 634 ExprResult Sema::UsualUnaryConversions(Expr *E) { 635 // First, convert to an r-value. 636 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 637 if (Res.isInvalid()) 638 return ExprError(); 639 E = Res.take(); 640 641 QualType Ty = E->getType(); 642 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 643 644 // Half FP have to be promoted to float unless it is natively supported 645 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 646 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 647 648 // Try to perform integral promotions if the object has a theoretically 649 // promotable type. 650 if (Ty->isIntegralOrUnscopedEnumerationType()) { 651 // C99 6.3.1.1p2: 652 // 653 // The following may be used in an expression wherever an int or 654 // unsigned int may be used: 655 // - an object or expression with an integer type whose integer 656 // conversion rank is less than or equal to the rank of int 657 // and unsigned int. 658 // - A bit-field of type _Bool, int, signed int, or unsigned int. 659 // 660 // If an int can represent all values of the original type, the 661 // value is converted to an int; otherwise, it is converted to an 662 // unsigned int. These are called the integer promotions. All 663 // other types are unchanged by the integer promotions. 664 665 QualType PTy = Context.isPromotableBitField(E); 666 if (!PTy.isNull()) { 667 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 668 return Owned(E); 669 } 670 if (Ty->isPromotableIntegerType()) { 671 QualType PT = Context.getPromotedIntegerType(Ty); 672 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 673 return Owned(E); 674 } 675 } 676 return Owned(E); 677 } 678 679 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 680 /// do not have a prototype. Arguments that have type float or __fp16 681 /// are promoted to double. All other argument types are converted by 682 /// UsualUnaryConversions(). 683 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 684 QualType Ty = E->getType(); 685 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 686 687 ExprResult Res = UsualUnaryConversions(E); 688 if (Res.isInvalid()) 689 return ExprError(); 690 E = Res.take(); 691 692 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 693 // double. 694 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 695 if (BTy && (BTy->getKind() == BuiltinType::Half || 696 BTy->getKind() == BuiltinType::Float)) 697 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 698 699 // C++ performs lvalue-to-rvalue conversion as a default argument 700 // promotion, even on class types, but note: 701 // C++11 [conv.lval]p2: 702 // When an lvalue-to-rvalue conversion occurs in an unevaluated 703 // operand or a subexpression thereof the value contained in the 704 // referenced object is not accessed. Otherwise, if the glvalue 705 // has a class type, the conversion copy-initializes a temporary 706 // of type T from the glvalue and the result of the conversion 707 // is a prvalue for the temporary. 708 // FIXME: add some way to gate this entire thing for correctness in 709 // potentially potentially evaluated contexts. 710 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 711 ExprResult Temp = PerformCopyInitialization( 712 InitializedEntity::InitializeTemporary(E->getType()), 713 E->getExprLoc(), 714 Owned(E)); 715 if (Temp.isInvalid()) 716 return ExprError(); 717 E = Temp.get(); 718 } 719 720 return Owned(E); 721 } 722 723 /// Determine the degree of POD-ness for an expression. 724 /// Incomplete types are considered POD, since this check can be performed 725 /// when we're in an unevaluated context. 726 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 727 if (Ty->isIncompleteType()) { 728 if (Ty->isObjCObjectType()) 729 return VAK_Invalid; 730 return VAK_Valid; 731 } 732 733 if (Ty.isCXX98PODType(Context)) 734 return VAK_Valid; 735 736 // C++11 [expr.call]p7: 737 // Passing a potentially-evaluated argument of class type (Clause 9) 738 // having a non-trivial copy constructor, a non-trivial move constructor, 739 // or a non-trivial destructor, with no corresponding parameter, 740 // is conditionally-supported with implementation-defined semantics. 741 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 742 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 743 if (!Record->hasNonTrivialCopyConstructor() && 744 !Record->hasNonTrivialMoveConstructor() && 745 !Record->hasNonTrivialDestructor()) 746 return VAK_ValidInCXX11; 747 748 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 749 return VAK_Valid; 750 return VAK_Invalid; 751 } 752 753 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) { 754 // Don't allow one to pass an Objective-C interface to a vararg. 755 const QualType & Ty = E->getType(); 756 757 // Complain about passing non-POD types through varargs. 758 switch (isValidVarArgType(Ty)) { 759 case VAK_Valid: 760 break; 761 case VAK_ValidInCXX11: 762 DiagRuntimeBehavior(E->getLocStart(), 0, 763 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 764 << E->getType() << CT); 765 break; 766 case VAK_Invalid: { 767 if (Ty->isObjCObjectType()) 768 return DiagRuntimeBehavior(E->getLocStart(), 0, 769 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 770 << Ty << CT); 771 772 return DiagRuntimeBehavior(E->getLocStart(), 0, 773 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 774 << getLangOpts().CPlusPlus11 << Ty << CT); 775 } 776 } 777 // c++ rules are enforced elsewhere. 778 return false; 779 } 780 781 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 782 /// will create a trap if the resulting type is not a POD type. 783 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 784 FunctionDecl *FDecl) { 785 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 786 // Strip the unbridged-cast placeholder expression off, if applicable. 787 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 788 (CT == VariadicMethod || 789 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 790 E = stripARCUnbridgedCast(E); 791 792 // Otherwise, do normal placeholder checking. 793 } else { 794 ExprResult ExprRes = CheckPlaceholderExpr(E); 795 if (ExprRes.isInvalid()) 796 return ExprError(); 797 E = ExprRes.take(); 798 } 799 } 800 801 ExprResult ExprRes = DefaultArgumentPromotion(E); 802 if (ExprRes.isInvalid()) 803 return ExprError(); 804 E = ExprRes.take(); 805 806 // Diagnostics regarding non-POD argument types are 807 // emitted along with format string checking in Sema::CheckFunctionCall(). 808 if (isValidVarArgType(E->getType()) == VAK_Invalid) { 809 // Turn this into a trap. 810 CXXScopeSpec SS; 811 SourceLocation TemplateKWLoc; 812 UnqualifiedId Name; 813 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 814 E->getLocStart()); 815 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 816 Name, true, false); 817 if (TrapFn.isInvalid()) 818 return ExprError(); 819 820 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 821 E->getLocStart(), None, 822 E->getLocEnd()); 823 if (Call.isInvalid()) 824 return ExprError(); 825 826 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 827 Call.get(), E); 828 if (Comma.isInvalid()) 829 return ExprError(); 830 return Comma.get(); 831 } 832 833 if (!getLangOpts().CPlusPlus && 834 RequireCompleteType(E->getExprLoc(), E->getType(), 835 diag::err_call_incomplete_argument)) 836 return ExprError(); 837 838 return Owned(E); 839 } 840 841 /// \brief Converts an integer to complex float type. Helper function of 842 /// UsualArithmeticConversions() 843 /// 844 /// \return false if the integer expression is an integer type and is 845 /// successfully converted to the complex type. 846 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 847 ExprResult &ComplexExpr, 848 QualType IntTy, 849 QualType ComplexTy, 850 bool SkipCast) { 851 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 852 if (SkipCast) return false; 853 if (IntTy->isIntegerType()) { 854 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 855 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 856 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 857 CK_FloatingRealToComplex); 858 } else { 859 assert(IntTy->isComplexIntegerType()); 860 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 861 CK_IntegralComplexToFloatingComplex); 862 } 863 return false; 864 } 865 866 /// \brief Takes two complex float types and converts them to the same type. 867 /// Helper function of UsualArithmeticConversions() 868 static QualType 869 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 870 ExprResult &RHS, QualType LHSType, 871 QualType RHSType, 872 bool IsCompAssign) { 873 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 874 875 if (order < 0) { 876 // _Complex float -> _Complex double 877 if (!IsCompAssign) 878 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 879 return RHSType; 880 } 881 if (order > 0) 882 // _Complex float -> _Complex double 883 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 884 return LHSType; 885 } 886 887 /// \brief Converts otherExpr to complex float and promotes complexExpr if 888 /// necessary. Helper function of UsualArithmeticConversions() 889 static QualType handleOtherComplexFloatConversion(Sema &S, 890 ExprResult &ComplexExpr, 891 ExprResult &OtherExpr, 892 QualType ComplexTy, 893 QualType OtherTy, 894 bool ConvertComplexExpr, 895 bool ConvertOtherExpr) { 896 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 897 898 // If just the complexExpr is complex, the otherExpr needs to be converted, 899 // and the complexExpr might need to be promoted. 900 if (order > 0) { // complexExpr is wider 901 // float -> _Complex double 902 if (ConvertOtherExpr) { 903 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 904 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 905 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 906 CK_FloatingRealToComplex); 907 } 908 return ComplexTy; 909 } 910 911 // otherTy is at least as wide. Find its corresponding complex type. 912 QualType result = (order == 0 ? ComplexTy : 913 S.Context.getComplexType(OtherTy)); 914 915 // double -> _Complex double 916 if (ConvertOtherExpr) 917 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 918 CK_FloatingRealToComplex); 919 920 // _Complex float -> _Complex double 921 if (ConvertComplexExpr && order < 0) 922 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 923 CK_FloatingComplexCast); 924 925 return result; 926 } 927 928 /// \brief Handle arithmetic conversion with complex types. Helper function of 929 /// UsualArithmeticConversions() 930 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 931 ExprResult &RHS, QualType LHSType, 932 QualType RHSType, 933 bool IsCompAssign) { 934 // if we have an integer operand, the result is the complex type. 935 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 936 /*skipCast*/false)) 937 return LHSType; 938 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 939 /*skipCast*/IsCompAssign)) 940 return RHSType; 941 942 // This handles complex/complex, complex/float, or float/complex. 943 // When both operands are complex, the shorter operand is converted to the 944 // type of the longer, and that is the type of the result. This corresponds 945 // to what is done when combining two real floating-point operands. 946 // The fun begins when size promotion occur across type domains. 947 // From H&S 6.3.4: When one operand is complex and the other is a real 948 // floating-point type, the less precise type is converted, within it's 949 // real or complex domain, to the precision of the other type. For example, 950 // when combining a "long double" with a "double _Complex", the 951 // "double _Complex" is promoted to "long double _Complex". 952 953 bool LHSComplexFloat = LHSType->isComplexType(); 954 bool RHSComplexFloat = RHSType->isComplexType(); 955 956 // If both are complex, just cast to the more precise type. 957 if (LHSComplexFloat && RHSComplexFloat) 958 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 959 LHSType, RHSType, 960 IsCompAssign); 961 962 // If only one operand is complex, promote it if necessary and convert the 963 // other operand to complex. 964 if (LHSComplexFloat) 965 return handleOtherComplexFloatConversion( 966 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 967 /*convertOtherExpr*/ true); 968 969 assert(RHSComplexFloat); 970 return handleOtherComplexFloatConversion( 971 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 972 /*convertOtherExpr*/ !IsCompAssign); 973 } 974 975 /// \brief Hande arithmetic conversion from integer to float. Helper function 976 /// of UsualArithmeticConversions() 977 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 978 ExprResult &IntExpr, 979 QualType FloatTy, QualType IntTy, 980 bool ConvertFloat, bool ConvertInt) { 981 if (IntTy->isIntegerType()) { 982 if (ConvertInt) 983 // Convert intExpr to the lhs floating point type. 984 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 985 CK_IntegralToFloating); 986 return FloatTy; 987 } 988 989 // Convert both sides to the appropriate complex float. 990 assert(IntTy->isComplexIntegerType()); 991 QualType result = S.Context.getComplexType(FloatTy); 992 993 // _Complex int -> _Complex float 994 if (ConvertInt) 995 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 996 CK_IntegralComplexToFloatingComplex); 997 998 // float -> _Complex float 999 if (ConvertFloat) 1000 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1001 CK_FloatingRealToComplex); 1002 1003 return result; 1004 } 1005 1006 /// \brief Handle arithmethic conversion with floating point types. Helper 1007 /// function of UsualArithmeticConversions() 1008 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1009 ExprResult &RHS, QualType LHSType, 1010 QualType RHSType, bool IsCompAssign) { 1011 bool LHSFloat = LHSType->isRealFloatingType(); 1012 bool RHSFloat = RHSType->isRealFloatingType(); 1013 1014 // If we have two real floating types, convert the smaller operand 1015 // to the bigger result. 1016 if (LHSFloat && RHSFloat) { 1017 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1018 if (order > 0) { 1019 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1020 return LHSType; 1021 } 1022 1023 assert(order < 0 && "illegal float comparison"); 1024 if (!IsCompAssign) 1025 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1026 return RHSType; 1027 } 1028 1029 if (LHSFloat) 1030 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1031 /*convertFloat=*/!IsCompAssign, 1032 /*convertInt=*/ true); 1033 assert(RHSFloat); 1034 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1035 /*convertInt=*/ true, 1036 /*convertFloat=*/!IsCompAssign); 1037 } 1038 1039 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1040 1041 namespace { 1042 /// These helper callbacks are placed in an anonymous namespace to 1043 /// permit their use as function template parameters. 1044 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1045 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1046 } 1047 1048 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1049 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1050 CK_IntegralComplexCast); 1051 } 1052 } 1053 1054 /// \brief Handle integer arithmetic conversions. Helper function of 1055 /// UsualArithmeticConversions() 1056 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1057 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1058 ExprResult &RHS, QualType LHSType, 1059 QualType RHSType, bool IsCompAssign) { 1060 // The rules for this case are in C99 6.3.1.8 1061 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1062 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1063 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1064 if (LHSSigned == RHSSigned) { 1065 // Same signedness; use the higher-ranked type 1066 if (order >= 0) { 1067 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1068 return LHSType; 1069 } else if (!IsCompAssign) 1070 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1071 return RHSType; 1072 } else if (order != (LHSSigned ? 1 : -1)) { 1073 // The unsigned type has greater than or equal rank to the 1074 // signed type, so use the unsigned type 1075 if (RHSSigned) { 1076 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1077 return LHSType; 1078 } else if (!IsCompAssign) 1079 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1080 return RHSType; 1081 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1082 // The two types are different widths; if we are here, that 1083 // means the signed type is larger than the unsigned type, so 1084 // use the signed type. 1085 if (LHSSigned) { 1086 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1087 return LHSType; 1088 } else if (!IsCompAssign) 1089 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1090 return RHSType; 1091 } else { 1092 // The signed type is higher-ranked than the unsigned type, 1093 // but isn't actually any bigger (like unsigned int and long 1094 // on most 32-bit systems). Use the unsigned type corresponding 1095 // to the signed type. 1096 QualType result = 1097 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1098 RHS = (*doRHSCast)(S, RHS.take(), result); 1099 if (!IsCompAssign) 1100 LHS = (*doLHSCast)(S, LHS.take(), result); 1101 return result; 1102 } 1103 } 1104 1105 /// \brief Handle conversions with GCC complex int extension. Helper function 1106 /// of UsualArithmeticConversions() 1107 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1108 ExprResult &RHS, QualType LHSType, 1109 QualType RHSType, 1110 bool IsCompAssign) { 1111 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1112 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1113 1114 if (LHSComplexInt && RHSComplexInt) { 1115 QualType LHSEltType = LHSComplexInt->getElementType(); 1116 QualType RHSEltType = RHSComplexInt->getElementType(); 1117 QualType ScalarType = 1118 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1119 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1120 1121 return S.Context.getComplexType(ScalarType); 1122 } 1123 1124 if (LHSComplexInt) { 1125 QualType LHSEltType = LHSComplexInt->getElementType(); 1126 QualType ScalarType = 1127 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1128 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1129 QualType ComplexType = S.Context.getComplexType(ScalarType); 1130 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1131 CK_IntegralRealToComplex); 1132 1133 return ComplexType; 1134 } 1135 1136 assert(RHSComplexInt); 1137 1138 QualType RHSEltType = RHSComplexInt->getElementType(); 1139 QualType ScalarType = 1140 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1141 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1142 QualType ComplexType = S.Context.getComplexType(ScalarType); 1143 1144 if (!IsCompAssign) 1145 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1146 CK_IntegralRealToComplex); 1147 return ComplexType; 1148 } 1149 1150 /// UsualArithmeticConversions - Performs various conversions that are common to 1151 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1152 /// routine returns the first non-arithmetic type found. The client is 1153 /// responsible for emitting appropriate error diagnostics. 1154 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1155 bool IsCompAssign) { 1156 if (!IsCompAssign) { 1157 LHS = UsualUnaryConversions(LHS.take()); 1158 if (LHS.isInvalid()) 1159 return QualType(); 1160 } 1161 1162 RHS = UsualUnaryConversions(RHS.take()); 1163 if (RHS.isInvalid()) 1164 return QualType(); 1165 1166 // For conversion purposes, we ignore any qualifiers. 1167 // For example, "const float" and "float" are equivalent. 1168 QualType LHSType = 1169 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1170 QualType RHSType = 1171 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1172 1173 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1174 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1175 LHSType = AtomicLHS->getValueType(); 1176 1177 // If both types are identical, no conversion is needed. 1178 if (LHSType == RHSType) 1179 return LHSType; 1180 1181 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1182 // The caller can deal with this (e.g. pointer + int). 1183 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1184 return QualType(); 1185 1186 // Apply unary and bitfield promotions to the LHS's type. 1187 QualType LHSUnpromotedType = LHSType; 1188 if (LHSType->isPromotableIntegerType()) 1189 LHSType = Context.getPromotedIntegerType(LHSType); 1190 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1191 if (!LHSBitfieldPromoteTy.isNull()) 1192 LHSType = LHSBitfieldPromoteTy; 1193 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1194 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1195 1196 // If both types are identical, no conversion is needed. 1197 if (LHSType == RHSType) 1198 return LHSType; 1199 1200 // At this point, we have two different arithmetic types. 1201 1202 // Handle complex types first (C99 6.3.1.8p1). 1203 if (LHSType->isComplexType() || RHSType->isComplexType()) 1204 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1205 IsCompAssign); 1206 1207 // Now handle "real" floating types (i.e. float, double, long double). 1208 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1209 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1210 IsCompAssign); 1211 1212 // Handle GCC complex int extension. 1213 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1214 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1215 IsCompAssign); 1216 1217 // Finally, we have two differing integer types. 1218 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1219 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1220 } 1221 1222 1223 //===----------------------------------------------------------------------===// 1224 // Semantic Analysis for various Expression Types 1225 //===----------------------------------------------------------------------===// 1226 1227 1228 ExprResult 1229 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1230 SourceLocation DefaultLoc, 1231 SourceLocation RParenLoc, 1232 Expr *ControllingExpr, 1233 MultiTypeArg ArgTypes, 1234 MultiExprArg ArgExprs) { 1235 unsigned NumAssocs = ArgTypes.size(); 1236 assert(NumAssocs == ArgExprs.size()); 1237 1238 ParsedType *ParsedTypes = ArgTypes.data(); 1239 Expr **Exprs = ArgExprs.data(); 1240 1241 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1242 for (unsigned i = 0; i < NumAssocs; ++i) { 1243 if (ParsedTypes[i]) 1244 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]); 1245 else 1246 Types[i] = 0; 1247 } 1248 1249 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1250 ControllingExpr, Types, Exprs, 1251 NumAssocs); 1252 delete [] Types; 1253 return ER; 1254 } 1255 1256 ExprResult 1257 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1258 SourceLocation DefaultLoc, 1259 SourceLocation RParenLoc, 1260 Expr *ControllingExpr, 1261 TypeSourceInfo **Types, 1262 Expr **Exprs, 1263 unsigned NumAssocs) { 1264 if (ControllingExpr->getType()->isPlaceholderType()) { 1265 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1266 if (result.isInvalid()) return ExprError(); 1267 ControllingExpr = result.take(); 1268 } 1269 1270 bool TypeErrorFound = false, 1271 IsResultDependent = ControllingExpr->isTypeDependent(), 1272 ContainsUnexpandedParameterPack 1273 = ControllingExpr->containsUnexpandedParameterPack(); 1274 1275 for (unsigned i = 0; i < NumAssocs; ++i) { 1276 if (Exprs[i]->containsUnexpandedParameterPack()) 1277 ContainsUnexpandedParameterPack = true; 1278 1279 if (Types[i]) { 1280 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1281 ContainsUnexpandedParameterPack = true; 1282 1283 if (Types[i]->getType()->isDependentType()) { 1284 IsResultDependent = true; 1285 } else { 1286 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1287 // complete object type other than a variably modified type." 1288 unsigned D = 0; 1289 if (Types[i]->getType()->isIncompleteType()) 1290 D = diag::err_assoc_type_incomplete; 1291 else if (!Types[i]->getType()->isObjectType()) 1292 D = diag::err_assoc_type_nonobject; 1293 else if (Types[i]->getType()->isVariablyModifiedType()) 1294 D = diag::err_assoc_type_variably_modified; 1295 1296 if (D != 0) { 1297 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1298 << Types[i]->getTypeLoc().getSourceRange() 1299 << Types[i]->getType(); 1300 TypeErrorFound = true; 1301 } 1302 1303 // C11 6.5.1.1p2 "No two generic associations in the same generic 1304 // selection shall specify compatible types." 1305 for (unsigned j = i+1; j < NumAssocs; ++j) 1306 if (Types[j] && !Types[j]->getType()->isDependentType() && 1307 Context.typesAreCompatible(Types[i]->getType(), 1308 Types[j]->getType())) { 1309 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1310 diag::err_assoc_compatible_types) 1311 << Types[j]->getTypeLoc().getSourceRange() 1312 << Types[j]->getType() 1313 << Types[i]->getType(); 1314 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1315 diag::note_compat_assoc) 1316 << Types[i]->getTypeLoc().getSourceRange() 1317 << Types[i]->getType(); 1318 TypeErrorFound = true; 1319 } 1320 } 1321 } 1322 } 1323 if (TypeErrorFound) 1324 return ExprError(); 1325 1326 // If we determined that the generic selection is result-dependent, don't 1327 // try to compute the result expression. 1328 if (IsResultDependent) 1329 return Owned(new (Context) GenericSelectionExpr( 1330 Context, KeyLoc, ControllingExpr, 1331 llvm::makeArrayRef(Types, NumAssocs), 1332 llvm::makeArrayRef(Exprs, NumAssocs), 1333 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1334 1335 SmallVector<unsigned, 1> CompatIndices; 1336 unsigned DefaultIndex = -1U; 1337 for (unsigned i = 0; i < NumAssocs; ++i) { 1338 if (!Types[i]) 1339 DefaultIndex = i; 1340 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1341 Types[i]->getType())) 1342 CompatIndices.push_back(i); 1343 } 1344 1345 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1346 // type compatible with at most one of the types named in its generic 1347 // association list." 1348 if (CompatIndices.size() > 1) { 1349 // We strip parens here because the controlling expression is typically 1350 // parenthesized in macro definitions. 1351 ControllingExpr = ControllingExpr->IgnoreParens(); 1352 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1353 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1354 << (unsigned) CompatIndices.size(); 1355 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1356 E = CompatIndices.end(); I != E; ++I) { 1357 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1358 diag::note_compat_assoc) 1359 << Types[*I]->getTypeLoc().getSourceRange() 1360 << Types[*I]->getType(); 1361 } 1362 return ExprError(); 1363 } 1364 1365 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1366 // its controlling expression shall have type compatible with exactly one of 1367 // the types named in its generic association list." 1368 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1369 // We strip parens here because the controlling expression is typically 1370 // parenthesized in macro definitions. 1371 ControllingExpr = ControllingExpr->IgnoreParens(); 1372 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1373 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1374 return ExprError(); 1375 } 1376 1377 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1378 // type name that is compatible with the type of the controlling expression, 1379 // then the result expression of the generic selection is the expression 1380 // in that generic association. Otherwise, the result expression of the 1381 // generic selection is the expression in the default generic association." 1382 unsigned ResultIndex = 1383 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1384 1385 return Owned(new (Context) GenericSelectionExpr( 1386 Context, KeyLoc, ControllingExpr, 1387 llvm::makeArrayRef(Types, NumAssocs), 1388 llvm::makeArrayRef(Exprs, NumAssocs), 1389 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1390 ResultIndex)); 1391 } 1392 1393 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1394 /// location of the token and the offset of the ud-suffix within it. 1395 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1396 unsigned Offset) { 1397 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1398 S.getLangOpts()); 1399 } 1400 1401 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1402 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1403 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1404 IdentifierInfo *UDSuffix, 1405 SourceLocation UDSuffixLoc, 1406 ArrayRef<Expr*> Args, 1407 SourceLocation LitEndLoc) { 1408 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1409 1410 QualType ArgTy[2]; 1411 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1412 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1413 if (ArgTy[ArgIdx]->isArrayType()) 1414 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1415 } 1416 1417 DeclarationName OpName = 1418 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1419 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1420 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1421 1422 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1423 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1424 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1425 return ExprError(); 1426 1427 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1428 } 1429 1430 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1431 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1432 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1433 /// multiple tokens. However, the common case is that StringToks points to one 1434 /// string. 1435 /// 1436 ExprResult 1437 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1438 Scope *UDLScope) { 1439 assert(NumStringToks && "Must have at least one string!"); 1440 1441 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1442 if (Literal.hadError) 1443 return ExprError(); 1444 1445 SmallVector<SourceLocation, 4> StringTokLocs; 1446 for (unsigned i = 0; i != NumStringToks; ++i) 1447 StringTokLocs.push_back(StringToks[i].getLocation()); 1448 1449 QualType StrTy = Context.CharTy; 1450 if (Literal.isWide()) 1451 StrTy = Context.getWCharType(); 1452 else if (Literal.isUTF16()) 1453 StrTy = Context.Char16Ty; 1454 else if (Literal.isUTF32()) 1455 StrTy = Context.Char32Ty; 1456 else if (Literal.isPascal()) 1457 StrTy = Context.UnsignedCharTy; 1458 1459 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1460 if (Literal.isWide()) 1461 Kind = StringLiteral::Wide; 1462 else if (Literal.isUTF8()) 1463 Kind = StringLiteral::UTF8; 1464 else if (Literal.isUTF16()) 1465 Kind = StringLiteral::UTF16; 1466 else if (Literal.isUTF32()) 1467 Kind = StringLiteral::UTF32; 1468 1469 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1470 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1471 StrTy.addConst(); 1472 1473 // Get an array type for the string, according to C99 6.4.5. This includes 1474 // the nul terminator character as well as the string length for pascal 1475 // strings. 1476 StrTy = Context.getConstantArrayType(StrTy, 1477 llvm::APInt(32, Literal.GetNumStringChars()+1), 1478 ArrayType::Normal, 0); 1479 1480 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1481 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1482 Kind, Literal.Pascal, StrTy, 1483 &StringTokLocs[0], 1484 StringTokLocs.size()); 1485 if (Literal.getUDSuffix().empty()) 1486 return Owned(Lit); 1487 1488 // We're building a user-defined literal. 1489 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1490 SourceLocation UDSuffixLoc = 1491 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1492 Literal.getUDSuffixOffset()); 1493 1494 // Make sure we're allowed user-defined literals here. 1495 if (!UDLScope) 1496 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1497 1498 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1499 // operator "" X (str, len) 1500 QualType SizeType = Context.getSizeType(); 1501 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1502 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1503 StringTokLocs[0]); 1504 Expr *Args[] = { Lit, LenArg }; 1505 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1506 Args, StringTokLocs.back()); 1507 } 1508 1509 ExprResult 1510 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1511 SourceLocation Loc, 1512 const CXXScopeSpec *SS) { 1513 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1514 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1515 } 1516 1517 /// BuildDeclRefExpr - Build an expression that references a 1518 /// declaration that does not require a closure capture. 1519 ExprResult 1520 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1521 const DeclarationNameInfo &NameInfo, 1522 const CXXScopeSpec *SS, NamedDecl *FoundD) { 1523 if (getLangOpts().CUDA) 1524 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1525 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1526 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1527 CalleeTarget = IdentifyCUDATarget(Callee); 1528 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1529 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1530 << CalleeTarget << D->getIdentifier() << CallerTarget; 1531 Diag(D->getLocation(), diag::note_previous_decl) 1532 << D->getIdentifier(); 1533 return ExprError(); 1534 } 1535 } 1536 1537 bool refersToEnclosingScope = 1538 (CurContext != D->getDeclContext() && 1539 D->getDeclContext()->isFunctionOrMethod()); 1540 1541 DeclRefExpr *E = DeclRefExpr::Create(Context, 1542 SS ? SS->getWithLocInContext(Context) 1543 : NestedNameSpecifierLoc(), 1544 SourceLocation(), 1545 D, refersToEnclosingScope, 1546 NameInfo, Ty, VK, FoundD); 1547 1548 MarkDeclRefReferenced(E); 1549 1550 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1551 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1552 DiagnosticsEngine::Level Level = 1553 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1554 E->getLocStart()); 1555 if (Level != DiagnosticsEngine::Ignored) 1556 getCurFunction()->recordUseOfWeak(E); 1557 } 1558 1559 // Just in case we're building an illegal pointer-to-member. 1560 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1561 if (FD && FD->isBitField()) 1562 E->setObjectKind(OK_BitField); 1563 1564 return Owned(E); 1565 } 1566 1567 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1568 /// possibly a list of template arguments. 1569 /// 1570 /// If this produces template arguments, it is permitted to call 1571 /// DecomposeTemplateName. 1572 /// 1573 /// This actually loses a lot of source location information for 1574 /// non-standard name kinds; we should consider preserving that in 1575 /// some way. 1576 void 1577 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1578 TemplateArgumentListInfo &Buffer, 1579 DeclarationNameInfo &NameInfo, 1580 const TemplateArgumentListInfo *&TemplateArgs) { 1581 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1582 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1583 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1584 1585 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1586 Id.TemplateId->NumArgs); 1587 translateTemplateArguments(TemplateArgsPtr, Buffer); 1588 1589 TemplateName TName = Id.TemplateId->Template.get(); 1590 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1591 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1592 TemplateArgs = &Buffer; 1593 } else { 1594 NameInfo = GetNameFromUnqualifiedId(Id); 1595 TemplateArgs = 0; 1596 } 1597 } 1598 1599 /// Diagnose an empty lookup. 1600 /// 1601 /// \return false if new lookup candidates were found 1602 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1603 CorrectionCandidateCallback &CCC, 1604 TemplateArgumentListInfo *ExplicitTemplateArgs, 1605 llvm::ArrayRef<Expr *> Args) { 1606 DeclarationName Name = R.getLookupName(); 1607 1608 unsigned diagnostic = diag::err_undeclared_var_use; 1609 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1610 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1611 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1612 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1613 diagnostic = diag::err_undeclared_use; 1614 diagnostic_suggest = diag::err_undeclared_use_suggest; 1615 } 1616 1617 // If the original lookup was an unqualified lookup, fake an 1618 // unqualified lookup. This is useful when (for example) the 1619 // original lookup would not have found something because it was a 1620 // dependent name. 1621 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1622 ? CurContext : 0; 1623 while (DC) { 1624 if (isa<CXXRecordDecl>(DC)) { 1625 LookupQualifiedName(R, DC); 1626 1627 if (!R.empty()) { 1628 // Don't give errors about ambiguities in this lookup. 1629 R.suppressDiagnostics(); 1630 1631 // During a default argument instantiation the CurContext points 1632 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1633 // function parameter list, hence add an explicit check. 1634 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1635 ActiveTemplateInstantiations.back().Kind == 1636 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1637 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1638 bool isInstance = CurMethod && 1639 CurMethod->isInstance() && 1640 DC == CurMethod->getParent() && !isDefaultArgument; 1641 1642 1643 // Give a code modification hint to insert 'this->'. 1644 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1645 // Actually quite difficult! 1646 if (getLangOpts().MicrosoftMode) 1647 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1648 if (isInstance) { 1649 Diag(R.getNameLoc(), diagnostic) << Name 1650 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1651 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1652 CallsUndergoingInstantiation.back()->getCallee()); 1653 1654 CXXMethodDecl *DepMethod; 1655 if (CurMethod->isDependentContext()) 1656 DepMethod = CurMethod; 1657 else if (CurMethod->getTemplatedKind() == 1658 FunctionDecl::TK_FunctionTemplateSpecialization) 1659 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1660 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1661 else 1662 DepMethod = cast<CXXMethodDecl>( 1663 CurMethod->getInstantiatedFromMemberFunction()); 1664 assert(DepMethod && "No template pattern found"); 1665 1666 QualType DepThisType = DepMethod->getThisType(Context); 1667 CheckCXXThisCapture(R.getNameLoc()); 1668 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1669 R.getNameLoc(), DepThisType, false); 1670 TemplateArgumentListInfo TList; 1671 if (ULE->hasExplicitTemplateArgs()) 1672 ULE->copyTemplateArgumentsInto(TList); 1673 1674 CXXScopeSpec SS; 1675 SS.Adopt(ULE->getQualifierLoc()); 1676 CXXDependentScopeMemberExpr *DepExpr = 1677 CXXDependentScopeMemberExpr::Create( 1678 Context, DepThis, DepThisType, true, SourceLocation(), 1679 SS.getWithLocInContext(Context), 1680 ULE->getTemplateKeywordLoc(), 0, 1681 R.getLookupNameInfo(), 1682 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1683 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1684 } else { 1685 Diag(R.getNameLoc(), diagnostic) << Name; 1686 } 1687 1688 // Do we really want to note all of these? 1689 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1690 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1691 1692 // Return true if we are inside a default argument instantiation 1693 // and the found name refers to an instance member function, otherwise 1694 // the function calling DiagnoseEmptyLookup will try to create an 1695 // implicit member call and this is wrong for default argument. 1696 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1697 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1698 return true; 1699 } 1700 1701 // Tell the callee to try to recover. 1702 return false; 1703 } 1704 1705 R.clear(); 1706 } 1707 1708 // In Microsoft mode, if we are performing lookup from within a friend 1709 // function definition declared at class scope then we must set 1710 // DC to the lexical parent to be able to search into the parent 1711 // class. 1712 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1713 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1714 DC->getLexicalParent()->isRecord()) 1715 DC = DC->getLexicalParent(); 1716 else 1717 DC = DC->getParent(); 1718 } 1719 1720 // We didn't find anything, so try to correct for a typo. 1721 TypoCorrection Corrected; 1722 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1723 S, &SS, CCC))) { 1724 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1725 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1726 R.setLookupName(Corrected.getCorrection()); 1727 1728 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1729 if (Corrected.isOverloaded()) { 1730 OverloadCandidateSet OCS(R.getNameLoc()); 1731 OverloadCandidateSet::iterator Best; 1732 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1733 CDEnd = Corrected.end(); 1734 CD != CDEnd; ++CD) { 1735 if (FunctionTemplateDecl *FTD = 1736 dyn_cast<FunctionTemplateDecl>(*CD)) 1737 AddTemplateOverloadCandidate( 1738 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1739 Args, OCS); 1740 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1741 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1742 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1743 Args, OCS); 1744 } 1745 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1746 case OR_Success: 1747 ND = Best->Function; 1748 break; 1749 default: 1750 break; 1751 } 1752 } 1753 R.addDecl(ND); 1754 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1755 if (SS.isEmpty()) 1756 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1757 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1758 else 1759 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1760 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1761 << SS.getRange() 1762 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 1763 CorrectedStr); 1764 1765 unsigned diag = isa<ImplicitParamDecl>(ND) 1766 ? diag::note_implicit_param_decl 1767 : diag::note_previous_decl; 1768 1769 Diag(ND->getLocation(), diag) 1770 << CorrectedQuotedStr; 1771 1772 // Tell the callee to try to recover. 1773 return false; 1774 } 1775 1776 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1777 // FIXME: If we ended up with a typo for a type name or 1778 // Objective-C class name, we're in trouble because the parser 1779 // is in the wrong place to recover. Suggest the typo 1780 // correction, but don't make it a fix-it since we're not going 1781 // to recover well anyway. 1782 if (SS.isEmpty()) 1783 Diag(R.getNameLoc(), diagnostic_suggest) 1784 << Name << CorrectedQuotedStr; 1785 else 1786 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1787 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1788 << SS.getRange(); 1789 1790 // Don't try to recover; it won't work. 1791 return true; 1792 } 1793 } else { 1794 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1795 // because we aren't able to recover. 1796 if (SS.isEmpty()) 1797 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1798 else 1799 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1800 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1801 << SS.getRange(); 1802 return true; 1803 } 1804 } 1805 R.clear(); 1806 1807 // Emit a special diagnostic for failed member lookups. 1808 // FIXME: computing the declaration context might fail here (?) 1809 if (!SS.isEmpty()) { 1810 Diag(R.getNameLoc(), diag::err_no_member) 1811 << Name << computeDeclContext(SS, false) 1812 << SS.getRange(); 1813 return true; 1814 } 1815 1816 // Give up, we can't recover. 1817 Diag(R.getNameLoc(), diagnostic) << Name; 1818 return true; 1819 } 1820 1821 ExprResult Sema::ActOnIdExpression(Scope *S, 1822 CXXScopeSpec &SS, 1823 SourceLocation TemplateKWLoc, 1824 UnqualifiedId &Id, 1825 bool HasTrailingLParen, 1826 bool IsAddressOfOperand, 1827 CorrectionCandidateCallback *CCC) { 1828 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1829 "cannot be direct & operand and have a trailing lparen"); 1830 1831 if (SS.isInvalid()) 1832 return ExprError(); 1833 1834 TemplateArgumentListInfo TemplateArgsBuffer; 1835 1836 // Decompose the UnqualifiedId into the following data. 1837 DeclarationNameInfo NameInfo; 1838 const TemplateArgumentListInfo *TemplateArgs; 1839 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1840 1841 DeclarationName Name = NameInfo.getName(); 1842 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1843 SourceLocation NameLoc = NameInfo.getLoc(); 1844 1845 // C++ [temp.dep.expr]p3: 1846 // An id-expression is type-dependent if it contains: 1847 // -- an identifier that was declared with a dependent type, 1848 // (note: handled after lookup) 1849 // -- a template-id that is dependent, 1850 // (note: handled in BuildTemplateIdExpr) 1851 // -- a conversion-function-id that specifies a dependent type, 1852 // -- a nested-name-specifier that contains a class-name that 1853 // names a dependent type. 1854 // Determine whether this is a member of an unknown specialization; 1855 // we need to handle these differently. 1856 bool DependentID = false; 1857 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1858 Name.getCXXNameType()->isDependentType()) { 1859 DependentID = true; 1860 } else if (SS.isSet()) { 1861 if (DeclContext *DC = computeDeclContext(SS, false)) { 1862 if (RequireCompleteDeclContext(SS, DC)) 1863 return ExprError(); 1864 } else { 1865 DependentID = true; 1866 } 1867 } 1868 1869 if (DependentID) 1870 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1871 IsAddressOfOperand, TemplateArgs); 1872 1873 // Perform the required lookup. 1874 LookupResult R(*this, NameInfo, 1875 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1876 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1877 if (TemplateArgs) { 1878 // Lookup the template name again to correctly establish the context in 1879 // which it was found. This is really unfortunate as we already did the 1880 // lookup to determine that it was a template name in the first place. If 1881 // this becomes a performance hit, we can work harder to preserve those 1882 // results until we get here but it's likely not worth it. 1883 bool MemberOfUnknownSpecialization; 1884 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1885 MemberOfUnknownSpecialization); 1886 1887 if (MemberOfUnknownSpecialization || 1888 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1889 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1890 IsAddressOfOperand, TemplateArgs); 1891 } else { 1892 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1893 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1894 1895 // If the result might be in a dependent base class, this is a dependent 1896 // id-expression. 1897 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1898 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1899 IsAddressOfOperand, TemplateArgs); 1900 1901 // If this reference is in an Objective-C method, then we need to do 1902 // some special Objective-C lookup, too. 1903 if (IvarLookupFollowUp) { 1904 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1905 if (E.isInvalid()) 1906 return ExprError(); 1907 1908 if (Expr *Ex = E.takeAs<Expr>()) 1909 return Owned(Ex); 1910 } 1911 } 1912 1913 if (R.isAmbiguous()) 1914 return ExprError(); 1915 1916 // Determine whether this name might be a candidate for 1917 // argument-dependent lookup. 1918 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1919 1920 if (R.empty() && !ADL) { 1921 // Otherwise, this could be an implicitly declared function reference (legal 1922 // in C90, extension in C99, forbidden in C++). 1923 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1924 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1925 if (D) R.addDecl(D); 1926 } 1927 1928 // If this name wasn't predeclared and if this is not a function 1929 // call, diagnose the problem. 1930 if (R.empty()) { 1931 // In Microsoft mode, if we are inside a template class member function 1932 // whose parent class has dependent base classes, and we can't resolve 1933 // an identifier, then assume the identifier is type dependent. The 1934 // goal is to postpone name lookup to instantiation time to be able to 1935 // search into the type dependent base classes. 1936 if (getLangOpts().MicrosoftMode) { 1937 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 1938 if (MD && MD->getParent()->hasAnyDependentBases()) 1939 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1940 IsAddressOfOperand, TemplateArgs); 1941 } 1942 1943 CorrectionCandidateCallback DefaultValidator; 1944 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 1945 return ExprError(); 1946 1947 assert(!R.empty() && 1948 "DiagnoseEmptyLookup returned false but added no results"); 1949 1950 // If we found an Objective-C instance variable, let 1951 // LookupInObjCMethod build the appropriate expression to 1952 // reference the ivar. 1953 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1954 R.clear(); 1955 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1956 // In a hopelessly buggy code, Objective-C instance variable 1957 // lookup fails and no expression will be built to reference it. 1958 if (!E.isInvalid() && !E.get()) 1959 return ExprError(); 1960 return E; 1961 } 1962 } 1963 } 1964 1965 // This is guaranteed from this point on. 1966 assert(!R.empty() || ADL); 1967 1968 // Check whether this might be a C++ implicit instance member access. 1969 // C++ [class.mfct.non-static]p3: 1970 // When an id-expression that is not part of a class member access 1971 // syntax and not used to form a pointer to member is used in the 1972 // body of a non-static member function of class X, if name lookup 1973 // resolves the name in the id-expression to a non-static non-type 1974 // member of some class C, the id-expression is transformed into a 1975 // class member access expression using (*this) as the 1976 // postfix-expression to the left of the . operator. 1977 // 1978 // But we don't actually need to do this for '&' operands if R 1979 // resolved to a function or overloaded function set, because the 1980 // expression is ill-formed if it actually works out to be a 1981 // non-static member function: 1982 // 1983 // C++ [expr.ref]p4: 1984 // Otherwise, if E1.E2 refers to a non-static member function. . . 1985 // [t]he expression can be used only as the left-hand operand of a 1986 // member function call. 1987 // 1988 // There are other safeguards against such uses, but it's important 1989 // to get this right here so that we don't end up making a 1990 // spuriously dependent expression if we're inside a dependent 1991 // instance method. 1992 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1993 bool MightBeImplicitMember; 1994 if (!IsAddressOfOperand) 1995 MightBeImplicitMember = true; 1996 else if (!SS.isEmpty()) 1997 MightBeImplicitMember = false; 1998 else if (R.isOverloadedResult()) 1999 MightBeImplicitMember = false; 2000 else if (R.isUnresolvableResult()) 2001 MightBeImplicitMember = true; 2002 else 2003 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2004 isa<IndirectFieldDecl>(R.getFoundDecl()); 2005 2006 if (MightBeImplicitMember) 2007 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2008 R, TemplateArgs); 2009 } 2010 2011 if (TemplateArgs || TemplateKWLoc.isValid()) 2012 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2013 2014 return BuildDeclarationNameExpr(SS, R, ADL); 2015 } 2016 2017 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2018 /// declaration name, generally during template instantiation. 2019 /// There's a large number of things which don't need to be done along 2020 /// this path. 2021 ExprResult 2022 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2023 const DeclarationNameInfo &NameInfo, 2024 bool IsAddressOfOperand) { 2025 DeclContext *DC = computeDeclContext(SS, false); 2026 if (!DC) 2027 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2028 NameInfo, /*TemplateArgs=*/0); 2029 2030 if (RequireCompleteDeclContext(SS, DC)) 2031 return ExprError(); 2032 2033 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2034 LookupQualifiedName(R, DC); 2035 2036 if (R.isAmbiguous()) 2037 return ExprError(); 2038 2039 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2040 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2041 NameInfo, /*TemplateArgs=*/0); 2042 2043 if (R.empty()) { 2044 Diag(NameInfo.getLoc(), diag::err_no_member) 2045 << NameInfo.getName() << DC << SS.getRange(); 2046 return ExprError(); 2047 } 2048 2049 // Defend against this resolving to an implicit member access. We usually 2050 // won't get here if this might be a legitimate a class member (we end up in 2051 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2052 // a pointer-to-member or in an unevaluated context in C++11. 2053 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2054 return BuildPossibleImplicitMemberExpr(SS, 2055 /*TemplateKWLoc=*/SourceLocation(), 2056 R, /*TemplateArgs=*/0); 2057 2058 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2059 } 2060 2061 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2062 /// detected that we're currently inside an ObjC method. Perform some 2063 /// additional lookup. 2064 /// 2065 /// Ideally, most of this would be done by lookup, but there's 2066 /// actually quite a lot of extra work involved. 2067 /// 2068 /// Returns a null sentinel to indicate trivial success. 2069 ExprResult 2070 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2071 IdentifierInfo *II, bool AllowBuiltinCreation) { 2072 SourceLocation Loc = Lookup.getNameLoc(); 2073 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2074 2075 // Check for error condition which is already reported. 2076 if (!CurMethod) 2077 return ExprError(); 2078 2079 // There are two cases to handle here. 1) scoped lookup could have failed, 2080 // in which case we should look for an ivar. 2) scoped lookup could have 2081 // found a decl, but that decl is outside the current instance method (i.e. 2082 // a global variable). In these two cases, we do a lookup for an ivar with 2083 // this name, if the lookup sucedes, we replace it our current decl. 2084 2085 // If we're in a class method, we don't normally want to look for 2086 // ivars. But if we don't find anything else, and there's an 2087 // ivar, that's an error. 2088 bool IsClassMethod = CurMethod->isClassMethod(); 2089 2090 bool LookForIvars; 2091 if (Lookup.empty()) 2092 LookForIvars = true; 2093 else if (IsClassMethod) 2094 LookForIvars = false; 2095 else 2096 LookForIvars = (Lookup.isSingleResult() && 2097 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2098 ObjCInterfaceDecl *IFace = 0; 2099 if (LookForIvars) { 2100 IFace = CurMethod->getClassInterface(); 2101 ObjCInterfaceDecl *ClassDeclared; 2102 ObjCIvarDecl *IV = 0; 2103 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2104 // Diagnose using an ivar in a class method. 2105 if (IsClassMethod) 2106 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2107 << IV->getDeclName()); 2108 2109 // If we're referencing an invalid decl, just return this as a silent 2110 // error node. The error diagnostic was already emitted on the decl. 2111 if (IV->isInvalidDecl()) 2112 return ExprError(); 2113 2114 // Check if referencing a field with __attribute__((deprecated)). 2115 if (DiagnoseUseOfDecl(IV, Loc)) 2116 return ExprError(); 2117 2118 // Diagnose the use of an ivar outside of the declaring class. 2119 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2120 !declaresSameEntity(ClassDeclared, IFace) && 2121 !getLangOpts().DebuggerSupport) 2122 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2123 2124 // FIXME: This should use a new expr for a direct reference, don't 2125 // turn this into Self->ivar, just return a BareIVarExpr or something. 2126 IdentifierInfo &II = Context.Idents.get("self"); 2127 UnqualifiedId SelfName; 2128 SelfName.setIdentifier(&II, SourceLocation()); 2129 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2130 CXXScopeSpec SelfScopeSpec; 2131 SourceLocation TemplateKWLoc; 2132 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2133 SelfName, false, false); 2134 if (SelfExpr.isInvalid()) 2135 return ExprError(); 2136 2137 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2138 if (SelfExpr.isInvalid()) 2139 return ExprError(); 2140 2141 MarkAnyDeclReferenced(Loc, IV, true); 2142 2143 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2144 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2145 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2146 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2147 2148 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2149 Loc, IV->getLocation(), 2150 SelfExpr.take(), 2151 true, true); 2152 2153 if (getLangOpts().ObjCAutoRefCount) { 2154 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2155 DiagnosticsEngine::Level Level = 2156 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2157 if (Level != DiagnosticsEngine::Ignored) 2158 getCurFunction()->recordUseOfWeak(Result); 2159 } 2160 if (CurContext->isClosure()) 2161 Diag(Loc, diag::warn_implicitly_retains_self) 2162 << FixItHint::CreateInsertion(Loc, "self->"); 2163 } 2164 2165 return Owned(Result); 2166 } 2167 } else if (CurMethod->isInstanceMethod()) { 2168 // We should warn if a local variable hides an ivar. 2169 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2170 ObjCInterfaceDecl *ClassDeclared; 2171 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2172 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2173 declaresSameEntity(IFace, ClassDeclared)) 2174 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2175 } 2176 } 2177 } else if (Lookup.isSingleResult() && 2178 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2179 // If accessing a stand-alone ivar in a class method, this is an error. 2180 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2181 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2182 << IV->getDeclName()); 2183 } 2184 2185 if (Lookup.empty() && II && AllowBuiltinCreation) { 2186 // FIXME. Consolidate this with similar code in LookupName. 2187 if (unsigned BuiltinID = II->getBuiltinID()) { 2188 if (!(getLangOpts().CPlusPlus && 2189 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2190 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2191 S, Lookup.isForRedeclaration(), 2192 Lookup.getNameLoc()); 2193 if (D) Lookup.addDecl(D); 2194 } 2195 } 2196 } 2197 // Sentinel value saying that we didn't do anything special. 2198 return Owned((Expr*) 0); 2199 } 2200 2201 /// \brief Cast a base object to a member's actual type. 2202 /// 2203 /// Logically this happens in three phases: 2204 /// 2205 /// * First we cast from the base type to the naming class. 2206 /// The naming class is the class into which we were looking 2207 /// when we found the member; it's the qualifier type if a 2208 /// qualifier was provided, and otherwise it's the base type. 2209 /// 2210 /// * Next we cast from the naming class to the declaring class. 2211 /// If the member we found was brought into a class's scope by 2212 /// a using declaration, this is that class; otherwise it's 2213 /// the class declaring the member. 2214 /// 2215 /// * Finally we cast from the declaring class to the "true" 2216 /// declaring class of the member. This conversion does not 2217 /// obey access control. 2218 ExprResult 2219 Sema::PerformObjectMemberConversion(Expr *From, 2220 NestedNameSpecifier *Qualifier, 2221 NamedDecl *FoundDecl, 2222 NamedDecl *Member) { 2223 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2224 if (!RD) 2225 return Owned(From); 2226 2227 QualType DestRecordType; 2228 QualType DestType; 2229 QualType FromRecordType; 2230 QualType FromType = From->getType(); 2231 bool PointerConversions = false; 2232 if (isa<FieldDecl>(Member)) { 2233 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2234 2235 if (FromType->getAs<PointerType>()) { 2236 DestType = Context.getPointerType(DestRecordType); 2237 FromRecordType = FromType->getPointeeType(); 2238 PointerConversions = true; 2239 } else { 2240 DestType = DestRecordType; 2241 FromRecordType = FromType; 2242 } 2243 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2244 if (Method->isStatic()) 2245 return Owned(From); 2246 2247 DestType = Method->getThisType(Context); 2248 DestRecordType = DestType->getPointeeType(); 2249 2250 if (FromType->getAs<PointerType>()) { 2251 FromRecordType = FromType->getPointeeType(); 2252 PointerConversions = true; 2253 } else { 2254 FromRecordType = FromType; 2255 DestType = DestRecordType; 2256 } 2257 } else { 2258 // No conversion necessary. 2259 return Owned(From); 2260 } 2261 2262 if (DestType->isDependentType() || FromType->isDependentType()) 2263 return Owned(From); 2264 2265 // If the unqualified types are the same, no conversion is necessary. 2266 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2267 return Owned(From); 2268 2269 SourceRange FromRange = From->getSourceRange(); 2270 SourceLocation FromLoc = FromRange.getBegin(); 2271 2272 ExprValueKind VK = From->getValueKind(); 2273 2274 // C++ [class.member.lookup]p8: 2275 // [...] Ambiguities can often be resolved by qualifying a name with its 2276 // class name. 2277 // 2278 // If the member was a qualified name and the qualified referred to a 2279 // specific base subobject type, we'll cast to that intermediate type 2280 // first and then to the object in which the member is declared. That allows 2281 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2282 // 2283 // class Base { public: int x; }; 2284 // class Derived1 : public Base { }; 2285 // class Derived2 : public Base { }; 2286 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2287 // 2288 // void VeryDerived::f() { 2289 // x = 17; // error: ambiguous base subobjects 2290 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2291 // } 2292 if (Qualifier) { 2293 QualType QType = QualType(Qualifier->getAsType(), 0); 2294 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 2295 assert(QType->isRecordType() && "lookup done with non-record type"); 2296 2297 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2298 2299 // In C++98, the qualifier type doesn't actually have to be a base 2300 // type of the object type, in which case we just ignore it. 2301 // Otherwise build the appropriate casts. 2302 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2303 CXXCastPath BasePath; 2304 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2305 FromLoc, FromRange, &BasePath)) 2306 return ExprError(); 2307 2308 if (PointerConversions) 2309 QType = Context.getPointerType(QType); 2310 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2311 VK, &BasePath).take(); 2312 2313 FromType = QType; 2314 FromRecordType = QRecordType; 2315 2316 // If the qualifier type was the same as the destination type, 2317 // we're done. 2318 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2319 return Owned(From); 2320 } 2321 } 2322 2323 bool IgnoreAccess = false; 2324 2325 // If we actually found the member through a using declaration, cast 2326 // down to the using declaration's type. 2327 // 2328 // Pointer equality is fine here because only one declaration of a 2329 // class ever has member declarations. 2330 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2331 assert(isa<UsingShadowDecl>(FoundDecl)); 2332 QualType URecordType = Context.getTypeDeclType( 2333 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2334 2335 // We only need to do this if the naming-class to declaring-class 2336 // conversion is non-trivial. 2337 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2338 assert(IsDerivedFrom(FromRecordType, URecordType)); 2339 CXXCastPath BasePath; 2340 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2341 FromLoc, FromRange, &BasePath)) 2342 return ExprError(); 2343 2344 QualType UType = URecordType; 2345 if (PointerConversions) 2346 UType = Context.getPointerType(UType); 2347 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2348 VK, &BasePath).take(); 2349 FromType = UType; 2350 FromRecordType = URecordType; 2351 } 2352 2353 // We don't do access control for the conversion from the 2354 // declaring class to the true declaring class. 2355 IgnoreAccess = true; 2356 } 2357 2358 CXXCastPath BasePath; 2359 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2360 FromLoc, FromRange, &BasePath, 2361 IgnoreAccess)) 2362 return ExprError(); 2363 2364 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2365 VK, &BasePath); 2366 } 2367 2368 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2369 const LookupResult &R, 2370 bool HasTrailingLParen) { 2371 // Only when used directly as the postfix-expression of a call. 2372 if (!HasTrailingLParen) 2373 return false; 2374 2375 // Never if a scope specifier was provided. 2376 if (SS.isSet()) 2377 return false; 2378 2379 // Only in C++ or ObjC++. 2380 if (!getLangOpts().CPlusPlus) 2381 return false; 2382 2383 // Turn off ADL when we find certain kinds of declarations during 2384 // normal lookup: 2385 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2386 NamedDecl *D = *I; 2387 2388 // C++0x [basic.lookup.argdep]p3: 2389 // -- a declaration of a class member 2390 // Since using decls preserve this property, we check this on the 2391 // original decl. 2392 if (D->isCXXClassMember()) 2393 return false; 2394 2395 // C++0x [basic.lookup.argdep]p3: 2396 // -- a block-scope function declaration that is not a 2397 // using-declaration 2398 // NOTE: we also trigger this for function templates (in fact, we 2399 // don't check the decl type at all, since all other decl types 2400 // turn off ADL anyway). 2401 if (isa<UsingShadowDecl>(D)) 2402 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2403 else if (D->getDeclContext()->isFunctionOrMethod()) 2404 return false; 2405 2406 // C++0x [basic.lookup.argdep]p3: 2407 // -- a declaration that is neither a function or a function 2408 // template 2409 // And also for builtin functions. 2410 if (isa<FunctionDecl>(D)) { 2411 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2412 2413 // But also builtin functions. 2414 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2415 return false; 2416 } else if (!isa<FunctionTemplateDecl>(D)) 2417 return false; 2418 } 2419 2420 return true; 2421 } 2422 2423 2424 /// Diagnoses obvious problems with the use of the given declaration 2425 /// as an expression. This is only actually called for lookups that 2426 /// were not overloaded, and it doesn't promise that the declaration 2427 /// will in fact be used. 2428 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2429 if (isa<TypedefNameDecl>(D)) { 2430 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2431 return true; 2432 } 2433 2434 if (isa<ObjCInterfaceDecl>(D)) { 2435 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2436 return true; 2437 } 2438 2439 if (isa<NamespaceDecl>(D)) { 2440 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2441 return true; 2442 } 2443 2444 return false; 2445 } 2446 2447 ExprResult 2448 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2449 LookupResult &R, 2450 bool NeedsADL) { 2451 // If this is a single, fully-resolved result and we don't need ADL, 2452 // just build an ordinary singleton decl ref. 2453 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2454 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2455 R.getRepresentativeDecl()); 2456 2457 // We only need to check the declaration if there's exactly one 2458 // result, because in the overloaded case the results can only be 2459 // functions and function templates. 2460 if (R.isSingleResult() && 2461 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2462 return ExprError(); 2463 2464 // Otherwise, just build an unresolved lookup expression. Suppress 2465 // any lookup-related diagnostics; we'll hash these out later, when 2466 // we've picked a target. 2467 R.suppressDiagnostics(); 2468 2469 UnresolvedLookupExpr *ULE 2470 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2471 SS.getWithLocInContext(Context), 2472 R.getLookupNameInfo(), 2473 NeedsADL, R.isOverloadedResult(), 2474 R.begin(), R.end()); 2475 2476 return Owned(ULE); 2477 } 2478 2479 /// \brief Complete semantic analysis for a reference to the given declaration. 2480 ExprResult 2481 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2482 const DeclarationNameInfo &NameInfo, 2483 NamedDecl *D, NamedDecl *FoundD) { 2484 assert(D && "Cannot refer to a NULL declaration"); 2485 assert(!isa<FunctionTemplateDecl>(D) && 2486 "Cannot refer unambiguously to a function template"); 2487 2488 SourceLocation Loc = NameInfo.getLoc(); 2489 if (CheckDeclInExpr(*this, Loc, D)) 2490 return ExprError(); 2491 2492 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2493 // Specifically diagnose references to class templates that are missing 2494 // a template argument list. 2495 Diag(Loc, diag::err_template_decl_ref) 2496 << Template << SS.getRange(); 2497 Diag(Template->getLocation(), diag::note_template_decl_here); 2498 return ExprError(); 2499 } 2500 2501 // Make sure that we're referring to a value. 2502 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2503 if (!VD) { 2504 Diag(Loc, diag::err_ref_non_value) 2505 << D << SS.getRange(); 2506 Diag(D->getLocation(), diag::note_declared_at); 2507 return ExprError(); 2508 } 2509 2510 // Check whether this declaration can be used. Note that we suppress 2511 // this check when we're going to perform argument-dependent lookup 2512 // on this function name, because this might not be the function 2513 // that overload resolution actually selects. 2514 if (DiagnoseUseOfDecl(VD, Loc)) 2515 return ExprError(); 2516 2517 // Only create DeclRefExpr's for valid Decl's. 2518 if (VD->isInvalidDecl()) 2519 return ExprError(); 2520 2521 // Handle members of anonymous structs and unions. If we got here, 2522 // and the reference is to a class member indirect field, then this 2523 // must be the subject of a pointer-to-member expression. 2524 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2525 if (!indirectField->isCXXClassMember()) 2526 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2527 indirectField); 2528 2529 { 2530 QualType type = VD->getType(); 2531 ExprValueKind valueKind = VK_RValue; 2532 2533 switch (D->getKind()) { 2534 // Ignore all the non-ValueDecl kinds. 2535 #define ABSTRACT_DECL(kind) 2536 #define VALUE(type, base) 2537 #define DECL(type, base) \ 2538 case Decl::type: 2539 #include "clang/AST/DeclNodes.inc" 2540 llvm_unreachable("invalid value decl kind"); 2541 2542 // These shouldn't make it here. 2543 case Decl::ObjCAtDefsField: 2544 case Decl::ObjCIvar: 2545 llvm_unreachable("forming non-member reference to ivar?"); 2546 2547 // Enum constants are always r-values and never references. 2548 // Unresolved using declarations are dependent. 2549 case Decl::EnumConstant: 2550 case Decl::UnresolvedUsingValue: 2551 valueKind = VK_RValue; 2552 break; 2553 2554 // Fields and indirect fields that got here must be for 2555 // pointer-to-member expressions; we just call them l-values for 2556 // internal consistency, because this subexpression doesn't really 2557 // exist in the high-level semantics. 2558 case Decl::Field: 2559 case Decl::IndirectField: 2560 assert(getLangOpts().CPlusPlus && 2561 "building reference to field in C?"); 2562 2563 // These can't have reference type in well-formed programs, but 2564 // for internal consistency we do this anyway. 2565 type = type.getNonReferenceType(); 2566 valueKind = VK_LValue; 2567 break; 2568 2569 // Non-type template parameters are either l-values or r-values 2570 // depending on the type. 2571 case Decl::NonTypeTemplateParm: { 2572 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2573 type = reftype->getPointeeType(); 2574 valueKind = VK_LValue; // even if the parameter is an r-value reference 2575 break; 2576 } 2577 2578 // For non-references, we need to strip qualifiers just in case 2579 // the template parameter was declared as 'const int' or whatever. 2580 valueKind = VK_RValue; 2581 type = type.getUnqualifiedType(); 2582 break; 2583 } 2584 2585 case Decl::Var: 2586 // In C, "extern void blah;" is valid and is an r-value. 2587 if (!getLangOpts().CPlusPlus && 2588 !type.hasQualifiers() && 2589 type->isVoidType()) { 2590 valueKind = VK_RValue; 2591 break; 2592 } 2593 // fallthrough 2594 2595 case Decl::ImplicitParam: 2596 case Decl::ParmVar: { 2597 // These are always l-values. 2598 valueKind = VK_LValue; 2599 type = type.getNonReferenceType(); 2600 2601 // FIXME: Does the addition of const really only apply in 2602 // potentially-evaluated contexts? Since the variable isn't actually 2603 // captured in an unevaluated context, it seems that the answer is no. 2604 if (!isUnevaluatedContext()) { 2605 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2606 if (!CapturedType.isNull()) 2607 type = CapturedType; 2608 } 2609 2610 break; 2611 } 2612 2613 case Decl::Function: { 2614 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2615 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2616 type = Context.BuiltinFnTy; 2617 valueKind = VK_RValue; 2618 break; 2619 } 2620 } 2621 2622 const FunctionType *fty = type->castAs<FunctionType>(); 2623 2624 // If we're referring to a function with an __unknown_anytype 2625 // result type, make the entire expression __unknown_anytype. 2626 if (fty->getResultType() == Context.UnknownAnyTy) { 2627 type = Context.UnknownAnyTy; 2628 valueKind = VK_RValue; 2629 break; 2630 } 2631 2632 // Functions are l-values in C++. 2633 if (getLangOpts().CPlusPlus) { 2634 valueKind = VK_LValue; 2635 break; 2636 } 2637 2638 // C99 DR 316 says that, if a function type comes from a 2639 // function definition (without a prototype), that type is only 2640 // used for checking compatibility. Therefore, when referencing 2641 // the function, we pretend that we don't have the full function 2642 // type. 2643 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2644 isa<FunctionProtoType>(fty)) 2645 type = Context.getFunctionNoProtoType(fty->getResultType(), 2646 fty->getExtInfo()); 2647 2648 // Functions are r-values in C. 2649 valueKind = VK_RValue; 2650 break; 2651 } 2652 2653 case Decl::MSProperty: 2654 valueKind = VK_LValue; 2655 break; 2656 2657 case Decl::CXXMethod: 2658 // If we're referring to a method with an __unknown_anytype 2659 // result type, make the entire expression __unknown_anytype. 2660 // This should only be possible with a type written directly. 2661 if (const FunctionProtoType *proto 2662 = dyn_cast<FunctionProtoType>(VD->getType())) 2663 if (proto->getResultType() == Context.UnknownAnyTy) { 2664 type = Context.UnknownAnyTy; 2665 valueKind = VK_RValue; 2666 break; 2667 } 2668 2669 // C++ methods are l-values if static, r-values if non-static. 2670 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2671 valueKind = VK_LValue; 2672 break; 2673 } 2674 // fallthrough 2675 2676 case Decl::CXXConversion: 2677 case Decl::CXXDestructor: 2678 case Decl::CXXConstructor: 2679 valueKind = VK_RValue; 2680 break; 2681 } 2682 2683 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD); 2684 } 2685 } 2686 2687 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2688 PredefinedExpr::IdentType IT; 2689 2690 switch (Kind) { 2691 default: llvm_unreachable("Unknown simple primary expr!"); 2692 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2693 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2694 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2695 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2696 } 2697 2698 // Pre-defined identifiers are of type char[x], where x is the length of the 2699 // string. 2700 2701 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2702 // Blocks and lambdas can occur at global scope. Don't emit a warning. 2703 if (!currentDecl) { 2704 if (const BlockScopeInfo *BSI = getCurBlock()) 2705 currentDecl = BSI->TheDecl; 2706 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2707 currentDecl = LSI->CallOperator; 2708 } 2709 2710 if (!currentDecl) { 2711 Diag(Loc, diag::ext_predef_outside_function); 2712 currentDecl = Context.getTranslationUnitDecl(); 2713 } 2714 2715 QualType ResTy; 2716 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2717 ResTy = Context.DependentTy; 2718 } else { 2719 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2720 2721 llvm::APInt LengthI(32, Length + 1); 2722 if (IT == PredefinedExpr::LFunction) 2723 ResTy = Context.WCharTy.withConst(); 2724 else 2725 ResTy = Context.CharTy.withConst(); 2726 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2727 } 2728 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2729 } 2730 2731 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2732 SmallString<16> CharBuffer; 2733 bool Invalid = false; 2734 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2735 if (Invalid) 2736 return ExprError(); 2737 2738 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2739 PP, Tok.getKind()); 2740 if (Literal.hadError()) 2741 return ExprError(); 2742 2743 QualType Ty; 2744 if (Literal.isWide()) 2745 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++. 2746 else if (Literal.isUTF16()) 2747 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2748 else if (Literal.isUTF32()) 2749 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2750 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2751 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2752 else 2753 Ty = Context.CharTy; // 'x' -> char in C++ 2754 2755 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2756 if (Literal.isWide()) 2757 Kind = CharacterLiteral::Wide; 2758 else if (Literal.isUTF16()) 2759 Kind = CharacterLiteral::UTF16; 2760 else if (Literal.isUTF32()) 2761 Kind = CharacterLiteral::UTF32; 2762 2763 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2764 Tok.getLocation()); 2765 2766 if (Literal.getUDSuffix().empty()) 2767 return Owned(Lit); 2768 2769 // We're building a user-defined literal. 2770 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2771 SourceLocation UDSuffixLoc = 2772 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2773 2774 // Make sure we're allowed user-defined literals here. 2775 if (!UDLScope) 2776 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2777 2778 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2779 // operator "" X (ch) 2780 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2781 Lit, Tok.getLocation()); 2782 } 2783 2784 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2785 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2786 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2787 Context.IntTy, Loc)); 2788 } 2789 2790 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2791 QualType Ty, SourceLocation Loc) { 2792 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2793 2794 using llvm::APFloat; 2795 APFloat Val(Format); 2796 2797 APFloat::opStatus result = Literal.GetFloatValue(Val); 2798 2799 // Overflow is always an error, but underflow is only an error if 2800 // we underflowed to zero (APFloat reports denormals as underflow). 2801 if ((result & APFloat::opOverflow) || 2802 ((result & APFloat::opUnderflow) && Val.isZero())) { 2803 unsigned diagnostic; 2804 SmallString<20> buffer; 2805 if (result & APFloat::opOverflow) { 2806 diagnostic = diag::warn_float_overflow; 2807 APFloat::getLargest(Format).toString(buffer); 2808 } else { 2809 diagnostic = diag::warn_float_underflow; 2810 APFloat::getSmallest(Format).toString(buffer); 2811 } 2812 2813 S.Diag(Loc, diagnostic) 2814 << Ty 2815 << StringRef(buffer.data(), buffer.size()); 2816 } 2817 2818 bool isExact = (result == APFloat::opOK); 2819 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2820 } 2821 2822 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2823 // Fast path for a single digit (which is quite common). A single digit 2824 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2825 if (Tok.getLength() == 1) { 2826 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2827 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2828 } 2829 2830 SmallString<128> SpellingBuffer; 2831 // NumericLiteralParser wants to overread by one character. Add padding to 2832 // the buffer in case the token is copied to the buffer. If getSpelling() 2833 // returns a StringRef to the memory buffer, it should have a null char at 2834 // the EOF, so it is also safe. 2835 SpellingBuffer.resize(Tok.getLength() + 1); 2836 2837 // Get the spelling of the token, which eliminates trigraphs, etc. 2838 bool Invalid = false; 2839 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2840 if (Invalid) 2841 return ExprError(); 2842 2843 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2844 if (Literal.hadError) 2845 return ExprError(); 2846 2847 if (Literal.hasUDSuffix()) { 2848 // We're building a user-defined literal. 2849 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2850 SourceLocation UDSuffixLoc = 2851 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2852 2853 // Make sure we're allowed user-defined literals here. 2854 if (!UDLScope) 2855 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2856 2857 QualType CookedTy; 2858 if (Literal.isFloatingLiteral()) { 2859 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2860 // long double, the literal is treated as a call of the form 2861 // operator "" X (f L) 2862 CookedTy = Context.LongDoubleTy; 2863 } else { 2864 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2865 // unsigned long long, the literal is treated as a call of the form 2866 // operator "" X (n ULL) 2867 CookedTy = Context.UnsignedLongLongTy; 2868 } 2869 2870 DeclarationName OpName = 2871 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2872 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2873 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2874 2875 // Perform literal operator lookup to determine if we're building a raw 2876 // literal or a cooked one. 2877 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2878 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 2879 /*AllowRawAndTemplate*/true)) { 2880 case LOLR_Error: 2881 return ExprError(); 2882 2883 case LOLR_Cooked: { 2884 Expr *Lit; 2885 if (Literal.isFloatingLiteral()) { 2886 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2887 } else { 2888 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2889 if (Literal.GetIntegerValue(ResultVal)) 2890 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2891 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2892 Tok.getLocation()); 2893 } 2894 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, 2895 Tok.getLocation()); 2896 } 2897 2898 case LOLR_Raw: { 2899 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2900 // literal is treated as a call of the form 2901 // operator "" X ("n") 2902 SourceLocation TokLoc = Tok.getLocation(); 2903 unsigned Length = Literal.getUDSuffixOffset(); 2904 QualType StrTy = Context.getConstantArrayType( 2905 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 2906 ArrayType::Normal, 0); 2907 Expr *Lit = StringLiteral::Create( 2908 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 2909 /*Pascal*/false, StrTy, &TokLoc, 1); 2910 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 2911 } 2912 2913 case LOLR_Template: 2914 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2915 // template), L is treated as a call fo the form 2916 // operator "" X <'c1', 'c2', ... 'ck'>() 2917 // where n is the source character sequence c1 c2 ... ck. 2918 TemplateArgumentListInfo ExplicitArgs; 2919 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2920 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2921 llvm::APSInt Value(CharBits, CharIsUnsigned); 2922 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2923 Value = TokSpelling[I]; 2924 TemplateArgument Arg(Context, Value, Context.CharTy); 2925 TemplateArgumentLocInfo ArgInfo; 2926 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2927 } 2928 return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(), 2929 &ExplicitArgs); 2930 } 2931 2932 llvm_unreachable("unexpected literal operator lookup result"); 2933 } 2934 2935 Expr *Res; 2936 2937 if (Literal.isFloatingLiteral()) { 2938 QualType Ty; 2939 if (Literal.isFloat) 2940 Ty = Context.FloatTy; 2941 else if (!Literal.isLong) 2942 Ty = Context.DoubleTy; 2943 else 2944 Ty = Context.LongDoubleTy; 2945 2946 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 2947 2948 if (Ty == Context.DoubleTy) { 2949 if (getLangOpts().SinglePrecisionConstants) { 2950 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2951 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2952 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2953 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2954 } 2955 } 2956 } else if (!Literal.isIntegerLiteral()) { 2957 return ExprError(); 2958 } else { 2959 QualType Ty; 2960 2961 // 'long long' is a C99 or C++11 feature. 2962 if (!getLangOpts().C99 && Literal.isLongLong) { 2963 if (getLangOpts().CPlusPlus) 2964 Diag(Tok.getLocation(), 2965 getLangOpts().CPlusPlus11 ? 2966 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 2967 else 2968 Diag(Tok.getLocation(), diag::ext_c99_longlong); 2969 } 2970 2971 // Get the value in the widest-possible width. 2972 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 2973 // The microsoft literal suffix extensions support 128-bit literals, which 2974 // may be wider than [u]intmax_t. 2975 // FIXME: Actually, they don't. We seem to have accidentally invented the 2976 // i128 suffix. 2977 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 2978 PP.getTargetInfo().hasInt128Type()) 2979 MaxWidth = 128; 2980 llvm::APInt ResultVal(MaxWidth, 0); 2981 2982 if (Literal.GetIntegerValue(ResultVal)) { 2983 // If this value didn't fit into uintmax_t, warn and force to ull. 2984 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2985 Ty = Context.UnsignedLongLongTy; 2986 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2987 "long long is not intmax_t?"); 2988 } else { 2989 // If this value fits into a ULL, try to figure out what else it fits into 2990 // according to the rules of C99 6.4.4.1p5. 2991 2992 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2993 // be an unsigned int. 2994 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2995 2996 // Check from smallest to largest, picking the smallest type we can. 2997 unsigned Width = 0; 2998 if (!Literal.isLong && !Literal.isLongLong) { 2999 // Are int/unsigned possibilities? 3000 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3001 3002 // Does it fit in a unsigned int? 3003 if (ResultVal.isIntN(IntSize)) { 3004 // Does it fit in a signed int? 3005 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3006 Ty = Context.IntTy; 3007 else if (AllowUnsigned) 3008 Ty = Context.UnsignedIntTy; 3009 Width = IntSize; 3010 } 3011 } 3012 3013 // Are long/unsigned long possibilities? 3014 if (Ty.isNull() && !Literal.isLongLong) { 3015 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3016 3017 // Does it fit in a unsigned long? 3018 if (ResultVal.isIntN(LongSize)) { 3019 // Does it fit in a signed long? 3020 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3021 Ty = Context.LongTy; 3022 else if (AllowUnsigned) 3023 Ty = Context.UnsignedLongTy; 3024 Width = LongSize; 3025 } 3026 } 3027 3028 // Check long long if needed. 3029 if (Ty.isNull()) { 3030 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3031 3032 // Does it fit in a unsigned long long? 3033 if (ResultVal.isIntN(LongLongSize)) { 3034 // Does it fit in a signed long long? 3035 // To be compatible with MSVC, hex integer literals ending with the 3036 // LL or i64 suffix are always signed in Microsoft mode. 3037 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3038 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3039 Ty = Context.LongLongTy; 3040 else if (AllowUnsigned) 3041 Ty = Context.UnsignedLongLongTy; 3042 Width = LongLongSize; 3043 } 3044 } 3045 3046 // If it doesn't fit in unsigned long long, and we're using Microsoft 3047 // extensions, then its a 128-bit integer literal. 3048 if (Ty.isNull() && Literal.isMicrosoftInteger && 3049 PP.getTargetInfo().hasInt128Type()) { 3050 if (Literal.isUnsigned) 3051 Ty = Context.UnsignedInt128Ty; 3052 else 3053 Ty = Context.Int128Ty; 3054 Width = 128; 3055 } 3056 3057 // If we still couldn't decide a type, we probably have something that 3058 // does not fit in a signed long long, but has no U suffix. 3059 if (Ty.isNull()) { 3060 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3061 Ty = Context.UnsignedLongLongTy; 3062 Width = Context.getTargetInfo().getLongLongWidth(); 3063 } 3064 3065 if (ResultVal.getBitWidth() != Width) 3066 ResultVal = ResultVal.trunc(Width); 3067 } 3068 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3069 } 3070 3071 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3072 if (Literal.isImaginary) 3073 Res = new (Context) ImaginaryLiteral(Res, 3074 Context.getComplexType(Res->getType())); 3075 3076 return Owned(Res); 3077 } 3078 3079 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3080 assert((E != 0) && "ActOnParenExpr() missing expr"); 3081 return Owned(new (Context) ParenExpr(L, R, E)); 3082 } 3083 3084 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3085 SourceLocation Loc, 3086 SourceRange ArgRange) { 3087 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3088 // scalar or vector data type argument..." 3089 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3090 // type (C99 6.2.5p18) or void. 3091 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3092 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3093 << T << ArgRange; 3094 return true; 3095 } 3096 3097 assert((T->isVoidType() || !T->isIncompleteType()) && 3098 "Scalar types should always be complete"); 3099 return false; 3100 } 3101 3102 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3103 SourceLocation Loc, 3104 SourceRange ArgRange, 3105 UnaryExprOrTypeTrait TraitKind) { 3106 // C99 6.5.3.4p1: 3107 if (T->isFunctionType() && 3108 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3109 // sizeof(function)/alignof(function) is allowed as an extension. 3110 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3111 << TraitKind << ArgRange; 3112 return false; 3113 } 3114 3115 // Allow sizeof(void)/alignof(void) as an extension. 3116 if (T->isVoidType()) { 3117 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange; 3118 return false; 3119 } 3120 3121 return true; 3122 } 3123 3124 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3125 SourceLocation Loc, 3126 SourceRange ArgRange, 3127 UnaryExprOrTypeTrait TraitKind) { 3128 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3129 // runtime doesn't allow it. 3130 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3131 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3132 << T << (TraitKind == UETT_SizeOf) 3133 << ArgRange; 3134 return true; 3135 } 3136 3137 return false; 3138 } 3139 3140 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3141 /// pointer type is equal to T) and emit a warning if it is. 3142 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3143 Expr *E) { 3144 // Don't warn if the operation changed the type. 3145 if (T != E->getType()) 3146 return; 3147 3148 // Now look for array decays. 3149 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3150 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3151 return; 3152 3153 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3154 << ICE->getType() 3155 << ICE->getSubExpr()->getType(); 3156 } 3157 3158 /// \brief Check the constrains on expression operands to unary type expression 3159 /// and type traits. 3160 /// 3161 /// Completes any types necessary and validates the constraints on the operand 3162 /// expression. The logic mostly mirrors the type-based overload, but may modify 3163 /// the expression as it completes the type for that expression through template 3164 /// instantiation, etc. 3165 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3166 UnaryExprOrTypeTrait ExprKind) { 3167 QualType ExprTy = E->getType(); 3168 assert(!ExprTy->isReferenceType()); 3169 3170 if (ExprKind == UETT_VecStep) 3171 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3172 E->getSourceRange()); 3173 3174 // Whitelist some types as extensions 3175 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3176 E->getSourceRange(), ExprKind)) 3177 return false; 3178 3179 if (RequireCompleteExprType(E, 3180 diag::err_sizeof_alignof_incomplete_type, 3181 ExprKind, E->getSourceRange())) 3182 return true; 3183 3184 // Completing the expression's type may have changed it. 3185 ExprTy = E->getType(); 3186 assert(!ExprTy->isReferenceType()); 3187 3188 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3189 E->getSourceRange(), ExprKind)) 3190 return true; 3191 3192 if (ExprKind == UETT_SizeOf) { 3193 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3194 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3195 QualType OType = PVD->getOriginalType(); 3196 QualType Type = PVD->getType(); 3197 if (Type->isPointerType() && OType->isArrayType()) { 3198 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3199 << Type << OType; 3200 Diag(PVD->getLocation(), diag::note_declared_at); 3201 } 3202 } 3203 } 3204 3205 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3206 // decays into a pointer and returns an unintended result. This is most 3207 // likely a typo for "sizeof(array) op x". 3208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3209 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3210 BO->getLHS()); 3211 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3212 BO->getRHS()); 3213 } 3214 } 3215 3216 return false; 3217 } 3218 3219 /// \brief Check the constraints on operands to unary expression and type 3220 /// traits. 3221 /// 3222 /// This will complete any types necessary, and validate the various constraints 3223 /// on those operands. 3224 /// 3225 /// The UsualUnaryConversions() function is *not* called by this routine. 3226 /// C99 6.3.2.1p[2-4] all state: 3227 /// Except when it is the operand of the sizeof operator ... 3228 /// 3229 /// C++ [expr.sizeof]p4 3230 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3231 /// standard conversions are not applied to the operand of sizeof. 3232 /// 3233 /// This policy is followed for all of the unary trait expressions. 3234 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3235 SourceLocation OpLoc, 3236 SourceRange ExprRange, 3237 UnaryExprOrTypeTrait ExprKind) { 3238 if (ExprType->isDependentType()) 3239 return false; 3240 3241 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3242 // the result is the size of the referenced type." 3243 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3244 // result shall be the alignment of the referenced type." 3245 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3246 ExprType = Ref->getPointeeType(); 3247 3248 if (ExprKind == UETT_VecStep) 3249 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3250 3251 // Whitelist some types as extensions 3252 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3253 ExprKind)) 3254 return false; 3255 3256 if (RequireCompleteType(OpLoc, ExprType, 3257 diag::err_sizeof_alignof_incomplete_type, 3258 ExprKind, ExprRange)) 3259 return true; 3260 3261 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3262 ExprKind)) 3263 return true; 3264 3265 return false; 3266 } 3267 3268 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3269 E = E->IgnoreParens(); 3270 3271 // Cannot know anything else if the expression is dependent. 3272 if (E->isTypeDependent()) 3273 return false; 3274 3275 if (E->getObjectKind() == OK_BitField) { 3276 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3277 << 1 << E->getSourceRange(); 3278 return true; 3279 } 3280 3281 ValueDecl *D = 0; 3282 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3283 D = DRE->getDecl(); 3284 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3285 D = ME->getMemberDecl(); 3286 } 3287 3288 // If it's a field, require the containing struct to have a 3289 // complete definition so that we can compute the layout. 3290 // 3291 // This requires a very particular set of circumstances. For a 3292 // field to be contained within an incomplete type, we must in the 3293 // process of parsing that type. To have an expression refer to a 3294 // field, it must be an id-expression or a member-expression, but 3295 // the latter are always ill-formed when the base type is 3296 // incomplete, including only being partially complete. An 3297 // id-expression can never refer to a field in C because fields 3298 // are not in the ordinary namespace. In C++, an id-expression 3299 // can implicitly be a member access, but only if there's an 3300 // implicit 'this' value, and all such contexts are subject to 3301 // delayed parsing --- except for trailing return types in C++11. 3302 // And if an id-expression referring to a field occurs in a 3303 // context that lacks a 'this' value, it's ill-formed --- except, 3304 // agian, in C++11, where such references are allowed in an 3305 // unevaluated context. So C++11 introduces some new complexity. 3306 // 3307 // For the record, since __alignof__ on expressions is a GCC 3308 // extension, GCC seems to permit this but always gives the 3309 // nonsensical answer 0. 3310 // 3311 // We don't really need the layout here --- we could instead just 3312 // directly check for all the appropriate alignment-lowing 3313 // attributes --- but that would require duplicating a lot of 3314 // logic that just isn't worth duplicating for such a marginal 3315 // use-case. 3316 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3317 // Fast path this check, since we at least know the record has a 3318 // definition if we can find a member of it. 3319 if (!FD->getParent()->isCompleteDefinition()) { 3320 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3321 << E->getSourceRange(); 3322 return true; 3323 } 3324 3325 // Otherwise, if it's a field, and the field doesn't have 3326 // reference type, then it must have a complete type (or be a 3327 // flexible array member, which we explicitly want to 3328 // white-list anyway), which makes the following checks trivial. 3329 if (!FD->getType()->isReferenceType()) 3330 return false; 3331 } 3332 3333 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3334 } 3335 3336 bool Sema::CheckVecStepExpr(Expr *E) { 3337 E = E->IgnoreParens(); 3338 3339 // Cannot know anything else if the expression is dependent. 3340 if (E->isTypeDependent()) 3341 return false; 3342 3343 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3344 } 3345 3346 /// \brief Build a sizeof or alignof expression given a type operand. 3347 ExprResult 3348 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3349 SourceLocation OpLoc, 3350 UnaryExprOrTypeTrait ExprKind, 3351 SourceRange R) { 3352 if (!TInfo) 3353 return ExprError(); 3354 3355 QualType T = TInfo->getType(); 3356 3357 if (!T->isDependentType() && 3358 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3359 return ExprError(); 3360 3361 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3362 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3363 Context.getSizeType(), 3364 OpLoc, R.getEnd())); 3365 } 3366 3367 /// \brief Build a sizeof or alignof expression given an expression 3368 /// operand. 3369 ExprResult 3370 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3371 UnaryExprOrTypeTrait ExprKind) { 3372 ExprResult PE = CheckPlaceholderExpr(E); 3373 if (PE.isInvalid()) 3374 return ExprError(); 3375 3376 E = PE.get(); 3377 3378 // Verify that the operand is valid. 3379 bool isInvalid = false; 3380 if (E->isTypeDependent()) { 3381 // Delay type-checking for type-dependent expressions. 3382 } else if (ExprKind == UETT_AlignOf) { 3383 isInvalid = CheckAlignOfExpr(*this, E); 3384 } else if (ExprKind == UETT_VecStep) { 3385 isInvalid = CheckVecStepExpr(E); 3386 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3387 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3388 isInvalid = true; 3389 } else { 3390 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3391 } 3392 3393 if (isInvalid) 3394 return ExprError(); 3395 3396 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3397 PE = TransformToPotentiallyEvaluated(E); 3398 if (PE.isInvalid()) return ExprError(); 3399 E = PE.take(); 3400 } 3401 3402 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3403 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3404 ExprKind, E, Context.getSizeType(), OpLoc, 3405 E->getSourceRange().getEnd())); 3406 } 3407 3408 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3409 /// expr and the same for @c alignof and @c __alignof 3410 /// Note that the ArgRange is invalid if isType is false. 3411 ExprResult 3412 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3413 UnaryExprOrTypeTrait ExprKind, bool IsType, 3414 void *TyOrEx, const SourceRange &ArgRange) { 3415 // If error parsing type, ignore. 3416 if (TyOrEx == 0) return ExprError(); 3417 3418 if (IsType) { 3419 TypeSourceInfo *TInfo; 3420 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3421 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3422 } 3423 3424 Expr *ArgEx = (Expr *)TyOrEx; 3425 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3426 return Result; 3427 } 3428 3429 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3430 bool IsReal) { 3431 if (V.get()->isTypeDependent()) 3432 return S.Context.DependentTy; 3433 3434 // _Real and _Imag are only l-values for normal l-values. 3435 if (V.get()->getObjectKind() != OK_Ordinary) { 3436 V = S.DefaultLvalueConversion(V.take()); 3437 if (V.isInvalid()) 3438 return QualType(); 3439 } 3440 3441 // These operators return the element type of a complex type. 3442 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3443 return CT->getElementType(); 3444 3445 // Otherwise they pass through real integer and floating point types here. 3446 if (V.get()->getType()->isArithmeticType()) 3447 return V.get()->getType(); 3448 3449 // Test for placeholders. 3450 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3451 if (PR.isInvalid()) return QualType(); 3452 if (PR.get() != V.get()) { 3453 V = PR; 3454 return CheckRealImagOperand(S, V, Loc, IsReal); 3455 } 3456 3457 // Reject anything else. 3458 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3459 << (IsReal ? "__real" : "__imag"); 3460 return QualType(); 3461 } 3462 3463 3464 3465 ExprResult 3466 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3467 tok::TokenKind Kind, Expr *Input) { 3468 UnaryOperatorKind Opc; 3469 switch (Kind) { 3470 default: llvm_unreachable("Unknown unary op!"); 3471 case tok::plusplus: Opc = UO_PostInc; break; 3472 case tok::minusminus: Opc = UO_PostDec; break; 3473 } 3474 3475 // Since this might is a postfix expression, get rid of ParenListExprs. 3476 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3477 if (Result.isInvalid()) return ExprError(); 3478 Input = Result.take(); 3479 3480 return BuildUnaryOp(S, OpLoc, Opc, Input); 3481 } 3482 3483 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3484 /// 3485 /// \return true on error 3486 static bool checkArithmeticOnObjCPointer(Sema &S, 3487 SourceLocation opLoc, 3488 Expr *op) { 3489 assert(op->getType()->isObjCObjectPointerType()); 3490 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3491 return false; 3492 3493 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3494 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3495 << op->getSourceRange(); 3496 return true; 3497 } 3498 3499 ExprResult 3500 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3501 Expr *idx, SourceLocation rbLoc) { 3502 // Since this might be a postfix expression, get rid of ParenListExprs. 3503 if (isa<ParenListExpr>(base)) { 3504 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3505 if (result.isInvalid()) return ExprError(); 3506 base = result.take(); 3507 } 3508 3509 // Handle any non-overload placeholder types in the base and index 3510 // expressions. We can't handle overloads here because the other 3511 // operand might be an overloadable type, in which case the overload 3512 // resolution for the operator overload should get the first crack 3513 // at the overload. 3514 if (base->getType()->isNonOverloadPlaceholderType()) { 3515 ExprResult result = CheckPlaceholderExpr(base); 3516 if (result.isInvalid()) return ExprError(); 3517 base = result.take(); 3518 } 3519 if (idx->getType()->isNonOverloadPlaceholderType()) { 3520 ExprResult result = CheckPlaceholderExpr(idx); 3521 if (result.isInvalid()) return ExprError(); 3522 idx = result.take(); 3523 } 3524 3525 // Build an unanalyzed expression if either operand is type-dependent. 3526 if (getLangOpts().CPlusPlus && 3527 (base->isTypeDependent() || idx->isTypeDependent())) { 3528 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3529 Context.DependentTy, 3530 VK_LValue, OK_Ordinary, 3531 rbLoc)); 3532 } 3533 3534 // Use C++ overloaded-operator rules if either operand has record 3535 // type. The spec says to do this if either type is *overloadable*, 3536 // but enum types can't declare subscript operators or conversion 3537 // operators, so there's nothing interesting for overload resolution 3538 // to do if there aren't any record types involved. 3539 // 3540 // ObjC pointers have their own subscripting logic that is not tied 3541 // to overload resolution and so should not take this path. 3542 if (getLangOpts().CPlusPlus && 3543 (base->getType()->isRecordType() || 3544 (!base->getType()->isObjCObjectPointerType() && 3545 idx->getType()->isRecordType()))) { 3546 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3547 } 3548 3549 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3550 } 3551 3552 ExprResult 3553 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3554 Expr *Idx, SourceLocation RLoc) { 3555 Expr *LHSExp = Base; 3556 Expr *RHSExp = Idx; 3557 3558 // Perform default conversions. 3559 if (!LHSExp->getType()->getAs<VectorType>()) { 3560 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3561 if (Result.isInvalid()) 3562 return ExprError(); 3563 LHSExp = Result.take(); 3564 } 3565 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3566 if (Result.isInvalid()) 3567 return ExprError(); 3568 RHSExp = Result.take(); 3569 3570 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3571 ExprValueKind VK = VK_LValue; 3572 ExprObjectKind OK = OK_Ordinary; 3573 3574 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3575 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3576 // in the subscript position. As a result, we need to derive the array base 3577 // and index from the expression types. 3578 Expr *BaseExpr, *IndexExpr; 3579 QualType ResultType; 3580 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3581 BaseExpr = LHSExp; 3582 IndexExpr = RHSExp; 3583 ResultType = Context.DependentTy; 3584 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3585 BaseExpr = LHSExp; 3586 IndexExpr = RHSExp; 3587 ResultType = PTy->getPointeeType(); 3588 } else if (const ObjCObjectPointerType *PTy = 3589 LHSTy->getAs<ObjCObjectPointerType>()) { 3590 BaseExpr = LHSExp; 3591 IndexExpr = RHSExp; 3592 3593 // Use custom logic if this should be the pseudo-object subscript 3594 // expression. 3595 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()) 3596 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3597 3598 ResultType = PTy->getPointeeType(); 3599 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3600 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3601 << ResultType << BaseExpr->getSourceRange(); 3602 return ExprError(); 3603 } 3604 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3605 // Handle the uncommon case of "123[Ptr]". 3606 BaseExpr = RHSExp; 3607 IndexExpr = LHSExp; 3608 ResultType = PTy->getPointeeType(); 3609 } else if (const ObjCObjectPointerType *PTy = 3610 RHSTy->getAs<ObjCObjectPointerType>()) { 3611 // Handle the uncommon case of "123[Ptr]". 3612 BaseExpr = RHSExp; 3613 IndexExpr = LHSExp; 3614 ResultType = PTy->getPointeeType(); 3615 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3616 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3617 << ResultType << BaseExpr->getSourceRange(); 3618 return ExprError(); 3619 } 3620 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3621 BaseExpr = LHSExp; // vectors: V[123] 3622 IndexExpr = RHSExp; 3623 VK = LHSExp->getValueKind(); 3624 if (VK != VK_RValue) 3625 OK = OK_VectorComponent; 3626 3627 // FIXME: need to deal with const... 3628 ResultType = VTy->getElementType(); 3629 } else if (LHSTy->isArrayType()) { 3630 // If we see an array that wasn't promoted by 3631 // DefaultFunctionArrayLvalueConversion, it must be an array that 3632 // wasn't promoted because of the C90 rule that doesn't 3633 // allow promoting non-lvalue arrays. Warn, then 3634 // force the promotion here. 3635 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3636 LHSExp->getSourceRange(); 3637 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3638 CK_ArrayToPointerDecay).take(); 3639 LHSTy = LHSExp->getType(); 3640 3641 BaseExpr = LHSExp; 3642 IndexExpr = RHSExp; 3643 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3644 } else if (RHSTy->isArrayType()) { 3645 // Same as previous, except for 123[f().a] case 3646 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3647 RHSExp->getSourceRange(); 3648 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3649 CK_ArrayToPointerDecay).take(); 3650 RHSTy = RHSExp->getType(); 3651 3652 BaseExpr = RHSExp; 3653 IndexExpr = LHSExp; 3654 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3655 } else { 3656 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3657 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3658 } 3659 // C99 6.5.2.1p1 3660 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3661 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3662 << IndexExpr->getSourceRange()); 3663 3664 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3665 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3666 && !IndexExpr->isTypeDependent()) 3667 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3668 3669 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3670 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3671 // type. Note that Functions are not objects, and that (in C99 parlance) 3672 // incomplete types are not object types. 3673 if (ResultType->isFunctionType()) { 3674 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3675 << ResultType << BaseExpr->getSourceRange(); 3676 return ExprError(); 3677 } 3678 3679 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3680 // GNU extension: subscripting on pointer to void 3681 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3682 << BaseExpr->getSourceRange(); 3683 3684 // C forbids expressions of unqualified void type from being l-values. 3685 // See IsCForbiddenLValueType. 3686 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3687 } else if (!ResultType->isDependentType() && 3688 RequireCompleteType(LLoc, ResultType, 3689 diag::err_subscript_incomplete_type, BaseExpr)) 3690 return ExprError(); 3691 3692 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3693 !ResultType.isCForbiddenLValueType()); 3694 3695 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3696 ResultType, VK, OK, RLoc)); 3697 } 3698 3699 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3700 FunctionDecl *FD, 3701 ParmVarDecl *Param) { 3702 if (Param->hasUnparsedDefaultArg()) { 3703 Diag(CallLoc, 3704 diag::err_use_of_default_argument_to_function_declared_later) << 3705 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3706 Diag(UnparsedDefaultArgLocs[Param], 3707 diag::note_default_argument_declared_here); 3708 return ExprError(); 3709 } 3710 3711 if (Param->hasUninstantiatedDefaultArg()) { 3712 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3713 3714 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3715 Param); 3716 3717 // Instantiate the expression. 3718 MultiLevelTemplateArgumentList MutiLevelArgList 3719 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3720 3721 InstantiatingTemplate Inst(*this, CallLoc, Param, 3722 MutiLevelArgList.getInnermost()); 3723 if (Inst) 3724 return ExprError(); 3725 3726 ExprResult Result; 3727 { 3728 // C++ [dcl.fct.default]p5: 3729 // The names in the [default argument] expression are bound, and 3730 // the semantic constraints are checked, at the point where the 3731 // default argument expression appears. 3732 ContextRAII SavedContext(*this, FD); 3733 LocalInstantiationScope Local(*this); 3734 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3735 } 3736 if (Result.isInvalid()) 3737 return ExprError(); 3738 3739 // Check the expression as an initializer for the parameter. 3740 InitializedEntity Entity 3741 = InitializedEntity::InitializeParameter(Context, Param); 3742 InitializationKind Kind 3743 = InitializationKind::CreateCopy(Param->getLocation(), 3744 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3745 Expr *ResultE = Result.takeAs<Expr>(); 3746 3747 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3748 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3749 if (Result.isInvalid()) 3750 return ExprError(); 3751 3752 Expr *Arg = Result.takeAs<Expr>(); 3753 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3754 // Build the default argument expression. 3755 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3756 } 3757 3758 // If the default expression creates temporaries, we need to 3759 // push them to the current stack of expression temporaries so they'll 3760 // be properly destroyed. 3761 // FIXME: We should really be rebuilding the default argument with new 3762 // bound temporaries; see the comment in PR5810. 3763 // We don't need to do that with block decls, though, because 3764 // blocks in default argument expression can never capture anything. 3765 if (isa<ExprWithCleanups>(Param->getInit())) { 3766 // Set the "needs cleanups" bit regardless of whether there are 3767 // any explicit objects. 3768 ExprNeedsCleanups = true; 3769 3770 // Append all the objects to the cleanup list. Right now, this 3771 // should always be a no-op, because blocks in default argument 3772 // expressions should never be able to capture anything. 3773 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3774 "default argument expression has capturing blocks?"); 3775 } 3776 3777 // We already type-checked the argument, so we know it works. 3778 // Just mark all of the declarations in this potentially-evaluated expression 3779 // as being "referenced". 3780 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3781 /*SkipLocalVariables=*/true); 3782 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3783 } 3784 3785 3786 Sema::VariadicCallType 3787 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3788 Expr *Fn) { 3789 if (Proto && Proto->isVariadic()) { 3790 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3791 return VariadicConstructor; 3792 else if (Fn && Fn->getType()->isBlockPointerType()) 3793 return VariadicBlock; 3794 else if (FDecl) { 3795 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3796 if (Method->isInstance()) 3797 return VariadicMethod; 3798 } 3799 return VariadicFunction; 3800 } 3801 return VariadicDoesNotApply; 3802 } 3803 3804 /// ConvertArgumentsForCall - Converts the arguments specified in 3805 /// Args/NumArgs to the parameter types of the function FDecl with 3806 /// function prototype Proto. Call is the call expression itself, and 3807 /// Fn is the function expression. For a C++ member function, this 3808 /// routine does not attempt to convert the object argument. Returns 3809 /// true if the call is ill-formed. 3810 bool 3811 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3812 FunctionDecl *FDecl, 3813 const FunctionProtoType *Proto, 3814 Expr **Args, unsigned NumArgs, 3815 SourceLocation RParenLoc, 3816 bool IsExecConfig) { 3817 // Bail out early if calling a builtin with custom typechecking. 3818 // We don't need to do this in the 3819 if (FDecl) 3820 if (unsigned ID = FDecl->getBuiltinID()) 3821 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3822 return false; 3823 3824 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3825 // assignment, to the types of the corresponding parameter, ... 3826 unsigned NumArgsInProto = Proto->getNumArgs(); 3827 bool Invalid = false; 3828 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3829 unsigned FnKind = Fn->getType()->isBlockPointerType() 3830 ? 1 /* block */ 3831 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3832 : 0 /* function */); 3833 3834 // If too few arguments are available (and we don't have default 3835 // arguments for the remaining parameters), don't make the call. 3836 if (NumArgs < NumArgsInProto) { 3837 if (NumArgs < MinArgs) { 3838 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3839 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3840 ? diag::err_typecheck_call_too_few_args_one 3841 : diag::err_typecheck_call_too_few_args_at_least_one) 3842 << FnKind 3843 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 3844 else 3845 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3846 ? diag::err_typecheck_call_too_few_args 3847 : diag::err_typecheck_call_too_few_args_at_least) 3848 << FnKind 3849 << MinArgs << NumArgs << Fn->getSourceRange(); 3850 3851 // Emit the location of the prototype. 3852 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3853 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3854 << FDecl; 3855 3856 return true; 3857 } 3858 Call->setNumArgs(Context, NumArgsInProto); 3859 } 3860 3861 // If too many are passed and not variadic, error on the extras and drop 3862 // them. 3863 if (NumArgs > NumArgsInProto) { 3864 if (!Proto->isVariadic()) { 3865 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3866 Diag(Args[NumArgsInProto]->getLocStart(), 3867 MinArgs == NumArgsInProto 3868 ? diag::err_typecheck_call_too_many_args_one 3869 : diag::err_typecheck_call_too_many_args_at_most_one) 3870 << FnKind 3871 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange() 3872 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3873 Args[NumArgs-1]->getLocEnd()); 3874 else 3875 Diag(Args[NumArgsInProto]->getLocStart(), 3876 MinArgs == NumArgsInProto 3877 ? diag::err_typecheck_call_too_many_args 3878 : diag::err_typecheck_call_too_many_args_at_most) 3879 << FnKind 3880 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3881 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3882 Args[NumArgs-1]->getLocEnd()); 3883 3884 // Emit the location of the prototype. 3885 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3886 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3887 << FDecl; 3888 3889 // This deletes the extra arguments. 3890 Call->setNumArgs(Context, NumArgsInProto); 3891 return true; 3892 } 3893 } 3894 SmallVector<Expr *, 8> AllArgs; 3895 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 3896 3897 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 3898 Proto, 0, Args, NumArgs, AllArgs, CallType); 3899 if (Invalid) 3900 return true; 3901 unsigned TotalNumArgs = AllArgs.size(); 3902 for (unsigned i = 0; i < TotalNumArgs; ++i) 3903 Call->setArg(i, AllArgs[i]); 3904 3905 return false; 3906 } 3907 3908 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3909 FunctionDecl *FDecl, 3910 const FunctionProtoType *Proto, 3911 unsigned FirstProtoArg, 3912 Expr **Args, unsigned NumArgs, 3913 SmallVector<Expr *, 8> &AllArgs, 3914 VariadicCallType CallType, 3915 bool AllowExplicit, 3916 bool IsListInitialization) { 3917 unsigned NumArgsInProto = Proto->getNumArgs(); 3918 unsigned NumArgsToCheck = NumArgs; 3919 bool Invalid = false; 3920 if (NumArgs != NumArgsInProto) 3921 // Use default arguments for missing arguments 3922 NumArgsToCheck = NumArgsInProto; 3923 unsigned ArgIx = 0; 3924 // Continue to check argument types (even if we have too few/many args). 3925 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3926 QualType ProtoArgType = Proto->getArgType(i); 3927 3928 Expr *Arg; 3929 ParmVarDecl *Param; 3930 if (ArgIx < NumArgs) { 3931 Arg = Args[ArgIx++]; 3932 3933 if (RequireCompleteType(Arg->getLocStart(), 3934 ProtoArgType, 3935 diag::err_call_incomplete_argument, Arg)) 3936 return true; 3937 3938 // Pass the argument 3939 Param = 0; 3940 if (FDecl && i < FDecl->getNumParams()) 3941 Param = FDecl->getParamDecl(i); 3942 3943 // Strip the unbridged-cast placeholder expression off, if applicable. 3944 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3945 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3946 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3947 Arg = stripARCUnbridgedCast(Arg); 3948 3949 InitializedEntity Entity = Param ? 3950 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType) 3951 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3952 Proto->isArgConsumed(i)); 3953 ExprResult ArgE = PerformCopyInitialization(Entity, 3954 SourceLocation(), 3955 Owned(Arg), 3956 IsListInitialization, 3957 AllowExplicit); 3958 if (ArgE.isInvalid()) 3959 return true; 3960 3961 Arg = ArgE.takeAs<Expr>(); 3962 } else { 3963 assert(FDecl && "can't use default arguments without a known callee"); 3964 Param = FDecl->getParamDecl(i); 3965 3966 ExprResult ArgExpr = 3967 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3968 if (ArgExpr.isInvalid()) 3969 return true; 3970 3971 Arg = ArgExpr.takeAs<Expr>(); 3972 } 3973 3974 // Check for array bounds violations for each argument to the call. This 3975 // check only triggers warnings when the argument isn't a more complex Expr 3976 // with its own checking, such as a BinaryOperator. 3977 CheckArrayAccess(Arg); 3978 3979 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3980 CheckStaticArrayArgument(CallLoc, Param, Arg); 3981 3982 AllArgs.push_back(Arg); 3983 } 3984 3985 // If this is a variadic call, handle args passed through "...". 3986 if (CallType != VariadicDoesNotApply) { 3987 // Assume that extern "C" functions with variadic arguments that 3988 // return __unknown_anytype aren't *really* variadic. 3989 if (Proto->getResultType() == Context.UnknownAnyTy && 3990 FDecl && FDecl->isExternC()) { 3991 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3992 QualType paramType; // ignored 3993 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 3994 Invalid |= arg.isInvalid(); 3995 AllArgs.push_back(arg.take()); 3996 } 3997 3998 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3999 } else { 4000 for (unsigned i = ArgIx; i != NumArgs; ++i) { 4001 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4002 FDecl); 4003 Invalid |= Arg.isInvalid(); 4004 AllArgs.push_back(Arg.take()); 4005 } 4006 } 4007 4008 // Check for array bounds violations. 4009 for (unsigned i = ArgIx; i != NumArgs; ++i) 4010 CheckArrayAccess(Args[i]); 4011 } 4012 return Invalid; 4013 } 4014 4015 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4016 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4017 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4018 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4019 << ATL.getLocalSourceRange(); 4020 } 4021 4022 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4023 /// array parameter, check that it is non-null, and that if it is formed by 4024 /// array-to-pointer decay, the underlying array is sufficiently large. 4025 /// 4026 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4027 /// array type derivation, then for each call to the function, the value of the 4028 /// corresponding actual argument shall provide access to the first element of 4029 /// an array with at least as many elements as specified by the size expression. 4030 void 4031 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4032 ParmVarDecl *Param, 4033 const Expr *ArgExpr) { 4034 // Static array parameters are not supported in C++. 4035 if (!Param || getLangOpts().CPlusPlus) 4036 return; 4037 4038 QualType OrigTy = Param->getOriginalType(); 4039 4040 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4041 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4042 return; 4043 4044 if (ArgExpr->isNullPointerConstant(Context, 4045 Expr::NPC_NeverValueDependent)) { 4046 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4047 DiagnoseCalleeStaticArrayParam(*this, Param); 4048 return; 4049 } 4050 4051 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4052 if (!CAT) 4053 return; 4054 4055 const ConstantArrayType *ArgCAT = 4056 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4057 if (!ArgCAT) 4058 return; 4059 4060 if (ArgCAT->getSize().ult(CAT->getSize())) { 4061 Diag(CallLoc, diag::warn_static_array_too_small) 4062 << ArgExpr->getSourceRange() 4063 << (unsigned) ArgCAT->getSize().getZExtValue() 4064 << (unsigned) CAT->getSize().getZExtValue(); 4065 DiagnoseCalleeStaticArrayParam(*this, Param); 4066 } 4067 } 4068 4069 /// Given a function expression of unknown-any type, try to rebuild it 4070 /// to have a function type. 4071 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4072 4073 /// Is the given type a placeholder that we need to lower out 4074 /// immediately during argument processing? 4075 static bool isPlaceholderToRemoveAsArg(QualType type) { 4076 // Placeholders are never sugared. 4077 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4078 if (!placeholder) return false; 4079 4080 switch (placeholder->getKind()) { 4081 // Ignore all the non-placeholder types. 4082 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4083 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4084 #include "clang/AST/BuiltinTypes.def" 4085 return false; 4086 4087 // We cannot lower out overload sets; they might validly be resolved 4088 // by the call machinery. 4089 case BuiltinType::Overload: 4090 return false; 4091 4092 // Unbridged casts in ARC can be handled in some call positions and 4093 // should be left in place. 4094 case BuiltinType::ARCUnbridgedCast: 4095 return false; 4096 4097 // Pseudo-objects should be converted as soon as possible. 4098 case BuiltinType::PseudoObject: 4099 return true; 4100 4101 // The debugger mode could theoretically but currently does not try 4102 // to resolve unknown-typed arguments based on known parameter types. 4103 case BuiltinType::UnknownAny: 4104 return true; 4105 4106 // These are always invalid as call arguments and should be reported. 4107 case BuiltinType::BoundMember: 4108 case BuiltinType::BuiltinFn: 4109 return true; 4110 } 4111 llvm_unreachable("bad builtin type kind"); 4112 } 4113 4114 /// Check an argument list for placeholders that we won't try to 4115 /// handle later. 4116 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4117 // Apply this processing to all the arguments at once instead of 4118 // dying at the first failure. 4119 bool hasInvalid = false; 4120 for (size_t i = 0, e = args.size(); i != e; i++) { 4121 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4122 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4123 if (result.isInvalid()) hasInvalid = true; 4124 else args[i] = result.take(); 4125 } 4126 } 4127 return hasInvalid; 4128 } 4129 4130 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4131 /// This provides the location of the left/right parens and a list of comma 4132 /// locations. 4133 ExprResult 4134 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4135 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4136 Expr *ExecConfig, bool IsExecConfig) { 4137 // Since this might be a postfix expression, get rid of ParenListExprs. 4138 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4139 if (Result.isInvalid()) return ExprError(); 4140 Fn = Result.take(); 4141 4142 if (checkArgsForPlaceholders(*this, ArgExprs)) 4143 return ExprError(); 4144 4145 if (getLangOpts().CPlusPlus) { 4146 // If this is a pseudo-destructor expression, build the call immediately. 4147 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4148 if (!ArgExprs.empty()) { 4149 // Pseudo-destructor calls should not have any arguments. 4150 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4151 << FixItHint::CreateRemoval( 4152 SourceRange(ArgExprs[0]->getLocStart(), 4153 ArgExprs.back()->getLocEnd())); 4154 } 4155 4156 return Owned(new (Context) CallExpr(Context, Fn, None, 4157 Context.VoidTy, VK_RValue, 4158 RParenLoc)); 4159 } 4160 if (Fn->getType() == Context.PseudoObjectTy) { 4161 ExprResult result = CheckPlaceholderExpr(Fn); 4162 if (result.isInvalid()) return ExprError(); 4163 Fn = result.take(); 4164 } 4165 4166 // Determine whether this is a dependent call inside a C++ template, 4167 // in which case we won't do any semantic analysis now. 4168 // FIXME: Will need to cache the results of name lookup (including ADL) in 4169 // Fn. 4170 bool Dependent = false; 4171 if (Fn->isTypeDependent()) 4172 Dependent = true; 4173 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4174 Dependent = true; 4175 4176 if (Dependent) { 4177 if (ExecConfig) { 4178 return Owned(new (Context) CUDAKernelCallExpr( 4179 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4180 Context.DependentTy, VK_RValue, RParenLoc)); 4181 } else { 4182 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4183 Context.DependentTy, VK_RValue, 4184 RParenLoc)); 4185 } 4186 } 4187 4188 // Determine whether this is a call to an object (C++ [over.call.object]). 4189 if (Fn->getType()->isRecordType()) 4190 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4191 ArgExprs.data(), 4192 ArgExprs.size(), RParenLoc)); 4193 4194 if (Fn->getType() == Context.UnknownAnyTy) { 4195 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4196 if (result.isInvalid()) return ExprError(); 4197 Fn = result.take(); 4198 } 4199 4200 if (Fn->getType() == Context.BoundMemberTy) { 4201 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(), 4202 ArgExprs.size(), RParenLoc); 4203 } 4204 } 4205 4206 // Check for overloaded calls. This can happen even in C due to extensions. 4207 if (Fn->getType() == Context.OverloadTy) { 4208 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4209 4210 // We aren't supposed to apply this logic for if there's an '&' involved. 4211 if (!find.HasFormOfMemberPointer) { 4212 OverloadExpr *ovl = find.Expression; 4213 if (isa<UnresolvedLookupExpr>(ovl)) { 4214 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4215 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(), 4216 ArgExprs.size(), RParenLoc, ExecConfig); 4217 } else { 4218 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(), 4219 ArgExprs.size(), RParenLoc); 4220 } 4221 } 4222 } 4223 4224 // If we're directly calling a function, get the appropriate declaration. 4225 if (Fn->getType() == Context.UnknownAnyTy) { 4226 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4227 if (result.isInvalid()) return ExprError(); 4228 Fn = result.take(); 4229 } 4230 4231 Expr *NakedFn = Fn->IgnoreParens(); 4232 4233 NamedDecl *NDecl = 0; 4234 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4235 if (UnOp->getOpcode() == UO_AddrOf) 4236 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4237 4238 if (isa<DeclRefExpr>(NakedFn)) 4239 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4240 else if (isa<MemberExpr>(NakedFn)) 4241 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4242 4243 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(), 4244 ArgExprs.size(), RParenLoc, ExecConfig, 4245 IsExecConfig); 4246 } 4247 4248 ExprResult 4249 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4250 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4251 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4252 if (!ConfigDecl) 4253 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4254 << "cudaConfigureCall"); 4255 QualType ConfigQTy = ConfigDecl->getType(); 4256 4257 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4258 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4259 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4260 4261 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4262 /*IsExecConfig=*/true); 4263 } 4264 4265 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4266 /// 4267 /// __builtin_astype( value, dst type ) 4268 /// 4269 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4270 SourceLocation BuiltinLoc, 4271 SourceLocation RParenLoc) { 4272 ExprValueKind VK = VK_RValue; 4273 ExprObjectKind OK = OK_Ordinary; 4274 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4275 QualType SrcTy = E->getType(); 4276 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4277 return ExprError(Diag(BuiltinLoc, 4278 diag::err_invalid_astype_of_different_size) 4279 << DstTy 4280 << SrcTy 4281 << E->getSourceRange()); 4282 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4283 RParenLoc)); 4284 } 4285 4286 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4287 /// i.e. an expression not of \p OverloadTy. The expression should 4288 /// unary-convert to an expression of function-pointer or 4289 /// block-pointer type. 4290 /// 4291 /// \param NDecl the declaration being called, if available 4292 ExprResult 4293 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4294 SourceLocation LParenLoc, 4295 Expr **Args, unsigned NumArgs, 4296 SourceLocation RParenLoc, 4297 Expr *Config, bool IsExecConfig) { 4298 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4299 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4300 4301 // Promote the function operand. 4302 // We special-case function promotion here because we only allow promoting 4303 // builtin functions to function pointers in the callee of a call. 4304 ExprResult Result; 4305 if (BuiltinID && 4306 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4307 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4308 CK_BuiltinFnToFnPtr).take(); 4309 } else { 4310 Result = UsualUnaryConversions(Fn); 4311 } 4312 if (Result.isInvalid()) 4313 return ExprError(); 4314 Fn = Result.take(); 4315 4316 // Make the call expr early, before semantic checks. This guarantees cleanup 4317 // of arguments and function on error. 4318 CallExpr *TheCall; 4319 if (Config) 4320 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4321 cast<CallExpr>(Config), 4322 llvm::makeArrayRef(Args,NumArgs), 4323 Context.BoolTy, 4324 VK_RValue, 4325 RParenLoc); 4326 else 4327 TheCall = new (Context) CallExpr(Context, Fn, 4328 llvm::makeArrayRef(Args, NumArgs), 4329 Context.BoolTy, 4330 VK_RValue, 4331 RParenLoc); 4332 4333 // Bail out early if calling a builtin with custom typechecking. 4334 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4335 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4336 4337 retry: 4338 const FunctionType *FuncT; 4339 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4340 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4341 // have type pointer to function". 4342 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4343 if (FuncT == 0) 4344 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4345 << Fn->getType() << Fn->getSourceRange()); 4346 } else if (const BlockPointerType *BPT = 4347 Fn->getType()->getAs<BlockPointerType>()) { 4348 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4349 } else { 4350 // Handle calls to expressions of unknown-any type. 4351 if (Fn->getType() == Context.UnknownAnyTy) { 4352 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4353 if (rewrite.isInvalid()) return ExprError(); 4354 Fn = rewrite.take(); 4355 TheCall->setCallee(Fn); 4356 goto retry; 4357 } 4358 4359 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4360 << Fn->getType() << Fn->getSourceRange()); 4361 } 4362 4363 if (getLangOpts().CUDA) { 4364 if (Config) { 4365 // CUDA: Kernel calls must be to global functions 4366 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4367 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4368 << FDecl->getName() << Fn->getSourceRange()); 4369 4370 // CUDA: Kernel function must have 'void' return type 4371 if (!FuncT->getResultType()->isVoidType()) 4372 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4373 << Fn->getType() << Fn->getSourceRange()); 4374 } else { 4375 // CUDA: Calls to global functions must be configured 4376 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4377 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4378 << FDecl->getName() << Fn->getSourceRange()); 4379 } 4380 } 4381 4382 // Check for a valid return type 4383 if (CheckCallReturnType(FuncT->getResultType(), 4384 Fn->getLocStart(), TheCall, 4385 FDecl)) 4386 return ExprError(); 4387 4388 // We know the result type of the call, set it. 4389 TheCall->setType(FuncT->getCallResultType(Context)); 4390 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4391 4392 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4393 if (Proto) { 4394 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 4395 RParenLoc, IsExecConfig)) 4396 return ExprError(); 4397 } else { 4398 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4399 4400 if (FDecl) { 4401 // Check if we have too few/too many template arguments, based 4402 // on our knowledge of the function definition. 4403 const FunctionDecl *Def = 0; 4404 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 4405 Proto = Def->getType()->getAs<FunctionProtoType>(); 4406 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 4407 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4408 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 4409 } 4410 4411 // If the function we're calling isn't a function prototype, but we have 4412 // a function prototype from a prior declaratiom, use that prototype. 4413 if (!FDecl->hasPrototype()) 4414 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4415 } 4416 4417 // Promote the arguments (C99 6.5.2.2p6). 4418 for (unsigned i = 0; i != NumArgs; i++) { 4419 Expr *Arg = Args[i]; 4420 4421 if (Proto && i < Proto->getNumArgs()) { 4422 InitializedEntity Entity 4423 = InitializedEntity::InitializeParameter(Context, 4424 Proto->getArgType(i), 4425 Proto->isArgConsumed(i)); 4426 ExprResult ArgE = PerformCopyInitialization(Entity, 4427 SourceLocation(), 4428 Owned(Arg)); 4429 if (ArgE.isInvalid()) 4430 return true; 4431 4432 Arg = ArgE.takeAs<Expr>(); 4433 4434 } else { 4435 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4436 4437 if (ArgE.isInvalid()) 4438 return true; 4439 4440 Arg = ArgE.takeAs<Expr>(); 4441 } 4442 4443 if (RequireCompleteType(Arg->getLocStart(), 4444 Arg->getType(), 4445 diag::err_call_incomplete_argument, Arg)) 4446 return ExprError(); 4447 4448 TheCall->setArg(i, Arg); 4449 } 4450 } 4451 4452 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4453 if (!Method->isStatic()) 4454 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4455 << Fn->getSourceRange()); 4456 4457 // Check for sentinels 4458 if (NDecl) 4459 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 4460 4461 // Do special checking on direct calls to functions. 4462 if (FDecl) { 4463 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4464 return ExprError(); 4465 4466 if (BuiltinID) 4467 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4468 } else if (NDecl) { 4469 if (CheckBlockCall(NDecl, TheCall, Proto)) 4470 return ExprError(); 4471 } 4472 4473 return MaybeBindToTemporary(TheCall); 4474 } 4475 4476 ExprResult 4477 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4478 SourceLocation RParenLoc, Expr *InitExpr) { 4479 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 4480 // FIXME: put back this assert when initializers are worked out. 4481 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4482 4483 TypeSourceInfo *TInfo; 4484 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4485 if (!TInfo) 4486 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4487 4488 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4489 } 4490 4491 ExprResult 4492 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4493 SourceLocation RParenLoc, Expr *LiteralExpr) { 4494 QualType literalType = TInfo->getType(); 4495 4496 if (literalType->isArrayType()) { 4497 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4498 diag::err_illegal_decl_array_incomplete_type, 4499 SourceRange(LParenLoc, 4500 LiteralExpr->getSourceRange().getEnd()))) 4501 return ExprError(); 4502 if (literalType->isVariableArrayType()) 4503 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4504 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4505 } else if (!literalType->isDependentType() && 4506 RequireCompleteType(LParenLoc, literalType, 4507 diag::err_typecheck_decl_incomplete_type, 4508 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4509 return ExprError(); 4510 4511 InitializedEntity Entity 4512 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4513 InitializationKind Kind 4514 = InitializationKind::CreateCStyleCast(LParenLoc, 4515 SourceRange(LParenLoc, RParenLoc), 4516 /*InitList=*/true); 4517 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4518 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4519 &literalType); 4520 if (Result.isInvalid()) 4521 return ExprError(); 4522 LiteralExpr = Result.get(); 4523 4524 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4525 if (isFileScope) { // 6.5.2.5p3 4526 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4527 return ExprError(); 4528 } 4529 4530 // In C, compound literals are l-values for some reason. 4531 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4532 4533 return MaybeBindToTemporary( 4534 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4535 VK, LiteralExpr, isFileScope)); 4536 } 4537 4538 ExprResult 4539 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4540 SourceLocation RBraceLoc) { 4541 // Immediately handle non-overload placeholders. Overloads can be 4542 // resolved contextually, but everything else here can't. 4543 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4544 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4545 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4546 4547 // Ignore failures; dropping the entire initializer list because 4548 // of one failure would be terrible for indexing/etc. 4549 if (result.isInvalid()) continue; 4550 4551 InitArgList[I] = result.take(); 4552 } 4553 } 4554 4555 // Semantic analysis for initializers is done by ActOnDeclarator() and 4556 // CheckInitializer() - it requires knowledge of the object being intialized. 4557 4558 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4559 RBraceLoc); 4560 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4561 return Owned(E); 4562 } 4563 4564 /// Do an explicit extend of the given block pointer if we're in ARC. 4565 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4566 assert(E.get()->getType()->isBlockPointerType()); 4567 assert(E.get()->isRValue()); 4568 4569 // Only do this in an r-value context. 4570 if (!S.getLangOpts().ObjCAutoRefCount) return; 4571 4572 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4573 CK_ARCExtendBlockObject, E.get(), 4574 /*base path*/ 0, VK_RValue); 4575 S.ExprNeedsCleanups = true; 4576 } 4577 4578 /// Prepare a conversion of the given expression to an ObjC object 4579 /// pointer type. 4580 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4581 QualType type = E.get()->getType(); 4582 if (type->isObjCObjectPointerType()) { 4583 return CK_BitCast; 4584 } else if (type->isBlockPointerType()) { 4585 maybeExtendBlockObject(*this, E); 4586 return CK_BlockPointerToObjCPointerCast; 4587 } else { 4588 assert(type->isPointerType()); 4589 return CK_CPointerToObjCPointerCast; 4590 } 4591 } 4592 4593 /// Prepares for a scalar cast, performing all the necessary stages 4594 /// except the final cast and returning the kind required. 4595 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4596 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4597 // Also, callers should have filtered out the invalid cases with 4598 // pointers. Everything else should be possible. 4599 4600 QualType SrcTy = Src.get()->getType(); 4601 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4602 return CK_NoOp; 4603 4604 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4605 case Type::STK_MemberPointer: 4606 llvm_unreachable("member pointer type in C"); 4607 4608 case Type::STK_CPointer: 4609 case Type::STK_BlockPointer: 4610 case Type::STK_ObjCObjectPointer: 4611 switch (DestTy->getScalarTypeKind()) { 4612 case Type::STK_CPointer: 4613 return CK_BitCast; 4614 case Type::STK_BlockPointer: 4615 return (SrcKind == Type::STK_BlockPointer 4616 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4617 case Type::STK_ObjCObjectPointer: 4618 if (SrcKind == Type::STK_ObjCObjectPointer) 4619 return CK_BitCast; 4620 if (SrcKind == Type::STK_CPointer) 4621 return CK_CPointerToObjCPointerCast; 4622 maybeExtendBlockObject(*this, Src); 4623 return CK_BlockPointerToObjCPointerCast; 4624 case Type::STK_Bool: 4625 return CK_PointerToBoolean; 4626 case Type::STK_Integral: 4627 return CK_PointerToIntegral; 4628 case Type::STK_Floating: 4629 case Type::STK_FloatingComplex: 4630 case Type::STK_IntegralComplex: 4631 case Type::STK_MemberPointer: 4632 llvm_unreachable("illegal cast from pointer"); 4633 } 4634 llvm_unreachable("Should have returned before this"); 4635 4636 case Type::STK_Bool: // casting from bool is like casting from an integer 4637 case Type::STK_Integral: 4638 switch (DestTy->getScalarTypeKind()) { 4639 case Type::STK_CPointer: 4640 case Type::STK_ObjCObjectPointer: 4641 case Type::STK_BlockPointer: 4642 if (Src.get()->isNullPointerConstant(Context, 4643 Expr::NPC_ValueDependentIsNull)) 4644 return CK_NullToPointer; 4645 return CK_IntegralToPointer; 4646 case Type::STK_Bool: 4647 return CK_IntegralToBoolean; 4648 case Type::STK_Integral: 4649 return CK_IntegralCast; 4650 case Type::STK_Floating: 4651 return CK_IntegralToFloating; 4652 case Type::STK_IntegralComplex: 4653 Src = ImpCastExprToType(Src.take(), 4654 DestTy->castAs<ComplexType>()->getElementType(), 4655 CK_IntegralCast); 4656 return CK_IntegralRealToComplex; 4657 case Type::STK_FloatingComplex: 4658 Src = ImpCastExprToType(Src.take(), 4659 DestTy->castAs<ComplexType>()->getElementType(), 4660 CK_IntegralToFloating); 4661 return CK_FloatingRealToComplex; 4662 case Type::STK_MemberPointer: 4663 llvm_unreachable("member pointer type in C"); 4664 } 4665 llvm_unreachable("Should have returned before this"); 4666 4667 case Type::STK_Floating: 4668 switch (DestTy->getScalarTypeKind()) { 4669 case Type::STK_Floating: 4670 return CK_FloatingCast; 4671 case Type::STK_Bool: 4672 return CK_FloatingToBoolean; 4673 case Type::STK_Integral: 4674 return CK_FloatingToIntegral; 4675 case Type::STK_FloatingComplex: 4676 Src = ImpCastExprToType(Src.take(), 4677 DestTy->castAs<ComplexType>()->getElementType(), 4678 CK_FloatingCast); 4679 return CK_FloatingRealToComplex; 4680 case Type::STK_IntegralComplex: 4681 Src = ImpCastExprToType(Src.take(), 4682 DestTy->castAs<ComplexType>()->getElementType(), 4683 CK_FloatingToIntegral); 4684 return CK_IntegralRealToComplex; 4685 case Type::STK_CPointer: 4686 case Type::STK_ObjCObjectPointer: 4687 case Type::STK_BlockPointer: 4688 llvm_unreachable("valid float->pointer cast?"); 4689 case Type::STK_MemberPointer: 4690 llvm_unreachable("member pointer type in C"); 4691 } 4692 llvm_unreachable("Should have returned before this"); 4693 4694 case Type::STK_FloatingComplex: 4695 switch (DestTy->getScalarTypeKind()) { 4696 case Type::STK_FloatingComplex: 4697 return CK_FloatingComplexCast; 4698 case Type::STK_IntegralComplex: 4699 return CK_FloatingComplexToIntegralComplex; 4700 case Type::STK_Floating: { 4701 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4702 if (Context.hasSameType(ET, DestTy)) 4703 return CK_FloatingComplexToReal; 4704 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4705 return CK_FloatingCast; 4706 } 4707 case Type::STK_Bool: 4708 return CK_FloatingComplexToBoolean; 4709 case Type::STK_Integral: 4710 Src = ImpCastExprToType(Src.take(), 4711 SrcTy->castAs<ComplexType>()->getElementType(), 4712 CK_FloatingComplexToReal); 4713 return CK_FloatingToIntegral; 4714 case Type::STK_CPointer: 4715 case Type::STK_ObjCObjectPointer: 4716 case Type::STK_BlockPointer: 4717 llvm_unreachable("valid complex float->pointer cast?"); 4718 case Type::STK_MemberPointer: 4719 llvm_unreachable("member pointer type in C"); 4720 } 4721 llvm_unreachable("Should have returned before this"); 4722 4723 case Type::STK_IntegralComplex: 4724 switch (DestTy->getScalarTypeKind()) { 4725 case Type::STK_FloatingComplex: 4726 return CK_IntegralComplexToFloatingComplex; 4727 case Type::STK_IntegralComplex: 4728 return CK_IntegralComplexCast; 4729 case Type::STK_Integral: { 4730 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4731 if (Context.hasSameType(ET, DestTy)) 4732 return CK_IntegralComplexToReal; 4733 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4734 return CK_IntegralCast; 4735 } 4736 case Type::STK_Bool: 4737 return CK_IntegralComplexToBoolean; 4738 case Type::STK_Floating: 4739 Src = ImpCastExprToType(Src.take(), 4740 SrcTy->castAs<ComplexType>()->getElementType(), 4741 CK_IntegralComplexToReal); 4742 return CK_IntegralToFloating; 4743 case Type::STK_CPointer: 4744 case Type::STK_ObjCObjectPointer: 4745 case Type::STK_BlockPointer: 4746 llvm_unreachable("valid complex int->pointer cast?"); 4747 case Type::STK_MemberPointer: 4748 llvm_unreachable("member pointer type in C"); 4749 } 4750 llvm_unreachable("Should have returned before this"); 4751 } 4752 4753 llvm_unreachable("Unhandled scalar cast"); 4754 } 4755 4756 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4757 CastKind &Kind) { 4758 assert(VectorTy->isVectorType() && "Not a vector type!"); 4759 4760 if (Ty->isVectorType() || Ty->isIntegerType()) { 4761 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4762 return Diag(R.getBegin(), 4763 Ty->isVectorType() ? 4764 diag::err_invalid_conversion_between_vectors : 4765 diag::err_invalid_conversion_between_vector_and_integer) 4766 << VectorTy << Ty << R; 4767 } else 4768 return Diag(R.getBegin(), 4769 diag::err_invalid_conversion_between_vector_and_scalar) 4770 << VectorTy << Ty << R; 4771 4772 Kind = CK_BitCast; 4773 return false; 4774 } 4775 4776 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4777 Expr *CastExpr, CastKind &Kind) { 4778 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4779 4780 QualType SrcTy = CastExpr->getType(); 4781 4782 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4783 // an ExtVectorType. 4784 // In OpenCL, casts between vectors of different types are not allowed. 4785 // (See OpenCL 6.2). 4786 if (SrcTy->isVectorType()) { 4787 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4788 || (getLangOpts().OpenCL && 4789 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4790 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4791 << DestTy << SrcTy << R; 4792 return ExprError(); 4793 } 4794 Kind = CK_BitCast; 4795 return Owned(CastExpr); 4796 } 4797 4798 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4799 // conversion will take place first from scalar to elt type, and then 4800 // splat from elt type to vector. 4801 if (SrcTy->isPointerType()) 4802 return Diag(R.getBegin(), 4803 diag::err_invalid_conversion_between_vector_and_scalar) 4804 << DestTy << SrcTy << R; 4805 4806 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4807 ExprResult CastExprRes = Owned(CastExpr); 4808 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4809 if (CastExprRes.isInvalid()) 4810 return ExprError(); 4811 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4812 4813 Kind = CK_VectorSplat; 4814 return Owned(CastExpr); 4815 } 4816 4817 ExprResult 4818 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4819 Declarator &D, ParsedType &Ty, 4820 SourceLocation RParenLoc, Expr *CastExpr) { 4821 assert(!D.isInvalidType() && (CastExpr != 0) && 4822 "ActOnCastExpr(): missing type or expr"); 4823 4824 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4825 if (D.isInvalidType()) 4826 return ExprError(); 4827 4828 if (getLangOpts().CPlusPlus) { 4829 // Check that there are no default arguments (C++ only). 4830 CheckExtraCXXDefaultArguments(D); 4831 } 4832 4833 checkUnusedDeclAttributes(D); 4834 4835 QualType castType = castTInfo->getType(); 4836 Ty = CreateParsedType(castType, castTInfo); 4837 4838 bool isVectorLiteral = false; 4839 4840 // Check for an altivec or OpenCL literal, 4841 // i.e. all the elements are integer constants. 4842 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4843 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4844 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 4845 && castType->isVectorType() && (PE || PLE)) { 4846 if (PLE && PLE->getNumExprs() == 0) { 4847 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4848 return ExprError(); 4849 } 4850 if (PE || PLE->getNumExprs() == 1) { 4851 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4852 if (!E->getType()->isVectorType()) 4853 isVectorLiteral = true; 4854 } 4855 else 4856 isVectorLiteral = true; 4857 } 4858 4859 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4860 // then handle it as such. 4861 if (isVectorLiteral) 4862 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4863 4864 // If the Expr being casted is a ParenListExpr, handle it specially. 4865 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4866 // sequence of BinOp comma operators. 4867 if (isa<ParenListExpr>(CastExpr)) { 4868 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4869 if (Result.isInvalid()) return ExprError(); 4870 CastExpr = Result.take(); 4871 } 4872 4873 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4874 } 4875 4876 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4877 SourceLocation RParenLoc, Expr *E, 4878 TypeSourceInfo *TInfo) { 4879 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4880 "Expected paren or paren list expression"); 4881 4882 Expr **exprs; 4883 unsigned numExprs; 4884 Expr *subExpr; 4885 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 4886 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4887 LiteralLParenLoc = PE->getLParenLoc(); 4888 LiteralRParenLoc = PE->getRParenLoc(); 4889 exprs = PE->getExprs(); 4890 numExprs = PE->getNumExprs(); 4891 } else { // isa<ParenExpr> by assertion at function entrance 4892 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 4893 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 4894 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4895 exprs = &subExpr; 4896 numExprs = 1; 4897 } 4898 4899 QualType Ty = TInfo->getType(); 4900 assert(Ty->isVectorType() && "Expected vector type"); 4901 4902 SmallVector<Expr *, 8> initExprs; 4903 const VectorType *VTy = Ty->getAs<VectorType>(); 4904 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4905 4906 // '(...)' form of vector initialization in AltiVec: the number of 4907 // initializers must be one or must match the size of the vector. 4908 // If a single value is specified in the initializer then it will be 4909 // replicated to all the components of the vector 4910 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4911 // The number of initializers must be one or must match the size of the 4912 // vector. If a single value is specified in the initializer then it will 4913 // be replicated to all the components of the vector 4914 if (numExprs == 1) { 4915 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4916 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4917 if (Literal.isInvalid()) 4918 return ExprError(); 4919 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4920 PrepareScalarCast(Literal, ElemTy)); 4921 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4922 } 4923 else if (numExprs < numElems) { 4924 Diag(E->getExprLoc(), 4925 diag::err_incorrect_number_of_vector_initializers); 4926 return ExprError(); 4927 } 4928 else 4929 initExprs.append(exprs, exprs + numExprs); 4930 } 4931 else { 4932 // For OpenCL, when the number of initializers is a single value, 4933 // it will be replicated to all components of the vector. 4934 if (getLangOpts().OpenCL && 4935 VTy->getVectorKind() == VectorType::GenericVector && 4936 numExprs == 1) { 4937 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4938 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4939 if (Literal.isInvalid()) 4940 return ExprError(); 4941 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4942 PrepareScalarCast(Literal, ElemTy)); 4943 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4944 } 4945 4946 initExprs.append(exprs, exprs + numExprs); 4947 } 4948 // FIXME: This means that pretty-printing the final AST will produce curly 4949 // braces instead of the original commas. 4950 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 4951 initExprs, LiteralRParenLoc); 4952 initE->setType(Ty); 4953 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4954 } 4955 4956 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 4957 /// the ParenListExpr into a sequence of comma binary operators. 4958 ExprResult 4959 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4960 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4961 if (!E) 4962 return Owned(OrigExpr); 4963 4964 ExprResult Result(E->getExpr(0)); 4965 4966 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4967 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4968 E->getExpr(i)); 4969 4970 if (Result.isInvalid()) return ExprError(); 4971 4972 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4973 } 4974 4975 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 4976 SourceLocation R, 4977 MultiExprArg Val) { 4978 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 4979 return Owned(expr); 4980 } 4981 4982 /// \brief Emit a specialized diagnostic when one expression is a null pointer 4983 /// constant and the other is not a pointer. Returns true if a diagnostic is 4984 /// emitted. 4985 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4986 SourceLocation QuestionLoc) { 4987 Expr *NullExpr = LHSExpr; 4988 Expr *NonPointerExpr = RHSExpr; 4989 Expr::NullPointerConstantKind NullKind = 4990 NullExpr->isNullPointerConstant(Context, 4991 Expr::NPC_ValueDependentIsNotNull); 4992 4993 if (NullKind == Expr::NPCK_NotNull) { 4994 NullExpr = RHSExpr; 4995 NonPointerExpr = LHSExpr; 4996 NullKind = 4997 NullExpr->isNullPointerConstant(Context, 4998 Expr::NPC_ValueDependentIsNotNull); 4999 } 5000 5001 if (NullKind == Expr::NPCK_NotNull) 5002 return false; 5003 5004 if (NullKind == Expr::NPCK_ZeroExpression) 5005 return false; 5006 5007 if (NullKind == Expr::NPCK_ZeroLiteral) { 5008 // In this case, check to make sure that we got here from a "NULL" 5009 // string in the source code. 5010 NullExpr = NullExpr->IgnoreParenImpCasts(); 5011 SourceLocation loc = NullExpr->getExprLoc(); 5012 if (!findMacroSpelling(loc, "NULL")) 5013 return false; 5014 } 5015 5016 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5017 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5018 << NonPointerExpr->getType() << DiagType 5019 << NonPointerExpr->getSourceRange(); 5020 return true; 5021 } 5022 5023 /// \brief Return false if the condition expression is valid, true otherwise. 5024 static bool checkCondition(Sema &S, Expr *Cond) { 5025 QualType CondTy = Cond->getType(); 5026 5027 // C99 6.5.15p2 5028 if (CondTy->isScalarType()) return false; 5029 5030 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5031 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5032 return false; 5033 5034 // Emit the proper error message. 5035 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5036 diag::err_typecheck_cond_expect_scalar : 5037 diag::err_typecheck_cond_expect_scalar_or_vector) 5038 << CondTy; 5039 return true; 5040 } 5041 5042 /// \brief Return false if the two expressions can be converted to a vector, 5043 /// true otherwise 5044 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5045 ExprResult &RHS, 5046 QualType CondTy) { 5047 // Both operands should be of scalar type. 5048 if (!LHS.get()->getType()->isScalarType()) { 5049 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5050 << CondTy; 5051 return true; 5052 } 5053 if (!RHS.get()->getType()->isScalarType()) { 5054 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5055 << CondTy; 5056 return true; 5057 } 5058 5059 // Implicity convert these scalars to the type of the condition. 5060 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5061 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5062 return false; 5063 } 5064 5065 /// \brief Handle when one or both operands are void type. 5066 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5067 ExprResult &RHS) { 5068 Expr *LHSExpr = LHS.get(); 5069 Expr *RHSExpr = RHS.get(); 5070 5071 if (!LHSExpr->getType()->isVoidType()) 5072 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5073 << RHSExpr->getSourceRange(); 5074 if (!RHSExpr->getType()->isVoidType()) 5075 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5076 << LHSExpr->getSourceRange(); 5077 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5078 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5079 return S.Context.VoidTy; 5080 } 5081 5082 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5083 /// true otherwise. 5084 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5085 QualType PointerTy) { 5086 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5087 !NullExpr.get()->isNullPointerConstant(S.Context, 5088 Expr::NPC_ValueDependentIsNull)) 5089 return true; 5090 5091 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5092 return false; 5093 } 5094 5095 /// \brief Checks compatibility between two pointers and return the resulting 5096 /// type. 5097 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5098 ExprResult &RHS, 5099 SourceLocation Loc) { 5100 QualType LHSTy = LHS.get()->getType(); 5101 QualType RHSTy = RHS.get()->getType(); 5102 5103 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5104 // Two identical pointers types are always compatible. 5105 return LHSTy; 5106 } 5107 5108 QualType lhptee, rhptee; 5109 5110 // Get the pointee types. 5111 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5112 lhptee = LHSBTy->getPointeeType(); 5113 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5114 } else { 5115 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5116 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5117 } 5118 5119 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5120 // differently qualified versions of compatible types, the result type is 5121 // a pointer to an appropriately qualified version of the composite 5122 // type. 5123 5124 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5125 // clause doesn't make sense for our extensions. E.g. address space 2 should 5126 // be incompatible with address space 3: they may live on different devices or 5127 // anything. 5128 Qualifiers lhQual = lhptee.getQualifiers(); 5129 Qualifiers rhQual = rhptee.getQualifiers(); 5130 5131 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5132 lhQual.removeCVRQualifiers(); 5133 rhQual.removeCVRQualifiers(); 5134 5135 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5136 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5137 5138 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5139 5140 if (CompositeTy.isNull()) { 5141 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5142 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5143 << RHS.get()->getSourceRange(); 5144 // In this situation, we assume void* type. No especially good 5145 // reason, but this is what gcc does, and we do have to pick 5146 // to get a consistent AST. 5147 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5148 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5149 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5150 return incompatTy; 5151 } 5152 5153 // The pointer types are compatible. 5154 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5155 ResultTy = S.Context.getPointerType(ResultTy); 5156 5157 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5158 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5159 return ResultTy; 5160 } 5161 5162 /// \brief Return the resulting type when the operands are both block pointers. 5163 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5164 ExprResult &LHS, 5165 ExprResult &RHS, 5166 SourceLocation Loc) { 5167 QualType LHSTy = LHS.get()->getType(); 5168 QualType RHSTy = RHS.get()->getType(); 5169 5170 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5171 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5172 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5173 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5174 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5175 return destType; 5176 } 5177 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5178 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5179 << RHS.get()->getSourceRange(); 5180 return QualType(); 5181 } 5182 5183 // We have 2 block pointer types. 5184 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5185 } 5186 5187 /// \brief Return the resulting type when the operands are both pointers. 5188 static QualType 5189 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5190 ExprResult &RHS, 5191 SourceLocation Loc) { 5192 // get the pointer types 5193 QualType LHSTy = LHS.get()->getType(); 5194 QualType RHSTy = RHS.get()->getType(); 5195 5196 // get the "pointed to" types 5197 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5198 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5199 5200 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5201 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5202 // Figure out necessary qualifiers (C99 6.5.15p6) 5203 QualType destPointee 5204 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5205 QualType destType = S.Context.getPointerType(destPointee); 5206 // Add qualifiers if necessary. 5207 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5208 // Promote to void*. 5209 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5210 return destType; 5211 } 5212 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5213 QualType destPointee 5214 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5215 QualType destType = S.Context.getPointerType(destPointee); 5216 // Add qualifiers if necessary. 5217 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5218 // Promote to void*. 5219 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5220 return destType; 5221 } 5222 5223 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5224 } 5225 5226 /// \brief Return false if the first expression is not an integer and the second 5227 /// expression is not a pointer, true otherwise. 5228 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5229 Expr* PointerExpr, SourceLocation Loc, 5230 bool IsIntFirstExpr) { 5231 if (!PointerExpr->getType()->isPointerType() || 5232 !Int.get()->getType()->isIntegerType()) 5233 return false; 5234 5235 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5236 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5237 5238 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5239 << Expr1->getType() << Expr2->getType() 5240 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5241 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5242 CK_IntegralToPointer); 5243 return true; 5244 } 5245 5246 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5247 /// In that case, LHS = cond. 5248 /// C99 6.5.15 5249 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5250 ExprResult &RHS, ExprValueKind &VK, 5251 ExprObjectKind &OK, 5252 SourceLocation QuestionLoc) { 5253 5254 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5255 if (!LHSResult.isUsable()) return QualType(); 5256 LHS = LHSResult; 5257 5258 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5259 if (!RHSResult.isUsable()) return QualType(); 5260 RHS = RHSResult; 5261 5262 // C++ is sufficiently different to merit its own checker. 5263 if (getLangOpts().CPlusPlus) 5264 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5265 5266 VK = VK_RValue; 5267 OK = OK_Ordinary; 5268 5269 Cond = UsualUnaryConversions(Cond.take()); 5270 if (Cond.isInvalid()) 5271 return QualType(); 5272 LHS = UsualUnaryConversions(LHS.take()); 5273 if (LHS.isInvalid()) 5274 return QualType(); 5275 RHS = UsualUnaryConversions(RHS.take()); 5276 if (RHS.isInvalid()) 5277 return QualType(); 5278 5279 QualType CondTy = Cond.get()->getType(); 5280 QualType LHSTy = LHS.get()->getType(); 5281 QualType RHSTy = RHS.get()->getType(); 5282 5283 // first, check the condition. 5284 if (checkCondition(*this, Cond.get())) 5285 return QualType(); 5286 5287 // Now check the two expressions. 5288 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 5289 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5290 5291 // If the condition is a vector, and both operands are scalar, 5292 // attempt to implicity convert them to the vector type to act like the 5293 // built in select. (OpenCL v1.1 s6.3.i) 5294 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5295 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5296 return QualType(); 5297 5298 // If both operands have arithmetic type, do the usual arithmetic conversions 5299 // to find a common type: C99 6.5.15p3,5. 5300 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 5301 UsualArithmeticConversions(LHS, RHS); 5302 if (LHS.isInvalid() || RHS.isInvalid()) 5303 return QualType(); 5304 return LHS.get()->getType(); 5305 } 5306 5307 // If both operands are the same structure or union type, the result is that 5308 // type. 5309 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5310 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5311 if (LHSRT->getDecl() == RHSRT->getDecl()) 5312 // "If both the operands have structure or union type, the result has 5313 // that type." This implies that CV qualifiers are dropped. 5314 return LHSTy.getUnqualifiedType(); 5315 // FIXME: Type of conditional expression must be complete in C mode. 5316 } 5317 5318 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5319 // The following || allows only one side to be void (a GCC-ism). 5320 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5321 return checkConditionalVoidType(*this, LHS, RHS); 5322 } 5323 5324 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5325 // the type of the other operand." 5326 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5327 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5328 5329 // All objective-c pointer type analysis is done here. 5330 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5331 QuestionLoc); 5332 if (LHS.isInvalid() || RHS.isInvalid()) 5333 return QualType(); 5334 if (!compositeType.isNull()) 5335 return compositeType; 5336 5337 5338 // Handle block pointer types. 5339 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5340 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5341 QuestionLoc); 5342 5343 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5344 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5345 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5346 QuestionLoc); 5347 5348 // GCC compatibility: soften pointer/integer mismatch. Note that 5349 // null pointers have been filtered out by this point. 5350 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5351 /*isIntFirstExpr=*/true)) 5352 return RHSTy; 5353 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5354 /*isIntFirstExpr=*/false)) 5355 return LHSTy; 5356 5357 // Emit a better diagnostic if one of the expressions is a null pointer 5358 // constant and the other is not a pointer type. In this case, the user most 5359 // likely forgot to take the address of the other expression. 5360 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5361 return QualType(); 5362 5363 // Otherwise, the operands are not compatible. 5364 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5365 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5366 << RHS.get()->getSourceRange(); 5367 return QualType(); 5368 } 5369 5370 /// FindCompositeObjCPointerType - Helper method to find composite type of 5371 /// two objective-c pointer types of the two input expressions. 5372 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5373 SourceLocation QuestionLoc) { 5374 QualType LHSTy = LHS.get()->getType(); 5375 QualType RHSTy = RHS.get()->getType(); 5376 5377 // Handle things like Class and struct objc_class*. Here we case the result 5378 // to the pseudo-builtin, because that will be implicitly cast back to the 5379 // redefinition type if an attempt is made to access its fields. 5380 if (LHSTy->isObjCClassType() && 5381 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5382 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5383 return LHSTy; 5384 } 5385 if (RHSTy->isObjCClassType() && 5386 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5387 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5388 return RHSTy; 5389 } 5390 // And the same for struct objc_object* / id 5391 if (LHSTy->isObjCIdType() && 5392 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5393 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5394 return LHSTy; 5395 } 5396 if (RHSTy->isObjCIdType() && 5397 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5398 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5399 return RHSTy; 5400 } 5401 // And the same for struct objc_selector* / SEL 5402 if (Context.isObjCSelType(LHSTy) && 5403 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5404 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5405 return LHSTy; 5406 } 5407 if (Context.isObjCSelType(RHSTy) && 5408 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5409 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5410 return RHSTy; 5411 } 5412 // Check constraints for Objective-C object pointers types. 5413 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5414 5415 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5416 // Two identical object pointer types are always compatible. 5417 return LHSTy; 5418 } 5419 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5420 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5421 QualType compositeType = LHSTy; 5422 5423 // If both operands are interfaces and either operand can be 5424 // assigned to the other, use that type as the composite 5425 // type. This allows 5426 // xxx ? (A*) a : (B*) b 5427 // where B is a subclass of A. 5428 // 5429 // Additionally, as for assignment, if either type is 'id' 5430 // allow silent coercion. Finally, if the types are 5431 // incompatible then make sure to use 'id' as the composite 5432 // type so the result is acceptable for sending messages to. 5433 5434 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5435 // It could return the composite type. 5436 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5437 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5438 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5439 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5440 } else if ((LHSTy->isObjCQualifiedIdType() || 5441 RHSTy->isObjCQualifiedIdType()) && 5442 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5443 // Need to handle "id<xx>" explicitly. 5444 // GCC allows qualified id and any Objective-C type to devolve to 5445 // id. Currently localizing to here until clear this should be 5446 // part of ObjCQualifiedIdTypesAreCompatible. 5447 compositeType = Context.getObjCIdType(); 5448 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5449 compositeType = Context.getObjCIdType(); 5450 } else if (!(compositeType = 5451 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5452 ; 5453 else { 5454 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5455 << LHSTy << RHSTy 5456 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5457 QualType incompatTy = Context.getObjCIdType(); 5458 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5459 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5460 return incompatTy; 5461 } 5462 // The object pointer types are compatible. 5463 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5464 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5465 return compositeType; 5466 } 5467 // Check Objective-C object pointer types and 'void *' 5468 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5469 if (getLangOpts().ObjCAutoRefCount) { 5470 // ARC forbids the implicit conversion of object pointers to 'void *', 5471 // so these types are not compatible. 5472 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5473 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5474 LHS = RHS = true; 5475 return QualType(); 5476 } 5477 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5478 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5479 QualType destPointee 5480 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5481 QualType destType = Context.getPointerType(destPointee); 5482 // Add qualifiers if necessary. 5483 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5484 // Promote to void*. 5485 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5486 return destType; 5487 } 5488 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5489 if (getLangOpts().ObjCAutoRefCount) { 5490 // ARC forbids the implicit conversion of object pointers to 'void *', 5491 // so these types are not compatible. 5492 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5493 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5494 LHS = RHS = true; 5495 return QualType(); 5496 } 5497 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5498 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5499 QualType destPointee 5500 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5501 QualType destType = Context.getPointerType(destPointee); 5502 // Add qualifiers if necessary. 5503 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5504 // Promote to void*. 5505 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5506 return destType; 5507 } 5508 return QualType(); 5509 } 5510 5511 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5512 /// ParenRange in parentheses. 5513 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5514 const PartialDiagnostic &Note, 5515 SourceRange ParenRange) { 5516 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5517 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5518 EndLoc.isValid()) { 5519 Self.Diag(Loc, Note) 5520 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5521 << FixItHint::CreateInsertion(EndLoc, ")"); 5522 } else { 5523 // We can't display the parentheses, so just show the bare note. 5524 Self.Diag(Loc, Note) << ParenRange; 5525 } 5526 } 5527 5528 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5529 return Opc >= BO_Mul && Opc <= BO_Shr; 5530 } 5531 5532 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5533 /// expression, either using a built-in or overloaded operator, 5534 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5535 /// expression. 5536 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5537 Expr **RHSExprs) { 5538 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5539 E = E->IgnoreImpCasts(); 5540 E = E->IgnoreConversionOperator(); 5541 E = E->IgnoreImpCasts(); 5542 5543 // Built-in binary operator. 5544 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5545 if (IsArithmeticOp(OP->getOpcode())) { 5546 *Opcode = OP->getOpcode(); 5547 *RHSExprs = OP->getRHS(); 5548 return true; 5549 } 5550 } 5551 5552 // Overloaded operator. 5553 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5554 if (Call->getNumArgs() != 2) 5555 return false; 5556 5557 // Make sure this is really a binary operator that is safe to pass into 5558 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5559 OverloadedOperatorKind OO = Call->getOperator(); 5560 if (OO < OO_Plus || OO > OO_Arrow || 5561 OO == OO_PlusPlus || OO == OO_MinusMinus) 5562 return false; 5563 5564 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5565 if (IsArithmeticOp(OpKind)) { 5566 *Opcode = OpKind; 5567 *RHSExprs = Call->getArg(1); 5568 return true; 5569 } 5570 } 5571 5572 return false; 5573 } 5574 5575 static bool IsLogicOp(BinaryOperatorKind Opc) { 5576 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5577 } 5578 5579 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5580 /// or is a logical expression such as (x==y) which has int type, but is 5581 /// commonly interpreted as boolean. 5582 static bool ExprLooksBoolean(Expr *E) { 5583 E = E->IgnoreParenImpCasts(); 5584 5585 if (E->getType()->isBooleanType()) 5586 return true; 5587 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5588 return IsLogicOp(OP->getOpcode()); 5589 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5590 return OP->getOpcode() == UO_LNot; 5591 5592 return false; 5593 } 5594 5595 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5596 /// and binary operator are mixed in a way that suggests the programmer assumed 5597 /// the conditional operator has higher precedence, for example: 5598 /// "int x = a + someBinaryCondition ? 1 : 2". 5599 static void DiagnoseConditionalPrecedence(Sema &Self, 5600 SourceLocation OpLoc, 5601 Expr *Condition, 5602 Expr *LHSExpr, 5603 Expr *RHSExpr) { 5604 BinaryOperatorKind CondOpcode; 5605 Expr *CondRHS; 5606 5607 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5608 return; 5609 if (!ExprLooksBoolean(CondRHS)) 5610 return; 5611 5612 // The condition is an arithmetic binary expression, with a right- 5613 // hand side that looks boolean, so warn. 5614 5615 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5616 << Condition->getSourceRange() 5617 << BinaryOperator::getOpcodeStr(CondOpcode); 5618 5619 SuggestParentheses(Self, OpLoc, 5620 Self.PDiag(diag::note_precedence_silence) 5621 << BinaryOperator::getOpcodeStr(CondOpcode), 5622 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5623 5624 SuggestParentheses(Self, OpLoc, 5625 Self.PDiag(diag::note_precedence_conditional_first), 5626 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5627 } 5628 5629 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5630 /// in the case of a the GNU conditional expr extension. 5631 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5632 SourceLocation ColonLoc, 5633 Expr *CondExpr, Expr *LHSExpr, 5634 Expr *RHSExpr) { 5635 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5636 // was the condition. 5637 OpaqueValueExpr *opaqueValue = 0; 5638 Expr *commonExpr = 0; 5639 if (LHSExpr == 0) { 5640 commonExpr = CondExpr; 5641 5642 // We usually want to apply unary conversions *before* saving, except 5643 // in the special case of a C++ l-value conditional. 5644 if (!(getLangOpts().CPlusPlus 5645 && !commonExpr->isTypeDependent() 5646 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5647 && commonExpr->isGLValue() 5648 && commonExpr->isOrdinaryOrBitFieldObject() 5649 && RHSExpr->isOrdinaryOrBitFieldObject() 5650 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5651 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5652 if (commonRes.isInvalid()) 5653 return ExprError(); 5654 commonExpr = commonRes.take(); 5655 } 5656 5657 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5658 commonExpr->getType(), 5659 commonExpr->getValueKind(), 5660 commonExpr->getObjectKind(), 5661 commonExpr); 5662 LHSExpr = CondExpr = opaqueValue; 5663 } 5664 5665 ExprValueKind VK = VK_RValue; 5666 ExprObjectKind OK = OK_Ordinary; 5667 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5668 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5669 VK, OK, QuestionLoc); 5670 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5671 RHS.isInvalid()) 5672 return ExprError(); 5673 5674 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5675 RHS.get()); 5676 5677 if (!commonExpr) 5678 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5679 LHS.take(), ColonLoc, 5680 RHS.take(), result, VK, OK)); 5681 5682 return Owned(new (Context) 5683 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5684 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5685 OK)); 5686 } 5687 5688 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5689 // being closely modeled after the C99 spec:-). The odd characteristic of this 5690 // routine is it effectively iqnores the qualifiers on the top level pointee. 5691 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5692 // FIXME: add a couple examples in this comment. 5693 static Sema::AssignConvertType 5694 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5695 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5696 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5697 5698 // get the "pointed to" type (ignoring qualifiers at the top level) 5699 const Type *lhptee, *rhptee; 5700 Qualifiers lhq, rhq; 5701 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5702 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5703 5704 Sema::AssignConvertType ConvTy = Sema::Compatible; 5705 5706 // C99 6.5.16.1p1: This following citation is common to constraints 5707 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5708 // qualifiers of the type *pointed to* by the right; 5709 Qualifiers lq; 5710 5711 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5712 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5713 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5714 // Ignore lifetime for further calculation. 5715 lhq.removeObjCLifetime(); 5716 rhq.removeObjCLifetime(); 5717 } 5718 5719 if (!lhq.compatiblyIncludes(rhq)) { 5720 // Treat address-space mismatches as fatal. TODO: address subspaces 5721 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5722 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5723 5724 // It's okay to add or remove GC or lifetime qualifiers when converting to 5725 // and from void*. 5726 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5727 .compatiblyIncludes( 5728 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5729 && (lhptee->isVoidType() || rhptee->isVoidType())) 5730 ; // keep old 5731 5732 // Treat lifetime mismatches as fatal. 5733 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5734 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5735 5736 // For GCC compatibility, other qualifier mismatches are treated 5737 // as still compatible in C. 5738 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5739 } 5740 5741 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5742 // incomplete type and the other is a pointer to a qualified or unqualified 5743 // version of void... 5744 if (lhptee->isVoidType()) { 5745 if (rhptee->isIncompleteOrObjectType()) 5746 return ConvTy; 5747 5748 // As an extension, we allow cast to/from void* to function pointer. 5749 assert(rhptee->isFunctionType()); 5750 return Sema::FunctionVoidPointer; 5751 } 5752 5753 if (rhptee->isVoidType()) { 5754 if (lhptee->isIncompleteOrObjectType()) 5755 return ConvTy; 5756 5757 // As an extension, we allow cast to/from void* to function pointer. 5758 assert(lhptee->isFunctionType()); 5759 return Sema::FunctionVoidPointer; 5760 } 5761 5762 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5763 // unqualified versions of compatible types, ... 5764 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5765 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5766 // Check if the pointee types are compatible ignoring the sign. 5767 // We explicitly check for char so that we catch "char" vs 5768 // "unsigned char" on systems where "char" is unsigned. 5769 if (lhptee->isCharType()) 5770 ltrans = S.Context.UnsignedCharTy; 5771 else if (lhptee->hasSignedIntegerRepresentation()) 5772 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5773 5774 if (rhptee->isCharType()) 5775 rtrans = S.Context.UnsignedCharTy; 5776 else if (rhptee->hasSignedIntegerRepresentation()) 5777 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5778 5779 if (ltrans == rtrans) { 5780 // Types are compatible ignoring the sign. Qualifier incompatibility 5781 // takes priority over sign incompatibility because the sign 5782 // warning can be disabled. 5783 if (ConvTy != Sema::Compatible) 5784 return ConvTy; 5785 5786 return Sema::IncompatiblePointerSign; 5787 } 5788 5789 // If we are a multi-level pointer, it's possible that our issue is simply 5790 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5791 // the eventual target type is the same and the pointers have the same 5792 // level of indirection, this must be the issue. 5793 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5794 do { 5795 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5796 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5797 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5798 5799 if (lhptee == rhptee) 5800 return Sema::IncompatibleNestedPointerQualifiers; 5801 } 5802 5803 // General pointer incompatibility takes priority over qualifiers. 5804 return Sema::IncompatiblePointer; 5805 } 5806 if (!S.getLangOpts().CPlusPlus && 5807 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5808 return Sema::IncompatiblePointer; 5809 return ConvTy; 5810 } 5811 5812 /// checkBlockPointerTypesForAssignment - This routine determines whether two 5813 /// block pointer types are compatible or whether a block and normal pointer 5814 /// are compatible. It is more restrict than comparing two function pointer 5815 // types. 5816 static Sema::AssignConvertType 5817 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5818 QualType RHSType) { 5819 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5820 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5821 5822 QualType lhptee, rhptee; 5823 5824 // get the "pointed to" type (ignoring qualifiers at the top level) 5825 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5826 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5827 5828 // In C++, the types have to match exactly. 5829 if (S.getLangOpts().CPlusPlus) 5830 return Sema::IncompatibleBlockPointer; 5831 5832 Sema::AssignConvertType ConvTy = Sema::Compatible; 5833 5834 // For blocks we enforce that qualifiers are identical. 5835 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5836 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5837 5838 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5839 return Sema::IncompatibleBlockPointer; 5840 5841 return ConvTy; 5842 } 5843 5844 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5845 /// for assignment compatibility. 5846 static Sema::AssignConvertType 5847 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5848 QualType RHSType) { 5849 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5850 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5851 5852 if (LHSType->isObjCBuiltinType()) { 5853 // Class is not compatible with ObjC object pointers. 5854 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5855 !RHSType->isObjCQualifiedClassType()) 5856 return Sema::IncompatiblePointer; 5857 return Sema::Compatible; 5858 } 5859 if (RHSType->isObjCBuiltinType()) { 5860 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5861 !LHSType->isObjCQualifiedClassType()) 5862 return Sema::IncompatiblePointer; 5863 return Sema::Compatible; 5864 } 5865 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5866 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5867 5868 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 5869 // make an exception for id<P> 5870 !LHSType->isObjCQualifiedIdType()) 5871 return Sema::CompatiblePointerDiscardsQualifiers; 5872 5873 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5874 return Sema::Compatible; 5875 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5876 return Sema::IncompatibleObjCQualifiedId; 5877 return Sema::IncompatiblePointer; 5878 } 5879 5880 Sema::AssignConvertType 5881 Sema::CheckAssignmentConstraints(SourceLocation Loc, 5882 QualType LHSType, QualType RHSType) { 5883 // Fake up an opaque expression. We don't actually care about what 5884 // cast operations are required, so if CheckAssignmentConstraints 5885 // adds casts to this they'll be wasted, but fortunately that doesn't 5886 // usually happen on valid code. 5887 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5888 ExprResult RHSPtr = &RHSExpr; 5889 CastKind K = CK_Invalid; 5890 5891 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5892 } 5893 5894 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5895 /// has code to accommodate several GCC extensions when type checking 5896 /// pointers. Here are some objectionable examples that GCC considers warnings: 5897 /// 5898 /// int a, *pint; 5899 /// short *pshort; 5900 /// struct foo *pfoo; 5901 /// 5902 /// pint = pshort; // warning: assignment from incompatible pointer type 5903 /// a = pint; // warning: assignment makes integer from pointer without a cast 5904 /// pint = a; // warning: assignment makes pointer from integer without a cast 5905 /// pint = pfoo; // warning: assignment from incompatible pointer type 5906 /// 5907 /// As a result, the code for dealing with pointers is more complex than the 5908 /// C99 spec dictates. 5909 /// 5910 /// Sets 'Kind' for any result kind except Incompatible. 5911 Sema::AssignConvertType 5912 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5913 CastKind &Kind) { 5914 QualType RHSType = RHS.get()->getType(); 5915 QualType OrigLHSType = LHSType; 5916 5917 // Get canonical types. We're not formatting these types, just comparing 5918 // them. 5919 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5920 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5921 5922 // Common case: no conversion required. 5923 if (LHSType == RHSType) { 5924 Kind = CK_NoOp; 5925 return Compatible; 5926 } 5927 5928 // If we have an atomic type, try a non-atomic assignment, then just add an 5929 // atomic qualification step. 5930 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 5931 Sema::AssignConvertType result = 5932 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 5933 if (result != Compatible) 5934 return result; 5935 if (Kind != CK_NoOp) 5936 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 5937 Kind = CK_NonAtomicToAtomic; 5938 return Compatible; 5939 } 5940 5941 // If the left-hand side is a reference type, then we are in a 5942 // (rare!) case where we've allowed the use of references in C, 5943 // e.g., as a parameter type in a built-in function. In this case, 5944 // just make sure that the type referenced is compatible with the 5945 // right-hand side type. The caller is responsible for adjusting 5946 // LHSType so that the resulting expression does not have reference 5947 // type. 5948 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5949 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5950 Kind = CK_LValueBitCast; 5951 return Compatible; 5952 } 5953 return Incompatible; 5954 } 5955 5956 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5957 // to the same ExtVector type. 5958 if (LHSType->isExtVectorType()) { 5959 if (RHSType->isExtVectorType()) 5960 return Incompatible; 5961 if (RHSType->isArithmeticType()) { 5962 // CK_VectorSplat does T -> vector T, so first cast to the 5963 // element type. 5964 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5965 if (elType != RHSType) { 5966 Kind = PrepareScalarCast(RHS, elType); 5967 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5968 } 5969 Kind = CK_VectorSplat; 5970 return Compatible; 5971 } 5972 } 5973 5974 // Conversions to or from vector type. 5975 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5976 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5977 // Allow assignments of an AltiVec vector type to an equivalent GCC 5978 // vector type and vice versa 5979 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5980 Kind = CK_BitCast; 5981 return Compatible; 5982 } 5983 5984 // If we are allowing lax vector conversions, and LHS and RHS are both 5985 // vectors, the total size only needs to be the same. This is a bitcast; 5986 // no bits are changed but the result type is different. 5987 if (getLangOpts().LaxVectorConversions && 5988 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5989 Kind = CK_BitCast; 5990 return IncompatibleVectors; 5991 } 5992 } 5993 return Incompatible; 5994 } 5995 5996 // Arithmetic conversions. 5997 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5998 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 5999 Kind = PrepareScalarCast(RHS, LHSType); 6000 return Compatible; 6001 } 6002 6003 // Conversions to normal pointers. 6004 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6005 // U* -> T* 6006 if (isa<PointerType>(RHSType)) { 6007 Kind = CK_BitCast; 6008 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6009 } 6010 6011 // int -> T* 6012 if (RHSType->isIntegerType()) { 6013 Kind = CK_IntegralToPointer; // FIXME: null? 6014 return IntToPointer; 6015 } 6016 6017 // C pointers are not compatible with ObjC object pointers, 6018 // with two exceptions: 6019 if (isa<ObjCObjectPointerType>(RHSType)) { 6020 // - conversions to void* 6021 if (LHSPointer->getPointeeType()->isVoidType()) { 6022 Kind = CK_BitCast; 6023 return Compatible; 6024 } 6025 6026 // - conversions from 'Class' to the redefinition type 6027 if (RHSType->isObjCClassType() && 6028 Context.hasSameType(LHSType, 6029 Context.getObjCClassRedefinitionType())) { 6030 Kind = CK_BitCast; 6031 return Compatible; 6032 } 6033 6034 Kind = CK_BitCast; 6035 return IncompatiblePointer; 6036 } 6037 6038 // U^ -> void* 6039 if (RHSType->getAs<BlockPointerType>()) { 6040 if (LHSPointer->getPointeeType()->isVoidType()) { 6041 Kind = CK_BitCast; 6042 return Compatible; 6043 } 6044 } 6045 6046 return Incompatible; 6047 } 6048 6049 // Conversions to block pointers. 6050 if (isa<BlockPointerType>(LHSType)) { 6051 // U^ -> T^ 6052 if (RHSType->isBlockPointerType()) { 6053 Kind = CK_BitCast; 6054 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6055 } 6056 6057 // int or null -> T^ 6058 if (RHSType->isIntegerType()) { 6059 Kind = CK_IntegralToPointer; // FIXME: null 6060 return IntToBlockPointer; 6061 } 6062 6063 // id -> T^ 6064 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6065 Kind = CK_AnyPointerToBlockPointerCast; 6066 return Compatible; 6067 } 6068 6069 // void* -> T^ 6070 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6071 if (RHSPT->getPointeeType()->isVoidType()) { 6072 Kind = CK_AnyPointerToBlockPointerCast; 6073 return Compatible; 6074 } 6075 6076 return Incompatible; 6077 } 6078 6079 // Conversions to Objective-C pointers. 6080 if (isa<ObjCObjectPointerType>(LHSType)) { 6081 // A* -> B* 6082 if (RHSType->isObjCObjectPointerType()) { 6083 Kind = CK_BitCast; 6084 Sema::AssignConvertType result = 6085 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6086 if (getLangOpts().ObjCAutoRefCount && 6087 result == Compatible && 6088 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6089 result = IncompatibleObjCWeakRef; 6090 return result; 6091 } 6092 6093 // int or null -> A* 6094 if (RHSType->isIntegerType()) { 6095 Kind = CK_IntegralToPointer; // FIXME: null 6096 return IntToPointer; 6097 } 6098 6099 // In general, C pointers are not compatible with ObjC object pointers, 6100 // with two exceptions: 6101 if (isa<PointerType>(RHSType)) { 6102 Kind = CK_CPointerToObjCPointerCast; 6103 6104 // - conversions from 'void*' 6105 if (RHSType->isVoidPointerType()) { 6106 return Compatible; 6107 } 6108 6109 // - conversions to 'Class' from its redefinition type 6110 if (LHSType->isObjCClassType() && 6111 Context.hasSameType(RHSType, 6112 Context.getObjCClassRedefinitionType())) { 6113 return Compatible; 6114 } 6115 6116 return IncompatiblePointer; 6117 } 6118 6119 // T^ -> A* 6120 if (RHSType->isBlockPointerType()) { 6121 maybeExtendBlockObject(*this, RHS); 6122 Kind = CK_BlockPointerToObjCPointerCast; 6123 return Compatible; 6124 } 6125 6126 return Incompatible; 6127 } 6128 6129 // Conversions from pointers that are not covered by the above. 6130 if (isa<PointerType>(RHSType)) { 6131 // T* -> _Bool 6132 if (LHSType == Context.BoolTy) { 6133 Kind = CK_PointerToBoolean; 6134 return Compatible; 6135 } 6136 6137 // T* -> int 6138 if (LHSType->isIntegerType()) { 6139 Kind = CK_PointerToIntegral; 6140 return PointerToInt; 6141 } 6142 6143 return Incompatible; 6144 } 6145 6146 // Conversions from Objective-C pointers that are not covered by the above. 6147 if (isa<ObjCObjectPointerType>(RHSType)) { 6148 // T* -> _Bool 6149 if (LHSType == Context.BoolTy) { 6150 Kind = CK_PointerToBoolean; 6151 return Compatible; 6152 } 6153 6154 // T* -> int 6155 if (LHSType->isIntegerType()) { 6156 Kind = CK_PointerToIntegral; 6157 return PointerToInt; 6158 } 6159 6160 return Incompatible; 6161 } 6162 6163 // struct A -> struct B 6164 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6165 if (Context.typesAreCompatible(LHSType, RHSType)) { 6166 Kind = CK_NoOp; 6167 return Compatible; 6168 } 6169 } 6170 6171 return Incompatible; 6172 } 6173 6174 /// \brief Constructs a transparent union from an expression that is 6175 /// used to initialize the transparent union. 6176 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6177 ExprResult &EResult, QualType UnionType, 6178 FieldDecl *Field) { 6179 // Build an initializer list that designates the appropriate member 6180 // of the transparent union. 6181 Expr *E = EResult.take(); 6182 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6183 E, SourceLocation()); 6184 Initializer->setType(UnionType); 6185 Initializer->setInitializedFieldInUnion(Field); 6186 6187 // Build a compound literal constructing a value of the transparent 6188 // union type from this initializer list. 6189 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6190 EResult = S.Owned( 6191 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6192 VK_RValue, Initializer, false)); 6193 } 6194 6195 Sema::AssignConvertType 6196 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6197 ExprResult &RHS) { 6198 QualType RHSType = RHS.get()->getType(); 6199 6200 // If the ArgType is a Union type, we want to handle a potential 6201 // transparent_union GCC extension. 6202 const RecordType *UT = ArgType->getAsUnionType(); 6203 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6204 return Incompatible; 6205 6206 // The field to initialize within the transparent union. 6207 RecordDecl *UD = UT->getDecl(); 6208 FieldDecl *InitField = 0; 6209 // It's compatible if the expression matches any of the fields. 6210 for (RecordDecl::field_iterator it = UD->field_begin(), 6211 itend = UD->field_end(); 6212 it != itend; ++it) { 6213 if (it->getType()->isPointerType()) { 6214 // If the transparent union contains a pointer type, we allow: 6215 // 1) void pointer 6216 // 2) null pointer constant 6217 if (RHSType->isPointerType()) 6218 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6219 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6220 InitField = *it; 6221 break; 6222 } 6223 6224 if (RHS.get()->isNullPointerConstant(Context, 6225 Expr::NPC_ValueDependentIsNull)) { 6226 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6227 CK_NullToPointer); 6228 InitField = *it; 6229 break; 6230 } 6231 } 6232 6233 CastKind Kind = CK_Invalid; 6234 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6235 == Compatible) { 6236 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6237 InitField = *it; 6238 break; 6239 } 6240 } 6241 6242 if (!InitField) 6243 return Incompatible; 6244 6245 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6246 return Compatible; 6247 } 6248 6249 Sema::AssignConvertType 6250 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6251 bool Diagnose) { 6252 if (getLangOpts().CPlusPlus) { 6253 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6254 // C++ 5.17p3: If the left operand is not of class type, the 6255 // expression is implicitly converted (C++ 4) to the 6256 // cv-unqualified type of the left operand. 6257 ExprResult Res; 6258 if (Diagnose) { 6259 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6260 AA_Assigning); 6261 } else { 6262 ImplicitConversionSequence ICS = 6263 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6264 /*SuppressUserConversions=*/false, 6265 /*AllowExplicit=*/false, 6266 /*InOverloadResolution=*/false, 6267 /*CStyle=*/false, 6268 /*AllowObjCWritebackConversion=*/false); 6269 if (ICS.isFailure()) 6270 return Incompatible; 6271 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6272 ICS, AA_Assigning); 6273 } 6274 if (Res.isInvalid()) 6275 return Incompatible; 6276 Sema::AssignConvertType result = Compatible; 6277 if (getLangOpts().ObjCAutoRefCount && 6278 !CheckObjCARCUnavailableWeakConversion(LHSType, 6279 RHS.get()->getType())) 6280 result = IncompatibleObjCWeakRef; 6281 RHS = Res; 6282 return result; 6283 } 6284 6285 // FIXME: Currently, we fall through and treat C++ classes like C 6286 // structures. 6287 // FIXME: We also fall through for atomics; not sure what should 6288 // happen there, though. 6289 } 6290 6291 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6292 // a null pointer constant. 6293 if ((LHSType->isPointerType() || 6294 LHSType->isObjCObjectPointerType() || 6295 LHSType->isBlockPointerType()) 6296 && RHS.get()->isNullPointerConstant(Context, 6297 Expr::NPC_ValueDependentIsNull)) { 6298 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6299 return Compatible; 6300 } 6301 6302 // This check seems unnatural, however it is necessary to ensure the proper 6303 // conversion of functions/arrays. If the conversion were done for all 6304 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6305 // expressions that suppress this implicit conversion (&, sizeof). 6306 // 6307 // Suppress this for references: C++ 8.5.3p5. 6308 if (!LHSType->isReferenceType()) { 6309 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6310 if (RHS.isInvalid()) 6311 return Incompatible; 6312 } 6313 6314 CastKind Kind = CK_Invalid; 6315 Sema::AssignConvertType result = 6316 CheckAssignmentConstraints(LHSType, RHS, Kind); 6317 6318 // C99 6.5.16.1p2: The value of the right operand is converted to the 6319 // type of the assignment expression. 6320 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6321 // so that we can use references in built-in functions even in C. 6322 // The getNonReferenceType() call makes sure that the resulting expression 6323 // does not have reference type. 6324 if (result != Incompatible && RHS.get()->getType() != LHSType) 6325 RHS = ImpCastExprToType(RHS.take(), 6326 LHSType.getNonLValueExprType(Context), Kind); 6327 return result; 6328 } 6329 6330 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6331 ExprResult &RHS) { 6332 Diag(Loc, diag::err_typecheck_invalid_operands) 6333 << LHS.get()->getType() << RHS.get()->getType() 6334 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6335 return QualType(); 6336 } 6337 6338 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6339 SourceLocation Loc, bool IsCompAssign) { 6340 if (!IsCompAssign) { 6341 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6342 if (LHS.isInvalid()) 6343 return QualType(); 6344 } 6345 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6346 if (RHS.isInvalid()) 6347 return QualType(); 6348 6349 // For conversion purposes, we ignore any qualifiers. 6350 // For example, "const float" and "float" are equivalent. 6351 QualType LHSType = 6352 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6353 QualType RHSType = 6354 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6355 6356 // If the vector types are identical, return. 6357 if (LHSType == RHSType) 6358 return LHSType; 6359 6360 // Handle the case of equivalent AltiVec and GCC vector types 6361 if (LHSType->isVectorType() && RHSType->isVectorType() && 6362 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6363 if (LHSType->isExtVectorType()) { 6364 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6365 return LHSType; 6366 } 6367 6368 if (!IsCompAssign) 6369 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6370 return RHSType; 6371 } 6372 6373 if (getLangOpts().LaxVectorConversions && 6374 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6375 // If we are allowing lax vector conversions, and LHS and RHS are both 6376 // vectors, the total size only needs to be the same. This is a 6377 // bitcast; no bits are changed but the result type is different. 6378 // FIXME: Should we really be allowing this? 6379 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6380 return LHSType; 6381 } 6382 6383 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6384 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6385 bool swapped = false; 6386 if (RHSType->isExtVectorType() && !IsCompAssign) { 6387 swapped = true; 6388 std::swap(RHS, LHS); 6389 std::swap(RHSType, LHSType); 6390 } 6391 6392 // Handle the case of an ext vector and scalar. 6393 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6394 QualType EltTy = LV->getElementType(); 6395 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6396 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6397 if (order > 0) 6398 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6399 if (order >= 0) { 6400 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6401 if (swapped) std::swap(RHS, LHS); 6402 return LHSType; 6403 } 6404 } 6405 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 6406 RHSType->isRealFloatingType()) { 6407 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6408 if (order > 0) 6409 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6410 if (order >= 0) { 6411 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6412 if (swapped) std::swap(RHS, LHS); 6413 return LHSType; 6414 } 6415 } 6416 } 6417 6418 // Vectors of different size or scalar and non-ext-vector are errors. 6419 if (swapped) std::swap(RHS, LHS); 6420 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6421 << LHS.get()->getType() << RHS.get()->getType() 6422 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6423 return QualType(); 6424 } 6425 6426 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6427 // expression. These are mainly cases where the null pointer is used as an 6428 // integer instead of a pointer. 6429 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6430 SourceLocation Loc, bool IsCompare) { 6431 // The canonical way to check for a GNU null is with isNullPointerConstant, 6432 // but we use a bit of a hack here for speed; this is a relatively 6433 // hot path, and isNullPointerConstant is slow. 6434 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6435 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6436 6437 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6438 6439 // Avoid analyzing cases where the result will either be invalid (and 6440 // diagnosed as such) or entirely valid and not something to warn about. 6441 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6442 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6443 return; 6444 6445 // Comparison operations would not make sense with a null pointer no matter 6446 // what the other expression is. 6447 if (!IsCompare) { 6448 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6449 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6450 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6451 return; 6452 } 6453 6454 // The rest of the operations only make sense with a null pointer 6455 // if the other expression is a pointer. 6456 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6457 NonNullType->canDecayToPointerType()) 6458 return; 6459 6460 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6461 << LHSNull /* LHS is NULL */ << NonNullType 6462 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6463 } 6464 6465 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6466 SourceLocation Loc, 6467 bool IsCompAssign, bool IsDiv) { 6468 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6469 6470 if (LHS.get()->getType()->isVectorType() || 6471 RHS.get()->getType()->isVectorType()) 6472 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6473 6474 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6475 if (LHS.isInvalid() || RHS.isInvalid()) 6476 return QualType(); 6477 6478 6479 if (compType.isNull() || !compType->isArithmeticType()) 6480 return InvalidOperands(Loc, LHS, RHS); 6481 6482 // Check for division by zero. 6483 if (IsDiv && 6484 RHS.get()->isNullPointerConstant(Context, 6485 Expr::NPC_ValueDependentIsNotNull)) 6486 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 6487 << RHS.get()->getSourceRange()); 6488 6489 return compType; 6490 } 6491 6492 QualType Sema::CheckRemainderOperands( 6493 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6494 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6495 6496 if (LHS.get()->getType()->isVectorType() || 6497 RHS.get()->getType()->isVectorType()) { 6498 if (LHS.get()->getType()->hasIntegerRepresentation() && 6499 RHS.get()->getType()->hasIntegerRepresentation()) 6500 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6501 return InvalidOperands(Loc, LHS, RHS); 6502 } 6503 6504 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6505 if (LHS.isInvalid() || RHS.isInvalid()) 6506 return QualType(); 6507 6508 if (compType.isNull() || !compType->isIntegerType()) 6509 return InvalidOperands(Loc, LHS, RHS); 6510 6511 // Check for remainder by zero. 6512 if (RHS.get()->isNullPointerConstant(Context, 6513 Expr::NPC_ValueDependentIsNotNull)) 6514 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 6515 << RHS.get()->getSourceRange()); 6516 6517 return compType; 6518 } 6519 6520 /// \brief Diagnose invalid arithmetic on two void pointers. 6521 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6522 Expr *LHSExpr, Expr *RHSExpr) { 6523 S.Diag(Loc, S.getLangOpts().CPlusPlus 6524 ? diag::err_typecheck_pointer_arith_void_type 6525 : diag::ext_gnu_void_ptr) 6526 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6527 << RHSExpr->getSourceRange(); 6528 } 6529 6530 /// \brief Diagnose invalid arithmetic on a void pointer. 6531 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6532 Expr *Pointer) { 6533 S.Diag(Loc, S.getLangOpts().CPlusPlus 6534 ? diag::err_typecheck_pointer_arith_void_type 6535 : diag::ext_gnu_void_ptr) 6536 << 0 /* one pointer */ << Pointer->getSourceRange(); 6537 } 6538 6539 /// \brief Diagnose invalid arithmetic on two function pointers. 6540 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6541 Expr *LHS, Expr *RHS) { 6542 assert(LHS->getType()->isAnyPointerType()); 6543 assert(RHS->getType()->isAnyPointerType()); 6544 S.Diag(Loc, S.getLangOpts().CPlusPlus 6545 ? diag::err_typecheck_pointer_arith_function_type 6546 : diag::ext_gnu_ptr_func_arith) 6547 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6548 // We only show the second type if it differs from the first. 6549 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6550 RHS->getType()) 6551 << RHS->getType()->getPointeeType() 6552 << LHS->getSourceRange() << RHS->getSourceRange(); 6553 } 6554 6555 /// \brief Diagnose invalid arithmetic on a function pointer. 6556 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6557 Expr *Pointer) { 6558 assert(Pointer->getType()->isAnyPointerType()); 6559 S.Diag(Loc, S.getLangOpts().CPlusPlus 6560 ? diag::err_typecheck_pointer_arith_function_type 6561 : diag::ext_gnu_ptr_func_arith) 6562 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6563 << 0 /* one pointer, so only one type */ 6564 << Pointer->getSourceRange(); 6565 } 6566 6567 /// \brief Emit error if Operand is incomplete pointer type 6568 /// 6569 /// \returns True if pointer has incomplete type 6570 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6571 Expr *Operand) { 6572 assert(Operand->getType()->isAnyPointerType() && 6573 !Operand->getType()->isDependentType()); 6574 QualType PointeeTy = Operand->getType()->getPointeeType(); 6575 return S.RequireCompleteType(Loc, PointeeTy, 6576 diag::err_typecheck_arithmetic_incomplete_type, 6577 PointeeTy, Operand->getSourceRange()); 6578 } 6579 6580 /// \brief Check the validity of an arithmetic pointer operand. 6581 /// 6582 /// If the operand has pointer type, this code will check for pointer types 6583 /// which are invalid in arithmetic operations. These will be diagnosed 6584 /// appropriately, including whether or not the use is supported as an 6585 /// extension. 6586 /// 6587 /// \returns True when the operand is valid to use (even if as an extension). 6588 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6589 Expr *Operand) { 6590 if (!Operand->getType()->isAnyPointerType()) return true; 6591 6592 QualType PointeeTy = Operand->getType()->getPointeeType(); 6593 if (PointeeTy->isVoidType()) { 6594 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6595 return !S.getLangOpts().CPlusPlus; 6596 } 6597 if (PointeeTy->isFunctionType()) { 6598 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6599 return !S.getLangOpts().CPlusPlus; 6600 } 6601 6602 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6603 6604 return true; 6605 } 6606 6607 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6608 /// operands. 6609 /// 6610 /// This routine will diagnose any invalid arithmetic on pointer operands much 6611 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 6612 /// for emitting a single diagnostic even for operations where both LHS and RHS 6613 /// are (potentially problematic) pointers. 6614 /// 6615 /// \returns True when the operand is valid to use (even if as an extension). 6616 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6617 Expr *LHSExpr, Expr *RHSExpr) { 6618 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6619 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6620 if (!isLHSPointer && !isRHSPointer) return true; 6621 6622 QualType LHSPointeeTy, RHSPointeeTy; 6623 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6624 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6625 6626 // Check for arithmetic on pointers to incomplete types. 6627 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6628 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6629 if (isLHSVoidPtr || isRHSVoidPtr) { 6630 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6631 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6632 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6633 6634 return !S.getLangOpts().CPlusPlus; 6635 } 6636 6637 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6638 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6639 if (isLHSFuncPtr || isRHSFuncPtr) { 6640 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6641 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6642 RHSExpr); 6643 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6644 6645 return !S.getLangOpts().CPlusPlus; 6646 } 6647 6648 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6649 return false; 6650 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6651 return false; 6652 6653 return true; 6654 } 6655 6656 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6657 /// literal. 6658 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6659 Expr *LHSExpr, Expr *RHSExpr) { 6660 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6661 Expr* IndexExpr = RHSExpr; 6662 if (!StrExpr) { 6663 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6664 IndexExpr = LHSExpr; 6665 } 6666 6667 bool IsStringPlusInt = StrExpr && 6668 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6669 if (!IsStringPlusInt) 6670 return; 6671 6672 llvm::APSInt index; 6673 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6674 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6675 if (index.isNonNegative() && 6676 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6677 index.isUnsigned())) 6678 return; 6679 } 6680 6681 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6682 Self.Diag(OpLoc, diag::warn_string_plus_int) 6683 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6684 6685 // Only print a fixit for "str" + int, not for int + "str". 6686 if (IndexExpr == RHSExpr) { 6687 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6688 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6689 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6690 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6691 << FixItHint::CreateInsertion(EndLoc, "]"); 6692 } else 6693 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6694 } 6695 6696 /// \brief Emit error when two pointers are incompatible. 6697 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6698 Expr *LHSExpr, Expr *RHSExpr) { 6699 assert(LHSExpr->getType()->isAnyPointerType()); 6700 assert(RHSExpr->getType()->isAnyPointerType()); 6701 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6702 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6703 << RHSExpr->getSourceRange(); 6704 } 6705 6706 QualType Sema::CheckAdditionOperands( // C99 6.5.6 6707 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6708 QualType* CompLHSTy) { 6709 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6710 6711 if (LHS.get()->getType()->isVectorType() || 6712 RHS.get()->getType()->isVectorType()) { 6713 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6714 if (CompLHSTy) *CompLHSTy = compType; 6715 return compType; 6716 } 6717 6718 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6719 if (LHS.isInvalid() || RHS.isInvalid()) 6720 return QualType(); 6721 6722 // Diagnose "string literal" '+' int. 6723 if (Opc == BO_Add) 6724 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6725 6726 // handle the common case first (both operands are arithmetic). 6727 if (!compType.isNull() && compType->isArithmeticType()) { 6728 if (CompLHSTy) *CompLHSTy = compType; 6729 return compType; 6730 } 6731 6732 // Type-checking. Ultimately the pointer's going to be in PExp; 6733 // note that we bias towards the LHS being the pointer. 6734 Expr *PExp = LHS.get(), *IExp = RHS.get(); 6735 6736 bool isObjCPointer; 6737 if (PExp->getType()->isPointerType()) { 6738 isObjCPointer = false; 6739 } else if (PExp->getType()->isObjCObjectPointerType()) { 6740 isObjCPointer = true; 6741 } else { 6742 std::swap(PExp, IExp); 6743 if (PExp->getType()->isPointerType()) { 6744 isObjCPointer = false; 6745 } else if (PExp->getType()->isObjCObjectPointerType()) { 6746 isObjCPointer = true; 6747 } else { 6748 return InvalidOperands(Loc, LHS, RHS); 6749 } 6750 } 6751 assert(PExp->getType()->isAnyPointerType()); 6752 6753 if (!IExp->getType()->isIntegerType()) 6754 return InvalidOperands(Loc, LHS, RHS); 6755 6756 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6757 return QualType(); 6758 6759 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 6760 return QualType(); 6761 6762 // Check array bounds for pointer arithemtic 6763 CheckArrayAccess(PExp, IExp); 6764 6765 if (CompLHSTy) { 6766 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6767 if (LHSTy.isNull()) { 6768 LHSTy = LHS.get()->getType(); 6769 if (LHSTy->isPromotableIntegerType()) 6770 LHSTy = Context.getPromotedIntegerType(LHSTy); 6771 } 6772 *CompLHSTy = LHSTy; 6773 } 6774 6775 return PExp->getType(); 6776 } 6777 6778 // C99 6.5.6 6779 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6780 SourceLocation Loc, 6781 QualType* CompLHSTy) { 6782 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6783 6784 if (LHS.get()->getType()->isVectorType() || 6785 RHS.get()->getType()->isVectorType()) { 6786 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6787 if (CompLHSTy) *CompLHSTy = compType; 6788 return compType; 6789 } 6790 6791 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6792 if (LHS.isInvalid() || RHS.isInvalid()) 6793 return QualType(); 6794 6795 // Enforce type constraints: C99 6.5.6p3. 6796 6797 // Handle the common case first (both operands are arithmetic). 6798 if (!compType.isNull() && compType->isArithmeticType()) { 6799 if (CompLHSTy) *CompLHSTy = compType; 6800 return compType; 6801 } 6802 6803 // Either ptr - int or ptr - ptr. 6804 if (LHS.get()->getType()->isAnyPointerType()) { 6805 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6806 6807 // Diagnose bad cases where we step over interface counts. 6808 if (LHS.get()->getType()->isObjCObjectPointerType() && 6809 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 6810 return QualType(); 6811 6812 // The result type of a pointer-int computation is the pointer type. 6813 if (RHS.get()->getType()->isIntegerType()) { 6814 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6815 return QualType(); 6816 6817 // Check array bounds for pointer arithemtic 6818 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 6819 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 6820 6821 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6822 return LHS.get()->getType(); 6823 } 6824 6825 // Handle pointer-pointer subtractions. 6826 if (const PointerType *RHSPTy 6827 = RHS.get()->getType()->getAs<PointerType>()) { 6828 QualType rpointee = RHSPTy->getPointeeType(); 6829 6830 if (getLangOpts().CPlusPlus) { 6831 // Pointee types must be the same: C++ [expr.add] 6832 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6833 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6834 } 6835 } else { 6836 // Pointee types must be compatible C99 6.5.6p3 6837 if (!Context.typesAreCompatible( 6838 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6839 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6840 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6841 return QualType(); 6842 } 6843 } 6844 6845 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6846 LHS.get(), RHS.get())) 6847 return QualType(); 6848 6849 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6850 return Context.getPointerDiffType(); 6851 } 6852 } 6853 6854 return InvalidOperands(Loc, LHS, RHS); 6855 } 6856 6857 static bool isScopedEnumerationType(QualType T) { 6858 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6859 return ET->getDecl()->isScoped(); 6860 return false; 6861 } 6862 6863 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6864 SourceLocation Loc, unsigned Opc, 6865 QualType LHSType) { 6866 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 6867 // so skip remaining warnings as we don't want to modify values within Sema. 6868 if (S.getLangOpts().OpenCL) 6869 return; 6870 6871 llvm::APSInt Right; 6872 // Check right/shifter operand 6873 if (RHS.get()->isValueDependent() || 6874 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6875 return; 6876 6877 if (Right.isNegative()) { 6878 S.DiagRuntimeBehavior(Loc, RHS.get(), 6879 S.PDiag(diag::warn_shift_negative) 6880 << RHS.get()->getSourceRange()); 6881 return; 6882 } 6883 llvm::APInt LeftBits(Right.getBitWidth(), 6884 S.Context.getTypeSize(LHS.get()->getType())); 6885 if (Right.uge(LeftBits)) { 6886 S.DiagRuntimeBehavior(Loc, RHS.get(), 6887 S.PDiag(diag::warn_shift_gt_typewidth) 6888 << RHS.get()->getSourceRange()); 6889 return; 6890 } 6891 if (Opc != BO_Shl) 6892 return; 6893 6894 // When left shifting an ICE which is signed, we can check for overflow which 6895 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6896 // integers have defined behavior modulo one more than the maximum value 6897 // representable in the result type, so never warn for those. 6898 llvm::APSInt Left; 6899 if (LHS.get()->isValueDependent() || 6900 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6901 LHSType->hasUnsignedIntegerRepresentation()) 6902 return; 6903 llvm::APInt ResultBits = 6904 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6905 if (LeftBits.uge(ResultBits)) 6906 return; 6907 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6908 Result = Result.shl(Right); 6909 6910 // Print the bit representation of the signed integer as an unsigned 6911 // hexadecimal number. 6912 SmallString<40> HexResult; 6913 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6914 6915 // If we are only missing a sign bit, this is less likely to result in actual 6916 // bugs -- if the result is cast back to an unsigned type, it will have the 6917 // expected value. Thus we place this behind a different warning that can be 6918 // turned off separately if needed. 6919 if (LeftBits == ResultBits - 1) { 6920 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6921 << HexResult.str() << LHSType 6922 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6923 return; 6924 } 6925 6926 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6927 << HexResult.str() << Result.getMinSignedBits() << LHSType 6928 << Left.getBitWidth() << LHS.get()->getSourceRange() 6929 << RHS.get()->getSourceRange(); 6930 } 6931 6932 // C99 6.5.7 6933 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6934 SourceLocation Loc, unsigned Opc, 6935 bool IsCompAssign) { 6936 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6937 6938 // Vector shifts promote their scalar inputs to vector type. 6939 if (LHS.get()->getType()->isVectorType() || 6940 RHS.get()->getType()->isVectorType()) 6941 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6942 6943 // Shifts don't perform usual arithmetic conversions, they just do integer 6944 // promotions on each operand. C99 6.5.7p3 6945 6946 // For the LHS, do usual unary conversions, but then reset them away 6947 // if this is a compound assignment. 6948 ExprResult OldLHS = LHS; 6949 LHS = UsualUnaryConversions(LHS.take()); 6950 if (LHS.isInvalid()) 6951 return QualType(); 6952 QualType LHSType = LHS.get()->getType(); 6953 if (IsCompAssign) LHS = OldLHS; 6954 6955 // The RHS is simpler. 6956 RHS = UsualUnaryConversions(RHS.take()); 6957 if (RHS.isInvalid()) 6958 return QualType(); 6959 QualType RHSType = RHS.get()->getType(); 6960 6961 // C99 6.5.7p2: Each of the operands shall have integer type. 6962 if (!LHSType->hasIntegerRepresentation() || 6963 !RHSType->hasIntegerRepresentation()) 6964 return InvalidOperands(Loc, LHS, RHS); 6965 6966 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6967 // hasIntegerRepresentation() above instead of this. 6968 if (isScopedEnumerationType(LHSType) || 6969 isScopedEnumerationType(RHSType)) { 6970 return InvalidOperands(Loc, LHS, RHS); 6971 } 6972 // Sanity-check shift operands 6973 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6974 6975 // "The type of the result is that of the promoted left operand." 6976 return LHSType; 6977 } 6978 6979 static bool IsWithinTemplateSpecialization(Decl *D) { 6980 if (DeclContext *DC = D->getDeclContext()) { 6981 if (isa<ClassTemplateSpecializationDecl>(DC)) 6982 return true; 6983 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6984 return FD->isFunctionTemplateSpecialization(); 6985 } 6986 return false; 6987 } 6988 6989 /// If two different enums are compared, raise a warning. 6990 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 6991 Expr *RHS) { 6992 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 6993 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 6994 6995 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6996 if (!LHSEnumType) 6997 return; 6998 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6999 if (!RHSEnumType) 7000 return; 7001 7002 // Ignore anonymous enums. 7003 if (!LHSEnumType->getDecl()->getIdentifier()) 7004 return; 7005 if (!RHSEnumType->getDecl()->getIdentifier()) 7006 return; 7007 7008 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7009 return; 7010 7011 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7012 << LHSStrippedType << RHSStrippedType 7013 << LHS->getSourceRange() << RHS->getSourceRange(); 7014 } 7015 7016 /// \brief Diagnose bad pointer comparisons. 7017 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7018 ExprResult &LHS, ExprResult &RHS, 7019 bool IsError) { 7020 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7021 : diag::ext_typecheck_comparison_of_distinct_pointers) 7022 << LHS.get()->getType() << RHS.get()->getType() 7023 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7024 } 7025 7026 /// \brief Returns false if the pointers are converted to a composite type, 7027 /// true otherwise. 7028 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7029 ExprResult &LHS, ExprResult &RHS) { 7030 // C++ [expr.rel]p2: 7031 // [...] Pointer conversions (4.10) and qualification 7032 // conversions (4.4) are performed on pointer operands (or on 7033 // a pointer operand and a null pointer constant) to bring 7034 // them to their composite pointer type. [...] 7035 // 7036 // C++ [expr.eq]p1 uses the same notion for (in)equality 7037 // comparisons of pointers. 7038 7039 // C++ [expr.eq]p2: 7040 // In addition, pointers to members can be compared, or a pointer to 7041 // member and a null pointer constant. Pointer to member conversions 7042 // (4.11) and qualification conversions (4.4) are performed to bring 7043 // them to a common type. If one operand is a null pointer constant, 7044 // the common type is the type of the other operand. Otherwise, the 7045 // common type is a pointer to member type similar (4.4) to the type 7046 // of one of the operands, with a cv-qualification signature (4.4) 7047 // that is the union of the cv-qualification signatures of the operand 7048 // types. 7049 7050 QualType LHSType = LHS.get()->getType(); 7051 QualType RHSType = RHS.get()->getType(); 7052 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7053 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7054 7055 bool NonStandardCompositeType = false; 7056 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7057 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7058 if (T.isNull()) { 7059 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7060 return true; 7061 } 7062 7063 if (NonStandardCompositeType) 7064 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7065 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7066 << RHS.get()->getSourceRange(); 7067 7068 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7069 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7070 return false; 7071 } 7072 7073 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7074 ExprResult &LHS, 7075 ExprResult &RHS, 7076 bool IsError) { 7077 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7078 : diag::ext_typecheck_comparison_of_fptr_to_void) 7079 << LHS.get()->getType() << RHS.get()->getType() 7080 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7081 } 7082 7083 static bool isObjCObjectLiteral(ExprResult &E) { 7084 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7085 case Stmt::ObjCArrayLiteralClass: 7086 case Stmt::ObjCDictionaryLiteralClass: 7087 case Stmt::ObjCStringLiteralClass: 7088 case Stmt::ObjCBoxedExprClass: 7089 return true; 7090 default: 7091 // Note that ObjCBoolLiteral is NOT an object literal! 7092 return false; 7093 } 7094 } 7095 7096 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7097 const ObjCObjectPointerType *Type = 7098 LHS->getType()->getAs<ObjCObjectPointerType>(); 7099 7100 // If this is not actually an Objective-C object, bail out. 7101 if (!Type) 7102 return false; 7103 7104 // Get the LHS object's interface type. 7105 QualType InterfaceType = Type->getPointeeType(); 7106 if (const ObjCObjectType *iQFaceTy = 7107 InterfaceType->getAsObjCQualifiedInterfaceType()) 7108 InterfaceType = iQFaceTy->getBaseType(); 7109 7110 // If the RHS isn't an Objective-C object, bail out. 7111 if (!RHS->getType()->isObjCObjectPointerType()) 7112 return false; 7113 7114 // Try to find the -isEqual: method. 7115 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7116 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7117 InterfaceType, 7118 /*instance=*/true); 7119 if (!Method) { 7120 if (Type->isObjCIdType()) { 7121 // For 'id', just check the global pool. 7122 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7123 /*receiverId=*/true, 7124 /*warn=*/false); 7125 } else { 7126 // Check protocols. 7127 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7128 /*instance=*/true); 7129 } 7130 } 7131 7132 if (!Method) 7133 return false; 7134 7135 QualType T = Method->param_begin()[0]->getType(); 7136 if (!T->isObjCObjectPointerType()) 7137 return false; 7138 7139 QualType R = Method->getResultType(); 7140 if (!R->isScalarType()) 7141 return false; 7142 7143 return true; 7144 } 7145 7146 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7147 FromE = FromE->IgnoreParenImpCasts(); 7148 switch (FromE->getStmtClass()) { 7149 default: 7150 break; 7151 case Stmt::ObjCStringLiteralClass: 7152 // "string literal" 7153 return LK_String; 7154 case Stmt::ObjCArrayLiteralClass: 7155 // "array literal" 7156 return LK_Array; 7157 case Stmt::ObjCDictionaryLiteralClass: 7158 // "dictionary literal" 7159 return LK_Dictionary; 7160 case Stmt::BlockExprClass: 7161 return LK_Block; 7162 case Stmt::ObjCBoxedExprClass: { 7163 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7164 switch (Inner->getStmtClass()) { 7165 case Stmt::IntegerLiteralClass: 7166 case Stmt::FloatingLiteralClass: 7167 case Stmt::CharacterLiteralClass: 7168 case Stmt::ObjCBoolLiteralExprClass: 7169 case Stmt::CXXBoolLiteralExprClass: 7170 // "numeric literal" 7171 return LK_Numeric; 7172 case Stmt::ImplicitCastExprClass: { 7173 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7174 // Boolean literals can be represented by implicit casts. 7175 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7176 return LK_Numeric; 7177 break; 7178 } 7179 default: 7180 break; 7181 } 7182 return LK_Boxed; 7183 } 7184 } 7185 return LK_None; 7186 } 7187 7188 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7189 ExprResult &LHS, ExprResult &RHS, 7190 BinaryOperator::Opcode Opc){ 7191 Expr *Literal; 7192 Expr *Other; 7193 if (isObjCObjectLiteral(LHS)) { 7194 Literal = LHS.get(); 7195 Other = RHS.get(); 7196 } else { 7197 Literal = RHS.get(); 7198 Other = LHS.get(); 7199 } 7200 7201 // Don't warn on comparisons against nil. 7202 Other = Other->IgnoreParenCasts(); 7203 if (Other->isNullPointerConstant(S.getASTContext(), 7204 Expr::NPC_ValueDependentIsNotNull)) 7205 return; 7206 7207 // This should be kept in sync with warn_objc_literal_comparison. 7208 // LK_String should always be after the other literals, since it has its own 7209 // warning flag. 7210 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7211 assert(LiteralKind != Sema::LK_Block); 7212 if (LiteralKind == Sema::LK_None) { 7213 llvm_unreachable("Unknown Objective-C object literal kind"); 7214 } 7215 7216 if (LiteralKind == Sema::LK_String) 7217 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7218 << Literal->getSourceRange(); 7219 else 7220 S.Diag(Loc, diag::warn_objc_literal_comparison) 7221 << LiteralKind << Literal->getSourceRange(); 7222 7223 if (BinaryOperator::isEqualityOp(Opc) && 7224 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7225 SourceLocation Start = LHS.get()->getLocStart(); 7226 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7227 CharSourceRange OpRange = 7228 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7229 7230 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7231 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7232 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7233 << FixItHint::CreateInsertion(End, "]"); 7234 } 7235 } 7236 7237 // C99 6.5.8, C++ [expr.rel] 7238 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7239 SourceLocation Loc, unsigned OpaqueOpc, 7240 bool IsRelational) { 7241 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7242 7243 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7244 7245 // Handle vector comparisons separately. 7246 if (LHS.get()->getType()->isVectorType() || 7247 RHS.get()->getType()->isVectorType()) 7248 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7249 7250 QualType LHSType = LHS.get()->getType(); 7251 QualType RHSType = RHS.get()->getType(); 7252 7253 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7254 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7255 7256 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7257 7258 if (!LHSType->hasFloatingRepresentation() && 7259 !(LHSType->isBlockPointerType() && IsRelational) && 7260 !LHS.get()->getLocStart().isMacroID() && 7261 !RHS.get()->getLocStart().isMacroID()) { 7262 // For non-floating point types, check for self-comparisons of the form 7263 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7264 // often indicate logic errors in the program. 7265 // 7266 // NOTE: Don't warn about comparison expressions resulting from macro 7267 // expansion. Also don't warn about comparisons which are only self 7268 // comparisons within a template specialization. The warnings should catch 7269 // obvious cases in the definition of the template anyways. The idea is to 7270 // warn when the typed comparison operator will always evaluate to the same 7271 // result. 7272 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 7273 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 7274 if (DRL->getDecl() == DRR->getDecl() && 7275 !IsWithinTemplateSpecialization(DRL->getDecl())) { 7276 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7277 << 0 // self- 7278 << (Opc == BO_EQ 7279 || Opc == BO_LE 7280 || Opc == BO_GE)); 7281 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 7282 !DRL->getDecl()->getType()->isReferenceType() && 7283 !DRR->getDecl()->getType()->isReferenceType()) { 7284 // what is it always going to eval to? 7285 char always_evals_to; 7286 switch(Opc) { 7287 case BO_EQ: // e.g. array1 == array2 7288 always_evals_to = 0; // false 7289 break; 7290 case BO_NE: // e.g. array1 != array2 7291 always_evals_to = 1; // true 7292 break; 7293 default: 7294 // best we can say is 'a constant' 7295 always_evals_to = 2; // e.g. array1 <= array2 7296 break; 7297 } 7298 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7299 << 1 // array 7300 << always_evals_to); 7301 } 7302 } 7303 } 7304 7305 if (isa<CastExpr>(LHSStripped)) 7306 LHSStripped = LHSStripped->IgnoreParenCasts(); 7307 if (isa<CastExpr>(RHSStripped)) 7308 RHSStripped = RHSStripped->IgnoreParenCasts(); 7309 7310 // Warn about comparisons against a string constant (unless the other 7311 // operand is null), the user probably wants strcmp. 7312 Expr *literalString = 0; 7313 Expr *literalStringStripped = 0; 7314 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7315 !RHSStripped->isNullPointerConstant(Context, 7316 Expr::NPC_ValueDependentIsNull)) { 7317 literalString = LHS.get(); 7318 literalStringStripped = LHSStripped; 7319 } else if ((isa<StringLiteral>(RHSStripped) || 7320 isa<ObjCEncodeExpr>(RHSStripped)) && 7321 !LHSStripped->isNullPointerConstant(Context, 7322 Expr::NPC_ValueDependentIsNull)) { 7323 literalString = RHS.get(); 7324 literalStringStripped = RHSStripped; 7325 } 7326 7327 if (literalString) { 7328 DiagRuntimeBehavior(Loc, 0, 7329 PDiag(diag::warn_stringcompare) 7330 << isa<ObjCEncodeExpr>(literalStringStripped) 7331 << literalString->getSourceRange()); 7332 } 7333 } 7334 7335 // C99 6.5.8p3 / C99 6.5.9p4 7336 if (LHS.get()->getType()->isArithmeticType() && 7337 RHS.get()->getType()->isArithmeticType()) { 7338 UsualArithmeticConversions(LHS, RHS); 7339 if (LHS.isInvalid() || RHS.isInvalid()) 7340 return QualType(); 7341 } 7342 else { 7343 LHS = UsualUnaryConversions(LHS.take()); 7344 if (LHS.isInvalid()) 7345 return QualType(); 7346 7347 RHS = UsualUnaryConversions(RHS.take()); 7348 if (RHS.isInvalid()) 7349 return QualType(); 7350 } 7351 7352 LHSType = LHS.get()->getType(); 7353 RHSType = RHS.get()->getType(); 7354 7355 // The result of comparisons is 'bool' in C++, 'int' in C. 7356 QualType ResultTy = Context.getLogicalOperationType(); 7357 7358 if (IsRelational) { 7359 if (LHSType->isRealType() && RHSType->isRealType()) 7360 return ResultTy; 7361 } else { 7362 // Check for comparisons of floating point operands using != and ==. 7363 if (LHSType->hasFloatingRepresentation()) 7364 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7365 7366 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7367 return ResultTy; 7368 } 7369 7370 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7371 Expr::NPC_ValueDependentIsNull); 7372 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7373 Expr::NPC_ValueDependentIsNull); 7374 7375 // All of the following pointer-related warnings are GCC extensions, except 7376 // when handling null pointer constants. 7377 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7378 QualType LCanPointeeTy = 7379 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7380 QualType RCanPointeeTy = 7381 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7382 7383 if (getLangOpts().CPlusPlus) { 7384 if (LCanPointeeTy == RCanPointeeTy) 7385 return ResultTy; 7386 if (!IsRelational && 7387 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7388 // Valid unless comparison between non-null pointer and function pointer 7389 // This is a gcc extension compatibility comparison. 7390 // In a SFINAE context, we treat this as a hard error to maintain 7391 // conformance with the C++ standard. 7392 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7393 && !LHSIsNull && !RHSIsNull) { 7394 diagnoseFunctionPointerToVoidComparison( 7395 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7396 7397 if (isSFINAEContext()) 7398 return QualType(); 7399 7400 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7401 return ResultTy; 7402 } 7403 } 7404 7405 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7406 return QualType(); 7407 else 7408 return ResultTy; 7409 } 7410 // C99 6.5.9p2 and C99 6.5.8p2 7411 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7412 RCanPointeeTy.getUnqualifiedType())) { 7413 // Valid unless a relational comparison of function pointers 7414 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7415 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7416 << LHSType << RHSType << LHS.get()->getSourceRange() 7417 << RHS.get()->getSourceRange(); 7418 } 7419 } else if (!IsRelational && 7420 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7421 // Valid unless comparison between non-null pointer and function pointer 7422 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7423 && !LHSIsNull && !RHSIsNull) 7424 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7425 /*isError*/false); 7426 } else { 7427 // Invalid 7428 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7429 } 7430 if (LCanPointeeTy != RCanPointeeTy) { 7431 if (LHSIsNull && !RHSIsNull) 7432 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7433 else 7434 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7435 } 7436 return ResultTy; 7437 } 7438 7439 if (getLangOpts().CPlusPlus) { 7440 // Comparison of nullptr_t with itself. 7441 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7442 return ResultTy; 7443 7444 // Comparison of pointers with null pointer constants and equality 7445 // comparisons of member pointers to null pointer constants. 7446 if (RHSIsNull && 7447 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7448 (!IsRelational && 7449 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7450 RHS = ImpCastExprToType(RHS.take(), LHSType, 7451 LHSType->isMemberPointerType() 7452 ? CK_NullToMemberPointer 7453 : CK_NullToPointer); 7454 return ResultTy; 7455 } 7456 if (LHSIsNull && 7457 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7458 (!IsRelational && 7459 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7460 LHS = ImpCastExprToType(LHS.take(), RHSType, 7461 RHSType->isMemberPointerType() 7462 ? CK_NullToMemberPointer 7463 : CK_NullToPointer); 7464 return ResultTy; 7465 } 7466 7467 // Comparison of member pointers. 7468 if (!IsRelational && 7469 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7470 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7471 return QualType(); 7472 else 7473 return ResultTy; 7474 } 7475 7476 // Handle scoped enumeration types specifically, since they don't promote 7477 // to integers. 7478 if (LHS.get()->getType()->isEnumeralType() && 7479 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7480 RHS.get()->getType())) 7481 return ResultTy; 7482 } 7483 7484 // Handle block pointer types. 7485 if (!IsRelational && LHSType->isBlockPointerType() && 7486 RHSType->isBlockPointerType()) { 7487 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7488 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7489 7490 if (!LHSIsNull && !RHSIsNull && 7491 !Context.typesAreCompatible(lpointee, rpointee)) { 7492 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7493 << LHSType << RHSType << LHS.get()->getSourceRange() 7494 << RHS.get()->getSourceRange(); 7495 } 7496 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7497 return ResultTy; 7498 } 7499 7500 // Allow block pointers to be compared with null pointer constants. 7501 if (!IsRelational 7502 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7503 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7504 if (!LHSIsNull && !RHSIsNull) { 7505 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7506 ->getPointeeType()->isVoidType()) 7507 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7508 ->getPointeeType()->isVoidType()))) 7509 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7510 << LHSType << RHSType << LHS.get()->getSourceRange() 7511 << RHS.get()->getSourceRange(); 7512 } 7513 if (LHSIsNull && !RHSIsNull) 7514 LHS = ImpCastExprToType(LHS.take(), RHSType, 7515 RHSType->isPointerType() ? CK_BitCast 7516 : CK_AnyPointerToBlockPointerCast); 7517 else 7518 RHS = ImpCastExprToType(RHS.take(), LHSType, 7519 LHSType->isPointerType() ? CK_BitCast 7520 : CK_AnyPointerToBlockPointerCast); 7521 return ResultTy; 7522 } 7523 7524 if (LHSType->isObjCObjectPointerType() || 7525 RHSType->isObjCObjectPointerType()) { 7526 const PointerType *LPT = LHSType->getAs<PointerType>(); 7527 const PointerType *RPT = RHSType->getAs<PointerType>(); 7528 if (LPT || RPT) { 7529 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7530 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7531 7532 if (!LPtrToVoid && !RPtrToVoid && 7533 !Context.typesAreCompatible(LHSType, RHSType)) { 7534 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7535 /*isError*/false); 7536 } 7537 if (LHSIsNull && !RHSIsNull) 7538 LHS = ImpCastExprToType(LHS.take(), RHSType, 7539 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7540 else 7541 RHS = ImpCastExprToType(RHS.take(), LHSType, 7542 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7543 return ResultTy; 7544 } 7545 if (LHSType->isObjCObjectPointerType() && 7546 RHSType->isObjCObjectPointerType()) { 7547 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7548 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7549 /*isError*/false); 7550 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7551 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7552 7553 if (LHSIsNull && !RHSIsNull) 7554 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7555 else 7556 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7557 return ResultTy; 7558 } 7559 } 7560 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7561 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7562 unsigned DiagID = 0; 7563 bool isError = false; 7564 if (LangOpts.DebuggerSupport) { 7565 // Under a debugger, allow the comparison of pointers to integers, 7566 // since users tend to want to compare addresses. 7567 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7568 (RHSIsNull && RHSType->isIntegerType())) { 7569 if (IsRelational && !getLangOpts().CPlusPlus) 7570 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7571 } else if (IsRelational && !getLangOpts().CPlusPlus) 7572 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7573 else if (getLangOpts().CPlusPlus) { 7574 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7575 isError = true; 7576 } else 7577 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7578 7579 if (DiagID) { 7580 Diag(Loc, DiagID) 7581 << LHSType << RHSType << LHS.get()->getSourceRange() 7582 << RHS.get()->getSourceRange(); 7583 if (isError) 7584 return QualType(); 7585 } 7586 7587 if (LHSType->isIntegerType()) 7588 LHS = ImpCastExprToType(LHS.take(), RHSType, 7589 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7590 else 7591 RHS = ImpCastExprToType(RHS.take(), LHSType, 7592 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7593 return ResultTy; 7594 } 7595 7596 // Handle block pointers. 7597 if (!IsRelational && RHSIsNull 7598 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 7599 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 7600 return ResultTy; 7601 } 7602 if (!IsRelational && LHSIsNull 7603 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 7604 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 7605 return ResultTy; 7606 } 7607 7608 return InvalidOperands(Loc, LHS, RHS); 7609 } 7610 7611 7612 // Return a signed type that is of identical size and number of elements. 7613 // For floating point vectors, return an integer type of identical size 7614 // and number of elements. 7615 QualType Sema::GetSignedVectorType(QualType V) { 7616 const VectorType *VTy = V->getAs<VectorType>(); 7617 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7618 if (TypeSize == Context.getTypeSize(Context.CharTy)) 7619 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 7620 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 7621 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 7622 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 7623 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7624 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 7625 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7626 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7627 "Unhandled vector element size in vector compare"); 7628 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7629 } 7630 7631 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 7632 /// operates on extended vector types. Instead of producing an IntTy result, 7633 /// like a scalar comparison, a vector comparison produces a vector of integer 7634 /// types. 7635 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7636 SourceLocation Loc, 7637 bool IsRelational) { 7638 // Check to make sure we're operating on vectors of the same type and width, 7639 // Allowing one side to be a scalar of element type. 7640 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 7641 if (vType.isNull()) 7642 return vType; 7643 7644 QualType LHSType = LHS.get()->getType(); 7645 7646 // If AltiVec, the comparison results in a numeric type, i.e. 7647 // bool for C++, int for C 7648 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 7649 return Context.getLogicalOperationType(); 7650 7651 // For non-floating point types, check for self-comparisons of the form 7652 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7653 // often indicate logic errors in the program. 7654 if (!LHSType->hasFloatingRepresentation()) { 7655 if (DeclRefExpr* DRL 7656 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7657 if (DeclRefExpr* DRR 7658 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7659 if (DRL->getDecl() == DRR->getDecl()) 7660 DiagRuntimeBehavior(Loc, 0, 7661 PDiag(diag::warn_comparison_always) 7662 << 0 // self- 7663 << 2 // "a constant" 7664 ); 7665 } 7666 7667 // Check for comparisons of floating point operands using != and ==. 7668 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 7669 assert (RHS.get()->getType()->hasFloatingRepresentation()); 7670 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7671 } 7672 7673 // Return a signed type for the vector. 7674 return GetSignedVectorType(LHSType); 7675 } 7676 7677 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7678 SourceLocation Loc) { 7679 // Ensure that either both operands are of the same vector type, or 7680 // one operand is of a vector type and the other is of its element type. 7681 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 7682 if (vType.isNull()) 7683 return InvalidOperands(Loc, LHS, RHS); 7684 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 7685 vType->hasFloatingRepresentation()) 7686 return InvalidOperands(Loc, LHS, RHS); 7687 7688 return GetSignedVectorType(LHS.get()->getType()); 7689 } 7690 7691 inline QualType Sema::CheckBitwiseOperands( 7692 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7693 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7694 7695 if (LHS.get()->getType()->isVectorType() || 7696 RHS.get()->getType()->isVectorType()) { 7697 if (LHS.get()->getType()->hasIntegerRepresentation() && 7698 RHS.get()->getType()->hasIntegerRepresentation()) 7699 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7700 7701 return InvalidOperands(Loc, LHS, RHS); 7702 } 7703 7704 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 7705 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 7706 IsCompAssign); 7707 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 7708 return QualType(); 7709 LHS = LHSResult.take(); 7710 RHS = RHSResult.take(); 7711 7712 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 7713 return compType; 7714 return InvalidOperands(Loc, LHS, RHS); 7715 } 7716 7717 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7718 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 7719 7720 // Check vector operands differently. 7721 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 7722 return CheckVectorLogicalOperands(LHS, RHS, Loc); 7723 7724 // Diagnose cases where the user write a logical and/or but probably meant a 7725 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7726 // is a constant. 7727 if (LHS.get()->getType()->isIntegerType() && 7728 !LHS.get()->getType()->isBooleanType() && 7729 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 7730 // Don't warn in macros or template instantiations. 7731 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 7732 // If the RHS can be constant folded, and if it constant folds to something 7733 // that isn't 0 or 1 (which indicate a potential logical operation that 7734 // happened to fold to true/false) then warn. 7735 // Parens on the RHS are ignored. 7736 llvm::APSInt Result; 7737 if (RHS.get()->EvaluateAsInt(Result, Context)) 7738 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 7739 (Result != 0 && Result != 1)) { 7740 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7741 << RHS.get()->getSourceRange() 7742 << (Opc == BO_LAnd ? "&&" : "||"); 7743 // Suggest replacing the logical operator with the bitwise version 7744 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 7745 << (Opc == BO_LAnd ? "&" : "|") 7746 << FixItHint::CreateReplacement(SourceRange( 7747 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 7748 getLangOpts())), 7749 Opc == BO_LAnd ? "&" : "|"); 7750 if (Opc == BO_LAnd) 7751 // Suggest replacing "Foo() && kNonZero" with "Foo()" 7752 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 7753 << FixItHint::CreateRemoval( 7754 SourceRange( 7755 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 7756 0, getSourceManager(), 7757 getLangOpts()), 7758 RHS.get()->getLocEnd())); 7759 } 7760 } 7761 7762 if (!Context.getLangOpts().CPlusPlus) { 7763 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 7764 // not operate on the built-in scalar and vector float types. 7765 if (Context.getLangOpts().OpenCL && 7766 Context.getLangOpts().OpenCLVersion < 120) { 7767 if (LHS.get()->getType()->isFloatingType() || 7768 RHS.get()->getType()->isFloatingType()) 7769 return InvalidOperands(Loc, LHS, RHS); 7770 } 7771 7772 LHS = UsualUnaryConversions(LHS.take()); 7773 if (LHS.isInvalid()) 7774 return QualType(); 7775 7776 RHS = UsualUnaryConversions(RHS.take()); 7777 if (RHS.isInvalid()) 7778 return QualType(); 7779 7780 if (!LHS.get()->getType()->isScalarType() || 7781 !RHS.get()->getType()->isScalarType()) 7782 return InvalidOperands(Loc, LHS, RHS); 7783 7784 return Context.IntTy; 7785 } 7786 7787 // The following is safe because we only use this method for 7788 // non-overloadable operands. 7789 7790 // C++ [expr.log.and]p1 7791 // C++ [expr.log.or]p1 7792 // The operands are both contextually converted to type bool. 7793 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 7794 if (LHSRes.isInvalid()) 7795 return InvalidOperands(Loc, LHS, RHS); 7796 LHS = LHSRes; 7797 7798 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 7799 if (RHSRes.isInvalid()) 7800 return InvalidOperands(Loc, LHS, RHS); 7801 RHS = RHSRes; 7802 7803 // C++ [expr.log.and]p2 7804 // C++ [expr.log.or]p2 7805 // The result is a bool. 7806 return Context.BoolTy; 7807 } 7808 7809 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression 7810 /// is a read-only property; return true if so. A readonly property expression 7811 /// depends on various declarations and thus must be treated specially. 7812 /// 7813 static bool IsReadonlyProperty(Expr *E, Sema &S) { 7814 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 7815 if (!PropExpr) return false; 7816 if (PropExpr->isImplicitProperty()) return false; 7817 7818 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 7819 QualType BaseType = PropExpr->isSuperReceiver() ? 7820 PropExpr->getSuperReceiverType() : 7821 PropExpr->getBase()->getType(); 7822 7823 if (const ObjCObjectPointerType *OPT = 7824 BaseType->getAsObjCInterfacePointerType()) 7825 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 7826 if (S.isPropertyReadonly(PDecl, IFace)) 7827 return true; 7828 return false; 7829 } 7830 7831 static bool IsReadonlyMessage(Expr *E, Sema &S) { 7832 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 7833 if (!ME) return false; 7834 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 7835 ObjCMessageExpr *Base = 7836 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 7837 if (!Base) return false; 7838 return Base->getMethodDecl() != 0; 7839 } 7840 7841 /// Is the given expression (which must be 'const') a reference to a 7842 /// variable which was originally non-const, but which has become 7843 /// 'const' due to being captured within a block? 7844 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 7845 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 7846 assert(E->isLValue() && E->getType().isConstQualified()); 7847 E = E->IgnoreParens(); 7848 7849 // Must be a reference to a declaration from an enclosing scope. 7850 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 7851 if (!DRE) return NCCK_None; 7852 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 7853 7854 // The declaration must be a variable which is not declared 'const'. 7855 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 7856 if (!var) return NCCK_None; 7857 if (var->getType().isConstQualified()) return NCCK_None; 7858 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 7859 7860 // Decide whether the first capture was for a block or a lambda. 7861 DeclContext *DC = S.CurContext; 7862 while (DC->getParent() != var->getDeclContext()) 7863 DC = DC->getParent(); 7864 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 7865 } 7866 7867 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7868 /// emit an error and return true. If so, return false. 7869 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7870 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 7871 SourceLocation OrigLoc = Loc; 7872 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7873 &Loc); 7874 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 7875 IsLV = Expr::MLV_ReadonlyProperty; 7876 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 7877 IsLV = Expr::MLV_InvalidMessageExpression; 7878 if (IsLV == Expr::MLV_Valid) 7879 return false; 7880 7881 unsigned Diag = 0; 7882 bool NeedType = false; 7883 switch (IsLV) { // C99 6.5.16p2 7884 case Expr::MLV_ConstQualified: 7885 Diag = diag::err_typecheck_assign_const; 7886 7887 // Use a specialized diagnostic when we're assigning to an object 7888 // from an enclosing function or block. 7889 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 7890 if (NCCK == NCCK_Block) 7891 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7892 else 7893 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 7894 break; 7895 } 7896 7897 // In ARC, use some specialized diagnostics for occasions where we 7898 // infer 'const'. These are always pseudo-strong variables. 7899 if (S.getLangOpts().ObjCAutoRefCount) { 7900 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 7901 if (declRef && isa<VarDecl>(declRef->getDecl())) { 7902 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 7903 7904 // Use the normal diagnostic if it's pseudo-__strong but the 7905 // user actually wrote 'const'. 7906 if (var->isARCPseudoStrong() && 7907 (!var->getTypeSourceInfo() || 7908 !var->getTypeSourceInfo()->getType().isConstQualified())) { 7909 // There are two pseudo-strong cases: 7910 // - self 7911 ObjCMethodDecl *method = S.getCurMethodDecl(); 7912 if (method && var == method->getSelfDecl()) 7913 Diag = method->isClassMethod() 7914 ? diag::err_typecheck_arc_assign_self_class_method 7915 : diag::err_typecheck_arc_assign_self; 7916 7917 // - fast enumeration variables 7918 else 7919 Diag = diag::err_typecheck_arr_assign_enumeration; 7920 7921 SourceRange Assign; 7922 if (Loc != OrigLoc) 7923 Assign = SourceRange(OrigLoc, OrigLoc); 7924 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7925 // We need to preserve the AST regardless, so migration tool 7926 // can do its job. 7927 return false; 7928 } 7929 } 7930 } 7931 7932 break; 7933 case Expr::MLV_ArrayType: 7934 case Expr::MLV_ArrayTemporary: 7935 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7936 NeedType = true; 7937 break; 7938 case Expr::MLV_NotObjectType: 7939 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7940 NeedType = true; 7941 break; 7942 case Expr::MLV_LValueCast: 7943 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7944 break; 7945 case Expr::MLV_Valid: 7946 llvm_unreachable("did not take early return for MLV_Valid"); 7947 case Expr::MLV_InvalidExpression: 7948 case Expr::MLV_MemberFunction: 7949 case Expr::MLV_ClassTemporary: 7950 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7951 break; 7952 case Expr::MLV_IncompleteType: 7953 case Expr::MLV_IncompleteVoidType: 7954 return S.RequireCompleteType(Loc, E->getType(), 7955 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 7956 case Expr::MLV_DuplicateVectorComponents: 7957 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7958 break; 7959 case Expr::MLV_ReadonlyProperty: 7960 case Expr::MLV_NoSetterProperty: 7961 llvm_unreachable("readonly properties should be processed differently"); 7962 case Expr::MLV_InvalidMessageExpression: 7963 Diag = diag::error_readonly_message_assignment; 7964 break; 7965 case Expr::MLV_SubObjCPropertySetting: 7966 Diag = diag::error_no_subobject_property_setting; 7967 break; 7968 } 7969 7970 SourceRange Assign; 7971 if (Loc != OrigLoc) 7972 Assign = SourceRange(OrigLoc, OrigLoc); 7973 if (NeedType) 7974 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7975 else 7976 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7977 return true; 7978 } 7979 7980 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 7981 SourceLocation Loc, 7982 Sema &Sema) { 7983 // C / C++ fields 7984 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 7985 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 7986 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 7987 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 7988 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 7989 } 7990 7991 // Objective-C instance variables 7992 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 7993 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 7994 if (OL && OR && OL->getDecl() == OR->getDecl()) { 7995 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 7996 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 7997 if (RL && RR && RL->getDecl() == RR->getDecl()) 7998 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 7999 } 8000 } 8001 8002 // C99 6.5.16.1 8003 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8004 SourceLocation Loc, 8005 QualType CompoundType) { 8006 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8007 8008 // Verify that LHS is a modifiable lvalue, and emit error if not. 8009 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8010 return QualType(); 8011 8012 QualType LHSType = LHSExpr->getType(); 8013 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8014 CompoundType; 8015 AssignConvertType ConvTy; 8016 if (CompoundType.isNull()) { 8017 Expr *RHSCheck = RHS.get(); 8018 8019 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8020 8021 QualType LHSTy(LHSType); 8022 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8023 if (RHS.isInvalid()) 8024 return QualType(); 8025 // Special case of NSObject attributes on c-style pointer types. 8026 if (ConvTy == IncompatiblePointer && 8027 ((Context.isObjCNSObjectType(LHSType) && 8028 RHSType->isObjCObjectPointerType()) || 8029 (Context.isObjCNSObjectType(RHSType) && 8030 LHSType->isObjCObjectPointerType()))) 8031 ConvTy = Compatible; 8032 8033 if (ConvTy == Compatible && 8034 LHSType->isObjCObjectType()) 8035 Diag(Loc, diag::err_objc_object_assignment) 8036 << LHSType; 8037 8038 // If the RHS is a unary plus or minus, check to see if they = and + are 8039 // right next to each other. If so, the user may have typo'd "x =+ 4" 8040 // instead of "x += 4". 8041 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8042 RHSCheck = ICE->getSubExpr(); 8043 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8044 if ((UO->getOpcode() == UO_Plus || 8045 UO->getOpcode() == UO_Minus) && 8046 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8047 // Only if the two operators are exactly adjacent. 8048 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8049 // And there is a space or other character before the subexpr of the 8050 // unary +/-. We don't want to warn on "x=-1". 8051 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8052 UO->getSubExpr()->getLocStart().isFileID()) { 8053 Diag(Loc, diag::warn_not_compound_assign) 8054 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8055 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8056 } 8057 } 8058 8059 if (ConvTy == Compatible) { 8060 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8061 // Warn about retain cycles where a block captures the LHS, but 8062 // not if the LHS is a simple variable into which the block is 8063 // being stored...unless that variable can be captured by reference! 8064 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8065 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8066 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8067 checkRetainCycles(LHSExpr, RHS.get()); 8068 8069 // It is safe to assign a weak reference into a strong variable. 8070 // Although this code can still have problems: 8071 // id x = self.weakProp; 8072 // id y = self.weakProp; 8073 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8074 // paths through the function. This should be revisited if 8075 // -Wrepeated-use-of-weak is made flow-sensitive. 8076 DiagnosticsEngine::Level Level = 8077 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8078 RHS.get()->getLocStart()); 8079 if (Level != DiagnosticsEngine::Ignored) 8080 getCurFunction()->markSafeWeakUse(RHS.get()); 8081 8082 } else if (getLangOpts().ObjCAutoRefCount) { 8083 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8084 } 8085 } 8086 } else { 8087 // Compound assignment "x += y" 8088 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8089 } 8090 8091 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8092 RHS.get(), AA_Assigning)) 8093 return QualType(); 8094 8095 CheckForNullPointerDereference(*this, LHSExpr); 8096 8097 // C99 6.5.16p3: The type of an assignment expression is the type of the 8098 // left operand unless the left operand has qualified type, in which case 8099 // it is the unqualified version of the type of the left operand. 8100 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8101 // is converted to the type of the assignment expression (above). 8102 // C++ 5.17p1: the type of the assignment expression is that of its left 8103 // operand. 8104 return (getLangOpts().CPlusPlus 8105 ? LHSType : LHSType.getUnqualifiedType()); 8106 } 8107 8108 // C99 6.5.17 8109 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8110 SourceLocation Loc) { 8111 LHS = S.CheckPlaceholderExpr(LHS.take()); 8112 RHS = S.CheckPlaceholderExpr(RHS.take()); 8113 if (LHS.isInvalid() || RHS.isInvalid()) 8114 return QualType(); 8115 8116 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8117 // operands, but not unary promotions. 8118 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8119 8120 // So we treat the LHS as a ignored value, and in C++ we allow the 8121 // containing site to determine what should be done with the RHS. 8122 LHS = S.IgnoredValueConversions(LHS.take()); 8123 if (LHS.isInvalid()) 8124 return QualType(); 8125 8126 S.DiagnoseUnusedExprResult(LHS.get()); 8127 8128 if (!S.getLangOpts().CPlusPlus) { 8129 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8130 if (RHS.isInvalid()) 8131 return QualType(); 8132 if (!RHS.get()->getType()->isVoidType()) 8133 S.RequireCompleteType(Loc, RHS.get()->getType(), 8134 diag::err_incomplete_type); 8135 } 8136 8137 return RHS.get()->getType(); 8138 } 8139 8140 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8141 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8142 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8143 ExprValueKind &VK, 8144 SourceLocation OpLoc, 8145 bool IsInc, bool IsPrefix) { 8146 if (Op->isTypeDependent()) 8147 return S.Context.DependentTy; 8148 8149 QualType ResType = Op->getType(); 8150 // Atomic types can be used for increment / decrement where the non-atomic 8151 // versions can, so ignore the _Atomic() specifier for the purpose of 8152 // checking. 8153 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8154 ResType = ResAtomicType->getValueType(); 8155 8156 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8157 8158 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8159 // Decrement of bool is not allowed. 8160 if (!IsInc) { 8161 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8162 return QualType(); 8163 } 8164 // Increment of bool sets it to true, but is deprecated. 8165 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8166 } else if (ResType->isRealType()) { 8167 // OK! 8168 } else if (ResType->isPointerType()) { 8169 // C99 6.5.2.4p2, 6.5.6p2 8170 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8171 return QualType(); 8172 } else if (ResType->isObjCObjectPointerType()) { 8173 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8174 // Otherwise, we just need a complete type. 8175 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8176 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8177 return QualType(); 8178 } else if (ResType->isAnyComplexType()) { 8179 // C99 does not support ++/-- on complex types, we allow as an extension. 8180 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8181 << ResType << Op->getSourceRange(); 8182 } else if (ResType->isPlaceholderType()) { 8183 ExprResult PR = S.CheckPlaceholderExpr(Op); 8184 if (PR.isInvalid()) return QualType(); 8185 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8186 IsInc, IsPrefix); 8187 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8188 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8189 } else { 8190 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8191 << ResType << int(IsInc) << Op->getSourceRange(); 8192 return QualType(); 8193 } 8194 // At this point, we know we have a real, complex or pointer type. 8195 // Now make sure the operand is a modifiable lvalue. 8196 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8197 return QualType(); 8198 // In C++, a prefix increment is the same type as the operand. Otherwise 8199 // (in C or with postfix), the increment is the unqualified type of the 8200 // operand. 8201 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8202 VK = VK_LValue; 8203 return ResType; 8204 } else { 8205 VK = VK_RValue; 8206 return ResType.getUnqualifiedType(); 8207 } 8208 } 8209 8210 8211 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8212 /// This routine allows us to typecheck complex/recursive expressions 8213 /// where the declaration is needed for type checking. We only need to 8214 /// handle cases when the expression references a function designator 8215 /// or is an lvalue. Here are some examples: 8216 /// - &(x) => x 8217 /// - &*****f => f for f a function designator. 8218 /// - &s.xx => s 8219 /// - &s.zz[1].yy -> s, if zz is an array 8220 /// - *(x + 1) -> x, if x is an array 8221 /// - &"123"[2] -> 0 8222 /// - & __real__ x -> x 8223 static ValueDecl *getPrimaryDecl(Expr *E) { 8224 switch (E->getStmtClass()) { 8225 case Stmt::DeclRefExprClass: 8226 return cast<DeclRefExpr>(E)->getDecl(); 8227 case Stmt::MemberExprClass: 8228 // If this is an arrow operator, the address is an offset from 8229 // the base's value, so the object the base refers to is 8230 // irrelevant. 8231 if (cast<MemberExpr>(E)->isArrow()) 8232 return 0; 8233 // Otherwise, the expression refers to a part of the base 8234 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8235 case Stmt::ArraySubscriptExprClass: { 8236 // FIXME: This code shouldn't be necessary! We should catch the implicit 8237 // promotion of register arrays earlier. 8238 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8239 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8240 if (ICE->getSubExpr()->getType()->isArrayType()) 8241 return getPrimaryDecl(ICE->getSubExpr()); 8242 } 8243 return 0; 8244 } 8245 case Stmt::UnaryOperatorClass: { 8246 UnaryOperator *UO = cast<UnaryOperator>(E); 8247 8248 switch(UO->getOpcode()) { 8249 case UO_Real: 8250 case UO_Imag: 8251 case UO_Extension: 8252 return getPrimaryDecl(UO->getSubExpr()); 8253 default: 8254 return 0; 8255 } 8256 } 8257 case Stmt::ParenExprClass: 8258 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8259 case Stmt::ImplicitCastExprClass: 8260 // If the result of an implicit cast is an l-value, we care about 8261 // the sub-expression; otherwise, the result here doesn't matter. 8262 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8263 default: 8264 return 0; 8265 } 8266 } 8267 8268 namespace { 8269 enum { 8270 AO_Bit_Field = 0, 8271 AO_Vector_Element = 1, 8272 AO_Property_Expansion = 2, 8273 AO_Register_Variable = 3, 8274 AO_No_Error = 4 8275 }; 8276 } 8277 /// \brief Diagnose invalid operand for address of operations. 8278 /// 8279 /// \param Type The type of operand which cannot have its address taken. 8280 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8281 Expr *E, unsigned Type) { 8282 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8283 } 8284 8285 /// CheckAddressOfOperand - The operand of & must be either a function 8286 /// designator or an lvalue designating an object. If it is an lvalue, the 8287 /// object cannot be declared with storage class register or be a bit field. 8288 /// Note: The usual conversions are *not* applied to the operand of the & 8289 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8290 /// In C++, the operand might be an overloaded function name, in which case 8291 /// we allow the '&' but retain the overloaded-function type. 8292 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 8293 SourceLocation OpLoc) { 8294 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8295 if (PTy->getKind() == BuiltinType::Overload) { 8296 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 8297 assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode() 8298 == UO_AddrOf); 8299 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8300 << OrigOp.get()->getSourceRange(); 8301 return QualType(); 8302 } 8303 8304 return S.Context.OverloadTy; 8305 } 8306 8307 if (PTy->getKind() == BuiltinType::UnknownAny) 8308 return S.Context.UnknownAnyTy; 8309 8310 if (PTy->getKind() == BuiltinType::BoundMember) { 8311 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8312 << OrigOp.get()->getSourceRange(); 8313 return QualType(); 8314 } 8315 8316 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 8317 if (OrigOp.isInvalid()) return QualType(); 8318 } 8319 8320 if (OrigOp.get()->isTypeDependent()) 8321 return S.Context.DependentTy; 8322 8323 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8324 8325 // Make sure to ignore parentheses in subsequent checks 8326 Expr *op = OrigOp.get()->IgnoreParens(); 8327 8328 if (S.getLangOpts().C99) { 8329 // Implement C99-only parts of addressof rules. 8330 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8331 if (uOp->getOpcode() == UO_Deref) 8332 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8333 // (assuming the deref expression is valid). 8334 return uOp->getSubExpr()->getType(); 8335 } 8336 // Technically, there should be a check for array subscript 8337 // expressions here, but the result of one is always an lvalue anyway. 8338 } 8339 ValueDecl *dcl = getPrimaryDecl(op); 8340 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 8341 unsigned AddressOfError = AO_No_Error; 8342 8343 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8344 bool sfinae = (bool)S.isSFINAEContext(); 8345 S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8346 : diag::ext_typecheck_addrof_temporary) 8347 << op->getType() << op->getSourceRange(); 8348 if (sfinae) 8349 return QualType(); 8350 // Materialize the temporary as an lvalue so that we can take its address. 8351 OrigOp = op = new (S.Context) 8352 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true); 8353 } else if (isa<ObjCSelectorExpr>(op)) { 8354 return S.Context.getPointerType(op->getType()); 8355 } else if (lval == Expr::LV_MemberFunction) { 8356 // If it's an instance method, make a member pointer. 8357 // The expression must have exactly the form &A::foo. 8358 8359 // If the underlying expression isn't a decl ref, give up. 8360 if (!isa<DeclRefExpr>(op)) { 8361 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8362 << OrigOp.get()->getSourceRange(); 8363 return QualType(); 8364 } 8365 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8366 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8367 8368 // The id-expression was parenthesized. 8369 if (OrigOp.get() != DRE) { 8370 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 8371 << OrigOp.get()->getSourceRange(); 8372 8373 // The method was named without a qualifier. 8374 } else if (!DRE->getQualifier()) { 8375 if (MD->getParent()->getName().empty()) 8376 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8377 << op->getSourceRange(); 8378 else { 8379 SmallString<32> Str; 8380 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8381 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8382 << op->getSourceRange() 8383 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8384 } 8385 } 8386 8387 return S.Context.getMemberPointerType(op->getType(), 8388 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8389 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8390 // C99 6.5.3.2p1 8391 // The operand must be either an l-value or a function designator 8392 if (!op->getType()->isFunctionType()) { 8393 // Use a special diagnostic for loads from property references. 8394 if (isa<PseudoObjectExpr>(op)) { 8395 AddressOfError = AO_Property_Expansion; 8396 } else { 8397 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8398 << op->getType() << op->getSourceRange(); 8399 return QualType(); 8400 } 8401 } 8402 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8403 // The operand cannot be a bit-field 8404 AddressOfError = AO_Bit_Field; 8405 } else if (op->getObjectKind() == OK_VectorComponent) { 8406 // The operand cannot be an element of a vector 8407 AddressOfError = AO_Vector_Element; 8408 } else if (dcl) { // C99 6.5.3.2p1 8409 // We have an lvalue with a decl. Make sure the decl is not declared 8410 // with the register storage-class specifier. 8411 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8412 // in C++ it is not error to take address of a register 8413 // variable (c++03 7.1.1P3) 8414 if (vd->getStorageClass() == SC_Register && 8415 !S.getLangOpts().CPlusPlus) { 8416 AddressOfError = AO_Register_Variable; 8417 } 8418 } else if (isa<FunctionTemplateDecl>(dcl)) { 8419 return S.Context.OverloadTy; 8420 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8421 // Okay: we can take the address of a field. 8422 // Could be a pointer to member, though, if there is an explicit 8423 // scope qualifier for the class. 8424 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8425 DeclContext *Ctx = dcl->getDeclContext(); 8426 if (Ctx && Ctx->isRecord()) { 8427 if (dcl->getType()->isReferenceType()) { 8428 S.Diag(OpLoc, 8429 diag::err_cannot_form_pointer_to_member_of_reference_type) 8430 << dcl->getDeclName() << dcl->getType(); 8431 return QualType(); 8432 } 8433 8434 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8435 Ctx = Ctx->getParent(); 8436 return S.Context.getMemberPointerType(op->getType(), 8437 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8438 } 8439 } 8440 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8441 llvm_unreachable("Unknown/unexpected decl type"); 8442 } 8443 8444 if (AddressOfError != AO_No_Error) { 8445 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 8446 return QualType(); 8447 } 8448 8449 if (lval == Expr::LV_IncompleteVoidType) { 8450 // Taking the address of a void variable is technically illegal, but we 8451 // allow it in cases which are otherwise valid. 8452 // Example: "extern void x; void* y = &x;". 8453 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8454 } 8455 8456 // If the operand has type "type", the result has type "pointer to type". 8457 if (op->getType()->isObjCObjectType()) 8458 return S.Context.getObjCObjectPointerType(op->getType()); 8459 return S.Context.getPointerType(op->getType()); 8460 } 8461 8462 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8463 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8464 SourceLocation OpLoc) { 8465 if (Op->isTypeDependent()) 8466 return S.Context.DependentTy; 8467 8468 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8469 if (ConvResult.isInvalid()) 8470 return QualType(); 8471 Op = ConvResult.take(); 8472 QualType OpTy = Op->getType(); 8473 QualType Result; 8474 8475 if (isa<CXXReinterpretCastExpr>(Op)) { 8476 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8477 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8478 Op->getSourceRange()); 8479 } 8480 8481 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8482 // is an incomplete type or void. It would be possible to warn about 8483 // dereferencing a void pointer, but it's completely well-defined, and such a 8484 // warning is unlikely to catch any mistakes. 8485 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8486 Result = PT->getPointeeType(); 8487 else if (const ObjCObjectPointerType *OPT = 8488 OpTy->getAs<ObjCObjectPointerType>()) 8489 Result = OPT->getPointeeType(); 8490 else { 8491 ExprResult PR = S.CheckPlaceholderExpr(Op); 8492 if (PR.isInvalid()) return QualType(); 8493 if (PR.take() != Op) 8494 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8495 } 8496 8497 if (Result.isNull()) { 8498 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8499 << OpTy << Op->getSourceRange(); 8500 return QualType(); 8501 } 8502 8503 // Dereferences are usually l-values... 8504 VK = VK_LValue; 8505 8506 // ...except that certain expressions are never l-values in C. 8507 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8508 VK = VK_RValue; 8509 8510 return Result; 8511 } 8512 8513 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8514 tok::TokenKind Kind) { 8515 BinaryOperatorKind Opc; 8516 switch (Kind) { 8517 default: llvm_unreachable("Unknown binop!"); 8518 case tok::periodstar: Opc = BO_PtrMemD; break; 8519 case tok::arrowstar: Opc = BO_PtrMemI; break; 8520 case tok::star: Opc = BO_Mul; break; 8521 case tok::slash: Opc = BO_Div; break; 8522 case tok::percent: Opc = BO_Rem; break; 8523 case tok::plus: Opc = BO_Add; break; 8524 case tok::minus: Opc = BO_Sub; break; 8525 case tok::lessless: Opc = BO_Shl; break; 8526 case tok::greatergreater: Opc = BO_Shr; break; 8527 case tok::lessequal: Opc = BO_LE; break; 8528 case tok::less: Opc = BO_LT; break; 8529 case tok::greaterequal: Opc = BO_GE; break; 8530 case tok::greater: Opc = BO_GT; break; 8531 case tok::exclaimequal: Opc = BO_NE; break; 8532 case tok::equalequal: Opc = BO_EQ; break; 8533 case tok::amp: Opc = BO_And; break; 8534 case tok::caret: Opc = BO_Xor; break; 8535 case tok::pipe: Opc = BO_Or; break; 8536 case tok::ampamp: Opc = BO_LAnd; break; 8537 case tok::pipepipe: Opc = BO_LOr; break; 8538 case tok::equal: Opc = BO_Assign; break; 8539 case tok::starequal: Opc = BO_MulAssign; break; 8540 case tok::slashequal: Opc = BO_DivAssign; break; 8541 case tok::percentequal: Opc = BO_RemAssign; break; 8542 case tok::plusequal: Opc = BO_AddAssign; break; 8543 case tok::minusequal: Opc = BO_SubAssign; break; 8544 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8545 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8546 case tok::ampequal: Opc = BO_AndAssign; break; 8547 case tok::caretequal: Opc = BO_XorAssign; break; 8548 case tok::pipeequal: Opc = BO_OrAssign; break; 8549 case tok::comma: Opc = BO_Comma; break; 8550 } 8551 return Opc; 8552 } 8553 8554 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8555 tok::TokenKind Kind) { 8556 UnaryOperatorKind Opc; 8557 switch (Kind) { 8558 default: llvm_unreachable("Unknown unary op!"); 8559 case tok::plusplus: Opc = UO_PreInc; break; 8560 case tok::minusminus: Opc = UO_PreDec; break; 8561 case tok::amp: Opc = UO_AddrOf; break; 8562 case tok::star: Opc = UO_Deref; break; 8563 case tok::plus: Opc = UO_Plus; break; 8564 case tok::minus: Opc = UO_Minus; break; 8565 case tok::tilde: Opc = UO_Not; break; 8566 case tok::exclaim: Opc = UO_LNot; break; 8567 case tok::kw___real: Opc = UO_Real; break; 8568 case tok::kw___imag: Opc = UO_Imag; break; 8569 case tok::kw___extension__: Opc = UO_Extension; break; 8570 } 8571 return Opc; 8572 } 8573 8574 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8575 /// This warning is only emitted for builtin assignment operations. It is also 8576 /// suppressed in the event of macro expansions. 8577 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8578 SourceLocation OpLoc) { 8579 if (!S.ActiveTemplateInstantiations.empty()) 8580 return; 8581 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8582 return; 8583 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8584 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8585 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8586 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8587 if (!LHSDeclRef || !RHSDeclRef || 8588 LHSDeclRef->getLocation().isMacroID() || 8589 RHSDeclRef->getLocation().isMacroID()) 8590 return; 8591 const ValueDecl *LHSDecl = 8592 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8593 const ValueDecl *RHSDecl = 8594 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8595 if (LHSDecl != RHSDecl) 8596 return; 8597 if (LHSDecl->getType().isVolatileQualified()) 8598 return; 8599 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 8600 if (RefTy->getPointeeType().isVolatileQualified()) 8601 return; 8602 8603 S.Diag(OpLoc, diag::warn_self_assignment) 8604 << LHSDeclRef->getType() 8605 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8606 } 8607 8608 /// Check if a bitwise-& is performed on an Objective-C pointer. This 8609 /// is usually indicative of introspection within the Objective-C pointer. 8610 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 8611 SourceLocation OpLoc) { 8612 if (!S.getLangOpts().ObjC1) 8613 return; 8614 8615 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 8616 const Expr *LHS = L.get(); 8617 const Expr *RHS = R.get(); 8618 8619 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8620 ObjCPointerExpr = LHS; 8621 OtherExpr = RHS; 8622 } 8623 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8624 ObjCPointerExpr = RHS; 8625 OtherExpr = LHS; 8626 } 8627 8628 // This warning is deliberately made very specific to reduce false 8629 // positives with logic that uses '&' for hashing. This logic mainly 8630 // looks for code trying to introspect into tagged pointers, which 8631 // code should generally never do. 8632 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 8633 S.Diag(OpLoc, diag::warn_objc_pointer_masking) 8634 << ObjCPointerExpr->getSourceRange(); 8635 } 8636 } 8637 8638 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 8639 /// operator @p Opc at location @c TokLoc. This routine only supports 8640 /// built-in operations; ActOnBinOp handles overloaded operators. 8641 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8642 BinaryOperatorKind Opc, 8643 Expr *LHSExpr, Expr *RHSExpr) { 8644 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 8645 // The syntax only allows initializer lists on the RHS of assignment, 8646 // so we don't need to worry about accepting invalid code for 8647 // non-assignment operators. 8648 // C++11 5.17p9: 8649 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 8650 // of x = {} is x = T(). 8651 InitializationKind Kind = 8652 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 8653 InitializedEntity Entity = 8654 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 8655 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 8656 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 8657 if (Init.isInvalid()) 8658 return Init; 8659 RHSExpr = Init.take(); 8660 } 8661 8662 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 8663 QualType ResultTy; // Result type of the binary operator. 8664 // The following two variables are used for compound assignment operators 8665 QualType CompLHSTy; // Type of LHS after promotions for computation 8666 QualType CompResultTy; // Type of computation result 8667 ExprValueKind VK = VK_RValue; 8668 ExprObjectKind OK = OK_Ordinary; 8669 8670 switch (Opc) { 8671 case BO_Assign: 8672 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 8673 if (getLangOpts().CPlusPlus && 8674 LHS.get()->getObjectKind() != OK_ObjCProperty) { 8675 VK = LHS.get()->getValueKind(); 8676 OK = LHS.get()->getObjectKind(); 8677 } 8678 if (!ResultTy.isNull()) 8679 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 8680 break; 8681 case BO_PtrMemD: 8682 case BO_PtrMemI: 8683 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 8684 Opc == BO_PtrMemI); 8685 break; 8686 case BO_Mul: 8687 case BO_Div: 8688 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 8689 Opc == BO_Div); 8690 break; 8691 case BO_Rem: 8692 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 8693 break; 8694 case BO_Add: 8695 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 8696 break; 8697 case BO_Sub: 8698 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 8699 break; 8700 case BO_Shl: 8701 case BO_Shr: 8702 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 8703 break; 8704 case BO_LE: 8705 case BO_LT: 8706 case BO_GE: 8707 case BO_GT: 8708 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 8709 break; 8710 case BO_EQ: 8711 case BO_NE: 8712 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 8713 break; 8714 case BO_And: 8715 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 8716 case BO_Xor: 8717 case BO_Or: 8718 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 8719 break; 8720 case BO_LAnd: 8721 case BO_LOr: 8722 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 8723 break; 8724 case BO_MulAssign: 8725 case BO_DivAssign: 8726 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 8727 Opc == BO_DivAssign); 8728 CompLHSTy = CompResultTy; 8729 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8730 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8731 break; 8732 case BO_RemAssign: 8733 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 8734 CompLHSTy = CompResultTy; 8735 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8736 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8737 break; 8738 case BO_AddAssign: 8739 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 8740 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8741 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8742 break; 8743 case BO_SubAssign: 8744 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 8745 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8746 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8747 break; 8748 case BO_ShlAssign: 8749 case BO_ShrAssign: 8750 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 8751 CompLHSTy = CompResultTy; 8752 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8753 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8754 break; 8755 case BO_AndAssign: 8756 case BO_XorAssign: 8757 case BO_OrAssign: 8758 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 8759 CompLHSTy = CompResultTy; 8760 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8761 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8762 break; 8763 case BO_Comma: 8764 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 8765 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 8766 VK = RHS.get()->getValueKind(); 8767 OK = RHS.get()->getObjectKind(); 8768 } 8769 break; 8770 } 8771 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 8772 return ExprError(); 8773 8774 // Check for array bounds violations for both sides of the BinaryOperator 8775 CheckArrayAccess(LHS.get()); 8776 CheckArrayAccess(RHS.get()); 8777 8778 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 8779 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 8780 &Context.Idents.get("object_setClass"), 8781 SourceLocation(), LookupOrdinaryName); 8782 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 8783 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 8784 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 8785 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 8786 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 8787 FixItHint::CreateInsertion(RHSLocEnd, ")"); 8788 } 8789 else 8790 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 8791 } 8792 else if (const ObjCIvarRefExpr *OIRE = 8793 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 8794 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 8795 8796 if (CompResultTy.isNull()) 8797 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 8798 ResultTy, VK, OK, OpLoc, 8799 FPFeatures.fp_contract)); 8800 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 8801 OK_ObjCProperty) { 8802 VK = VK_LValue; 8803 OK = LHS.get()->getObjectKind(); 8804 } 8805 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 8806 ResultTy, VK, OK, CompLHSTy, 8807 CompResultTy, OpLoc, 8808 FPFeatures.fp_contract)); 8809 } 8810 8811 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 8812 /// operators are mixed in a way that suggests that the programmer forgot that 8813 /// comparison operators have higher precedence. The most typical example of 8814 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 8815 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 8816 SourceLocation OpLoc, Expr *LHSExpr, 8817 Expr *RHSExpr) { 8818 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 8819 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 8820 8821 // Check that one of the sides is a comparison operator. 8822 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 8823 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 8824 if (!isLeftComp && !isRightComp) 8825 return; 8826 8827 // Bitwise operations are sometimes used as eager logical ops. 8828 // Don't diagnose this. 8829 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 8830 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 8831 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 8832 return; 8833 8834 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 8835 OpLoc) 8836 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 8837 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 8838 SourceRange ParensRange = isLeftComp ? 8839 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 8840 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 8841 8842 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 8843 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 8844 SuggestParentheses(Self, OpLoc, 8845 Self.PDiag(diag::note_precedence_silence) << OpStr, 8846 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 8847 SuggestParentheses(Self, OpLoc, 8848 Self.PDiag(diag::note_precedence_bitwise_first) 8849 << BinaryOperator::getOpcodeStr(Opc), 8850 ParensRange); 8851 } 8852 8853 /// \brief It accepts a '&' expr that is inside a '|' one. 8854 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 8855 /// in parentheses. 8856 static void 8857 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 8858 BinaryOperator *Bop) { 8859 assert(Bop->getOpcode() == BO_And); 8860 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 8861 << Bop->getSourceRange() << OpLoc; 8862 SuggestParentheses(Self, Bop->getOperatorLoc(), 8863 Self.PDiag(diag::note_precedence_silence) 8864 << Bop->getOpcodeStr(), 8865 Bop->getSourceRange()); 8866 } 8867 8868 /// \brief It accepts a '&&' expr that is inside a '||' one. 8869 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 8870 /// in parentheses. 8871 static void 8872 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 8873 BinaryOperator *Bop) { 8874 assert(Bop->getOpcode() == BO_LAnd); 8875 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 8876 << Bop->getSourceRange() << OpLoc; 8877 SuggestParentheses(Self, Bop->getOperatorLoc(), 8878 Self.PDiag(diag::note_precedence_silence) 8879 << Bop->getOpcodeStr(), 8880 Bop->getSourceRange()); 8881 } 8882 8883 /// \brief Returns true if the given expression can be evaluated as a constant 8884 /// 'true'. 8885 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 8886 bool Res; 8887 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 8888 } 8889 8890 /// \brief Returns true if the given expression can be evaluated as a constant 8891 /// 'false'. 8892 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 8893 bool Res; 8894 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 8895 } 8896 8897 /// \brief Look for '&&' in the left hand of a '||' expr. 8898 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 8899 Expr *LHSExpr, Expr *RHSExpr) { 8900 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 8901 if (Bop->getOpcode() == BO_LAnd) { 8902 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 8903 if (EvaluatesAsFalse(S, RHSExpr)) 8904 return; 8905 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 8906 if (!EvaluatesAsTrue(S, Bop->getLHS())) 8907 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8908 } else if (Bop->getOpcode() == BO_LOr) { 8909 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 8910 // If it's "a || b && 1 || c" we didn't warn earlier for 8911 // "a || b && 1", but warn now. 8912 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 8913 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 8914 } 8915 } 8916 } 8917 } 8918 8919 /// \brief Look for '&&' in the right hand of a '||' expr. 8920 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 8921 Expr *LHSExpr, Expr *RHSExpr) { 8922 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 8923 if (Bop->getOpcode() == BO_LAnd) { 8924 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 8925 if (EvaluatesAsFalse(S, LHSExpr)) 8926 return; 8927 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 8928 if (!EvaluatesAsTrue(S, Bop->getRHS())) 8929 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8930 } 8931 } 8932 } 8933 8934 /// \brief Look for '&' in the left or right hand of a '|' expr. 8935 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 8936 Expr *OrArg) { 8937 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 8938 if (Bop->getOpcode() == BO_And) 8939 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 8940 } 8941 } 8942 8943 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 8944 Expr *SubExpr, StringRef Shift) { 8945 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 8946 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 8947 StringRef Op = Bop->getOpcodeStr(); 8948 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 8949 << Bop->getSourceRange() << OpLoc << Shift << Op; 8950 SuggestParentheses(S, Bop->getOperatorLoc(), 8951 S.PDiag(diag::note_precedence_silence) << Op, 8952 Bop->getSourceRange()); 8953 } 8954 } 8955 } 8956 8957 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 8958 Expr *LHSExpr, Expr *RHSExpr) { 8959 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 8960 if (!OCE) 8961 return; 8962 8963 FunctionDecl *FD = OCE->getDirectCallee(); 8964 if (!FD || !FD->isOverloadedOperator()) 8965 return; 8966 8967 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 8968 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 8969 return; 8970 8971 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 8972 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 8973 << (Kind == OO_LessLess); 8974 SuggestParentheses(S, OCE->getOperatorLoc(), 8975 S.PDiag(diag::note_precedence_silence) 8976 << (Kind == OO_LessLess ? "<<" : ">>"), 8977 OCE->getSourceRange()); 8978 SuggestParentheses(S, OpLoc, 8979 S.PDiag(diag::note_evaluate_comparison_first), 8980 SourceRange(OCE->getArg(1)->getLocStart(), 8981 RHSExpr->getLocEnd())); 8982 } 8983 8984 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 8985 /// precedence. 8986 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 8987 SourceLocation OpLoc, Expr *LHSExpr, 8988 Expr *RHSExpr){ 8989 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 8990 if (BinaryOperator::isBitwiseOp(Opc)) 8991 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 8992 8993 // Diagnose "arg1 & arg2 | arg3" 8994 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8995 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 8996 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 8997 } 8998 8999 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9000 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9001 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9002 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9003 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9004 } 9005 9006 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9007 || Opc == BO_Shr) { 9008 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9009 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9010 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9011 } 9012 9013 // Warn on overloaded shift operators and comparisons, such as: 9014 // cout << 5 == 4; 9015 if (BinaryOperator::isComparisonOp(Opc)) 9016 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9017 } 9018 9019 // Binary Operators. 'Tok' is the token for the operator. 9020 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9021 tok::TokenKind Kind, 9022 Expr *LHSExpr, Expr *RHSExpr) { 9023 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9024 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9025 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9026 9027 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9028 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9029 9030 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9031 } 9032 9033 /// Build an overloaded binary operator expression in the given scope. 9034 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9035 BinaryOperatorKind Opc, 9036 Expr *LHS, Expr *RHS) { 9037 // Find all of the overloaded operators visible from this 9038 // point. We perform both an operator-name lookup from the local 9039 // scope and an argument-dependent lookup based on the types of 9040 // the arguments. 9041 UnresolvedSet<16> Functions; 9042 OverloadedOperatorKind OverOp 9043 = BinaryOperator::getOverloadedOperator(Opc); 9044 if (Sc && OverOp != OO_None) 9045 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9046 RHS->getType(), Functions); 9047 9048 // Build the (potentially-overloaded, potentially-dependent) 9049 // binary operation. 9050 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9051 } 9052 9053 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9054 BinaryOperatorKind Opc, 9055 Expr *LHSExpr, Expr *RHSExpr) { 9056 // We want to end up calling one of checkPseudoObjectAssignment 9057 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9058 // both expressions are overloadable or either is type-dependent), 9059 // or CreateBuiltinBinOp (in any other case). We also want to get 9060 // any placeholder types out of the way. 9061 9062 // Handle pseudo-objects in the LHS. 9063 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9064 // Assignments with a pseudo-object l-value need special analysis. 9065 if (pty->getKind() == BuiltinType::PseudoObject && 9066 BinaryOperator::isAssignmentOp(Opc)) 9067 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9068 9069 // Don't resolve overloads if the other type is overloadable. 9070 if (pty->getKind() == BuiltinType::Overload) { 9071 // We can't actually test that if we still have a placeholder, 9072 // though. Fortunately, none of the exceptions we see in that 9073 // code below are valid when the LHS is an overload set. Note 9074 // that an overload set can be dependently-typed, but it never 9075 // instantiates to having an overloadable type. 9076 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9077 if (resolvedRHS.isInvalid()) return ExprError(); 9078 RHSExpr = resolvedRHS.take(); 9079 9080 if (RHSExpr->isTypeDependent() || 9081 RHSExpr->getType()->isOverloadableType()) 9082 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9083 } 9084 9085 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9086 if (LHS.isInvalid()) return ExprError(); 9087 LHSExpr = LHS.take(); 9088 } 9089 9090 // Handle pseudo-objects in the RHS. 9091 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9092 // An overload in the RHS can potentially be resolved by the type 9093 // being assigned to. 9094 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9095 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9096 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9097 9098 if (LHSExpr->getType()->isOverloadableType()) 9099 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9100 9101 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9102 } 9103 9104 // Don't resolve overloads if the other type is overloadable. 9105 if (pty->getKind() == BuiltinType::Overload && 9106 LHSExpr->getType()->isOverloadableType()) 9107 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9108 9109 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9110 if (!resolvedRHS.isUsable()) return ExprError(); 9111 RHSExpr = resolvedRHS.take(); 9112 } 9113 9114 if (getLangOpts().CPlusPlus) { 9115 // If either expression is type-dependent, always build an 9116 // overloaded op. 9117 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9118 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9119 9120 // Otherwise, build an overloaded op if either expression has an 9121 // overloadable type. 9122 if (LHSExpr->getType()->isOverloadableType() || 9123 RHSExpr->getType()->isOverloadableType()) 9124 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9125 } 9126 9127 // Build a built-in binary operation. 9128 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9129 } 9130 9131 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9132 UnaryOperatorKind Opc, 9133 Expr *InputExpr) { 9134 ExprResult Input = Owned(InputExpr); 9135 ExprValueKind VK = VK_RValue; 9136 ExprObjectKind OK = OK_Ordinary; 9137 QualType resultType; 9138 switch (Opc) { 9139 case UO_PreInc: 9140 case UO_PreDec: 9141 case UO_PostInc: 9142 case UO_PostDec: 9143 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9144 Opc == UO_PreInc || 9145 Opc == UO_PostInc, 9146 Opc == UO_PreInc || 9147 Opc == UO_PreDec); 9148 break; 9149 case UO_AddrOf: 9150 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 9151 break; 9152 case UO_Deref: { 9153 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9154 if (Input.isInvalid()) return ExprError(); 9155 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9156 break; 9157 } 9158 case UO_Plus: 9159 case UO_Minus: 9160 Input = UsualUnaryConversions(Input.take()); 9161 if (Input.isInvalid()) return ExprError(); 9162 resultType = Input.get()->getType(); 9163 if (resultType->isDependentType()) 9164 break; 9165 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9166 resultType->isVectorType()) 9167 break; 9168 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7 9169 resultType->isEnumeralType()) 9170 break; 9171 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9172 Opc == UO_Plus && 9173 resultType->isPointerType()) 9174 break; 9175 9176 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9177 << resultType << Input.get()->getSourceRange()); 9178 9179 case UO_Not: // bitwise complement 9180 Input = UsualUnaryConversions(Input.take()); 9181 if (Input.isInvalid()) 9182 return ExprError(); 9183 resultType = Input.get()->getType(); 9184 if (resultType->isDependentType()) 9185 break; 9186 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9187 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9188 // C99 does not support '~' for complex conjugation. 9189 Diag(OpLoc, diag::ext_integer_complement_complex) 9190 << resultType << Input.get()->getSourceRange(); 9191 else if (resultType->hasIntegerRepresentation()) 9192 break; 9193 else if (resultType->isExtVectorType()) { 9194 if (Context.getLangOpts().OpenCL) { 9195 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9196 // on vector float types. 9197 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9198 if (!T->isIntegerType()) 9199 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9200 << resultType << Input.get()->getSourceRange()); 9201 } 9202 break; 9203 } else { 9204 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9205 << resultType << Input.get()->getSourceRange()); 9206 } 9207 break; 9208 9209 case UO_LNot: // logical negation 9210 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9211 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9212 if (Input.isInvalid()) return ExprError(); 9213 resultType = Input.get()->getType(); 9214 9215 // Though we still have to promote half FP to float... 9216 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9217 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9218 resultType = Context.FloatTy; 9219 } 9220 9221 if (resultType->isDependentType()) 9222 break; 9223 if (resultType->isScalarType()) { 9224 // C99 6.5.3.3p1: ok, fallthrough; 9225 if (Context.getLangOpts().CPlusPlus) { 9226 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9227 // operand contextually converted to bool. 9228 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9229 ScalarTypeToBooleanCastKind(resultType)); 9230 } else if (Context.getLangOpts().OpenCL && 9231 Context.getLangOpts().OpenCLVersion < 120) { 9232 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9233 // operate on scalar float types. 9234 if (!resultType->isIntegerType()) 9235 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9236 << resultType << Input.get()->getSourceRange()); 9237 } 9238 } else if (resultType->isExtVectorType()) { 9239 if (Context.getLangOpts().OpenCL && 9240 Context.getLangOpts().OpenCLVersion < 120) { 9241 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9242 // operate on vector float types. 9243 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9244 if (!T->isIntegerType()) 9245 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9246 << resultType << Input.get()->getSourceRange()); 9247 } 9248 // Vector logical not returns the signed variant of the operand type. 9249 resultType = GetSignedVectorType(resultType); 9250 break; 9251 } else { 9252 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9253 << resultType << Input.get()->getSourceRange()); 9254 } 9255 9256 // LNot always has type int. C99 6.5.3.3p5. 9257 // In C++, it's bool. C++ 5.3.1p8 9258 resultType = Context.getLogicalOperationType(); 9259 break; 9260 case UO_Real: 9261 case UO_Imag: 9262 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9263 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9264 // complex l-values to ordinary l-values and all other values to r-values. 9265 if (Input.isInvalid()) return ExprError(); 9266 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9267 if (Input.get()->getValueKind() != VK_RValue && 9268 Input.get()->getObjectKind() == OK_Ordinary) 9269 VK = Input.get()->getValueKind(); 9270 } else if (!getLangOpts().CPlusPlus) { 9271 // In C, a volatile scalar is read by __imag. In C++, it is not. 9272 Input = DefaultLvalueConversion(Input.take()); 9273 } 9274 break; 9275 case UO_Extension: 9276 resultType = Input.get()->getType(); 9277 VK = Input.get()->getValueKind(); 9278 OK = Input.get()->getObjectKind(); 9279 break; 9280 } 9281 if (resultType.isNull() || Input.isInvalid()) 9282 return ExprError(); 9283 9284 // Check for array bounds violations in the operand of the UnaryOperator, 9285 // except for the '*' and '&' operators that have to be handled specially 9286 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9287 // that are explicitly defined as valid by the standard). 9288 if (Opc != UO_AddrOf && Opc != UO_Deref) 9289 CheckArrayAccess(Input.get()); 9290 9291 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9292 VK, OK, OpLoc)); 9293 } 9294 9295 /// \brief Determine whether the given expression is a qualified member 9296 /// access expression, of a form that could be turned into a pointer to member 9297 /// with the address-of operator. 9298 static bool isQualifiedMemberAccess(Expr *E) { 9299 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9300 if (!DRE->getQualifier()) 9301 return false; 9302 9303 ValueDecl *VD = DRE->getDecl(); 9304 if (!VD->isCXXClassMember()) 9305 return false; 9306 9307 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9308 return true; 9309 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9310 return Method->isInstance(); 9311 9312 return false; 9313 } 9314 9315 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9316 if (!ULE->getQualifier()) 9317 return false; 9318 9319 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9320 DEnd = ULE->decls_end(); 9321 D != DEnd; ++D) { 9322 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9323 if (Method->isInstance()) 9324 return true; 9325 } else { 9326 // Overload set does not contain methods. 9327 break; 9328 } 9329 } 9330 9331 return false; 9332 } 9333 9334 return false; 9335 } 9336 9337 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9338 UnaryOperatorKind Opc, Expr *Input) { 9339 // First things first: handle placeholders so that the 9340 // overloaded-operator check considers the right type. 9341 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9342 // Increment and decrement of pseudo-object references. 9343 if (pty->getKind() == BuiltinType::PseudoObject && 9344 UnaryOperator::isIncrementDecrementOp(Opc)) 9345 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9346 9347 // extension is always a builtin operator. 9348 if (Opc == UO_Extension) 9349 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9350 9351 // & gets special logic for several kinds of placeholder. 9352 // The builtin code knows what to do. 9353 if (Opc == UO_AddrOf && 9354 (pty->getKind() == BuiltinType::Overload || 9355 pty->getKind() == BuiltinType::UnknownAny || 9356 pty->getKind() == BuiltinType::BoundMember)) 9357 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9358 9359 // Anything else needs to be handled now. 9360 ExprResult Result = CheckPlaceholderExpr(Input); 9361 if (Result.isInvalid()) return ExprError(); 9362 Input = Result.take(); 9363 } 9364 9365 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9366 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9367 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9368 // Find all of the overloaded operators visible from this 9369 // point. We perform both an operator-name lookup from the local 9370 // scope and an argument-dependent lookup based on the types of 9371 // the arguments. 9372 UnresolvedSet<16> Functions; 9373 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9374 if (S && OverOp != OO_None) 9375 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9376 Functions); 9377 9378 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9379 } 9380 9381 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9382 } 9383 9384 // Unary Operators. 'Tok' is the token for the operator. 9385 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9386 tok::TokenKind Op, Expr *Input) { 9387 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9388 } 9389 9390 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9391 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9392 LabelDecl *TheDecl) { 9393 TheDecl->setUsed(); 9394 // Create the AST node. The address of a label always has type 'void*'. 9395 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9396 Context.getPointerType(Context.VoidTy))); 9397 } 9398 9399 /// Given the last statement in a statement-expression, check whether 9400 /// the result is a producing expression (like a call to an 9401 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9402 /// release out of the full-expression. Otherwise, return null. 9403 /// Cannot fail. 9404 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9405 // Should always be wrapped with one of these. 9406 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9407 if (!cleanups) return 0; 9408 9409 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9410 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9411 return 0; 9412 9413 // Splice out the cast. This shouldn't modify any interesting 9414 // features of the statement. 9415 Expr *producer = cast->getSubExpr(); 9416 assert(producer->getType() == cast->getType()); 9417 assert(producer->getValueKind() == cast->getValueKind()); 9418 cleanups->setSubExpr(producer); 9419 return cleanups; 9420 } 9421 9422 void Sema::ActOnStartStmtExpr() { 9423 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9424 } 9425 9426 void Sema::ActOnStmtExprError() { 9427 // Note that function is also called by TreeTransform when leaving a 9428 // StmtExpr scope without rebuilding anything. 9429 9430 DiscardCleanupsInEvaluationContext(); 9431 PopExpressionEvaluationContext(); 9432 } 9433 9434 ExprResult 9435 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9436 SourceLocation RPLoc) { // "({..})" 9437 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9438 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9439 9440 if (hasAnyUnrecoverableErrorsInThisFunction()) 9441 DiscardCleanupsInEvaluationContext(); 9442 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9443 PopExpressionEvaluationContext(); 9444 9445 bool isFileScope 9446 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9447 if (isFileScope) 9448 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9449 9450 // FIXME: there are a variety of strange constraints to enforce here, for 9451 // example, it is not possible to goto into a stmt expression apparently. 9452 // More semantic analysis is needed. 9453 9454 // If there are sub stmts in the compound stmt, take the type of the last one 9455 // as the type of the stmtexpr. 9456 QualType Ty = Context.VoidTy; 9457 bool StmtExprMayBindToTemp = false; 9458 if (!Compound->body_empty()) { 9459 Stmt *LastStmt = Compound->body_back(); 9460 LabelStmt *LastLabelStmt = 0; 9461 // If LastStmt is a label, skip down through into the body. 9462 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9463 LastLabelStmt = Label; 9464 LastStmt = Label->getSubStmt(); 9465 } 9466 9467 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9468 // Do function/array conversion on the last expression, but not 9469 // lvalue-to-rvalue. However, initialize an unqualified type. 9470 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9471 if (LastExpr.isInvalid()) 9472 return ExprError(); 9473 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9474 9475 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9476 // In ARC, if the final expression ends in a consume, splice 9477 // the consume out and bind it later. In the alternate case 9478 // (when dealing with a retainable type), the result 9479 // initialization will create a produce. In both cases the 9480 // result will be +1, and we'll need to balance that out with 9481 // a bind. 9482 if (Expr *rebuiltLastStmt 9483 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9484 LastExpr = rebuiltLastStmt; 9485 } else { 9486 LastExpr = PerformCopyInitialization( 9487 InitializedEntity::InitializeResult(LPLoc, 9488 Ty, 9489 false), 9490 SourceLocation(), 9491 LastExpr); 9492 } 9493 9494 if (LastExpr.isInvalid()) 9495 return ExprError(); 9496 if (LastExpr.get() != 0) { 9497 if (!LastLabelStmt) 9498 Compound->setLastStmt(LastExpr.take()); 9499 else 9500 LastLabelStmt->setSubStmt(LastExpr.take()); 9501 StmtExprMayBindToTemp = true; 9502 } 9503 } 9504 } 9505 } 9506 9507 // FIXME: Check that expression type is complete/non-abstract; statement 9508 // expressions are not lvalues. 9509 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9510 if (StmtExprMayBindToTemp) 9511 return MaybeBindToTemporary(ResStmtExpr); 9512 return Owned(ResStmtExpr); 9513 } 9514 9515 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9516 TypeSourceInfo *TInfo, 9517 OffsetOfComponent *CompPtr, 9518 unsigned NumComponents, 9519 SourceLocation RParenLoc) { 9520 QualType ArgTy = TInfo->getType(); 9521 bool Dependent = ArgTy->isDependentType(); 9522 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9523 9524 // We must have at least one component that refers to the type, and the first 9525 // one is known to be a field designator. Verify that the ArgTy represents 9526 // a struct/union/class. 9527 if (!Dependent && !ArgTy->isRecordType()) 9528 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9529 << ArgTy << TypeRange); 9530 9531 // Type must be complete per C99 7.17p3 because a declaring a variable 9532 // with an incomplete type would be ill-formed. 9533 if (!Dependent 9534 && RequireCompleteType(BuiltinLoc, ArgTy, 9535 diag::err_offsetof_incomplete_type, TypeRange)) 9536 return ExprError(); 9537 9538 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9539 // GCC extension, diagnose them. 9540 // FIXME: This diagnostic isn't actually visible because the location is in 9541 // a system header! 9542 if (NumComponents != 1) 9543 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9544 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9545 9546 bool DidWarnAboutNonPOD = false; 9547 QualType CurrentType = ArgTy; 9548 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9549 SmallVector<OffsetOfNode, 4> Comps; 9550 SmallVector<Expr*, 4> Exprs; 9551 for (unsigned i = 0; i != NumComponents; ++i) { 9552 const OffsetOfComponent &OC = CompPtr[i]; 9553 if (OC.isBrackets) { 9554 // Offset of an array sub-field. TODO: Should we allow vector elements? 9555 if (!CurrentType->isDependentType()) { 9556 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9557 if(!AT) 9558 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9559 << CurrentType); 9560 CurrentType = AT->getElementType(); 9561 } else 9562 CurrentType = Context.DependentTy; 9563 9564 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9565 if (IdxRval.isInvalid()) 9566 return ExprError(); 9567 Expr *Idx = IdxRval.take(); 9568 9569 // The expression must be an integral expression. 9570 // FIXME: An integral constant expression? 9571 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9572 !Idx->getType()->isIntegerType()) 9573 return ExprError(Diag(Idx->getLocStart(), 9574 diag::err_typecheck_subscript_not_integer) 9575 << Idx->getSourceRange()); 9576 9577 // Record this array index. 9578 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9579 Exprs.push_back(Idx); 9580 continue; 9581 } 9582 9583 // Offset of a field. 9584 if (CurrentType->isDependentType()) { 9585 // We have the offset of a field, but we can't look into the dependent 9586 // type. Just record the identifier of the field. 9587 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 9588 CurrentType = Context.DependentTy; 9589 continue; 9590 } 9591 9592 // We need to have a complete type to look into. 9593 if (RequireCompleteType(OC.LocStart, CurrentType, 9594 diag::err_offsetof_incomplete_type)) 9595 return ExprError(); 9596 9597 // Look for the designated field. 9598 const RecordType *RC = CurrentType->getAs<RecordType>(); 9599 if (!RC) 9600 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 9601 << CurrentType); 9602 RecordDecl *RD = RC->getDecl(); 9603 9604 // C++ [lib.support.types]p5: 9605 // The macro offsetof accepts a restricted set of type arguments in this 9606 // International Standard. type shall be a POD structure or a POD union 9607 // (clause 9). 9608 // C++11 [support.types]p4: 9609 // If type is not a standard-layout class (Clause 9), the results are 9610 // undefined. 9611 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9612 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 9613 unsigned DiagID = 9614 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 9615 : diag::warn_offsetof_non_pod_type; 9616 9617 if (!IsSafe && !DidWarnAboutNonPOD && 9618 DiagRuntimeBehavior(BuiltinLoc, 0, 9619 PDiag(DiagID) 9620 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 9621 << CurrentType)) 9622 DidWarnAboutNonPOD = true; 9623 } 9624 9625 // Look for the field. 9626 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 9627 LookupQualifiedName(R, RD); 9628 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 9629 IndirectFieldDecl *IndirectMemberDecl = 0; 9630 if (!MemberDecl) { 9631 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 9632 MemberDecl = IndirectMemberDecl->getAnonField(); 9633 } 9634 9635 if (!MemberDecl) 9636 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 9637 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 9638 OC.LocEnd)); 9639 9640 // C99 7.17p3: 9641 // (If the specified member is a bit-field, the behavior is undefined.) 9642 // 9643 // We diagnose this as an error. 9644 if (MemberDecl->isBitField()) { 9645 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 9646 << MemberDecl->getDeclName() 9647 << SourceRange(BuiltinLoc, RParenLoc); 9648 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 9649 return ExprError(); 9650 } 9651 9652 RecordDecl *Parent = MemberDecl->getParent(); 9653 if (IndirectMemberDecl) 9654 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 9655 9656 // If the member was found in a base class, introduce OffsetOfNodes for 9657 // the base class indirections. 9658 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9659 /*DetectVirtual=*/false); 9660 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 9661 CXXBasePath &Path = Paths.front(); 9662 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 9663 B != BEnd; ++B) 9664 Comps.push_back(OffsetOfNode(B->Base)); 9665 } 9666 9667 if (IndirectMemberDecl) { 9668 for (IndirectFieldDecl::chain_iterator FI = 9669 IndirectMemberDecl->chain_begin(), 9670 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 9671 assert(isa<FieldDecl>(*FI)); 9672 Comps.push_back(OffsetOfNode(OC.LocStart, 9673 cast<FieldDecl>(*FI), OC.LocEnd)); 9674 } 9675 } else 9676 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 9677 9678 CurrentType = MemberDecl->getType().getNonReferenceType(); 9679 } 9680 9681 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 9682 TInfo, Comps, Exprs, RParenLoc)); 9683 } 9684 9685 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 9686 SourceLocation BuiltinLoc, 9687 SourceLocation TypeLoc, 9688 ParsedType ParsedArgTy, 9689 OffsetOfComponent *CompPtr, 9690 unsigned NumComponents, 9691 SourceLocation RParenLoc) { 9692 9693 TypeSourceInfo *ArgTInfo; 9694 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 9695 if (ArgTy.isNull()) 9696 return ExprError(); 9697 9698 if (!ArgTInfo) 9699 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 9700 9701 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 9702 RParenLoc); 9703 } 9704 9705 9706 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 9707 Expr *CondExpr, 9708 Expr *LHSExpr, Expr *RHSExpr, 9709 SourceLocation RPLoc) { 9710 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 9711 9712 ExprValueKind VK = VK_RValue; 9713 ExprObjectKind OK = OK_Ordinary; 9714 QualType resType; 9715 bool ValueDependent = false; 9716 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 9717 resType = Context.DependentTy; 9718 ValueDependent = true; 9719 } else { 9720 // The conditional expression is required to be a constant expression. 9721 llvm::APSInt condEval(32); 9722 ExprResult CondICE 9723 = VerifyIntegerConstantExpression(CondExpr, &condEval, 9724 diag::err_typecheck_choose_expr_requires_constant, false); 9725 if (CondICE.isInvalid()) 9726 return ExprError(); 9727 CondExpr = CondICE.take(); 9728 9729 // If the condition is > zero, then the AST type is the same as the LSHExpr. 9730 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 9731 9732 resType = ActiveExpr->getType(); 9733 ValueDependent = ActiveExpr->isValueDependent(); 9734 VK = ActiveExpr->getValueKind(); 9735 OK = ActiveExpr->getObjectKind(); 9736 } 9737 9738 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 9739 resType, VK, OK, RPLoc, 9740 resType->isDependentType(), 9741 ValueDependent)); 9742 } 9743 9744 //===----------------------------------------------------------------------===// 9745 // Clang Extensions. 9746 //===----------------------------------------------------------------------===// 9747 9748 /// ActOnBlockStart - This callback is invoked when a block literal is started. 9749 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 9750 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 9751 PushBlockScope(CurScope, Block); 9752 CurContext->addDecl(Block); 9753 if (CurScope) 9754 PushDeclContext(CurScope, Block); 9755 else 9756 CurContext = Block; 9757 9758 getCurBlock()->HasImplicitReturnType = true; 9759 9760 // Enter a new evaluation context to insulate the block from any 9761 // cleanups from the enclosing full-expression. 9762 PushExpressionEvaluationContext(PotentiallyEvaluated); 9763 } 9764 9765 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 9766 Scope *CurScope) { 9767 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 9768 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 9769 BlockScopeInfo *CurBlock = getCurBlock(); 9770 9771 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 9772 QualType T = Sig->getType(); 9773 9774 // FIXME: We should allow unexpanded parameter packs here, but that would, 9775 // in turn, make the block expression contain unexpanded parameter packs. 9776 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 9777 // Drop the parameters. 9778 FunctionProtoType::ExtProtoInfo EPI; 9779 EPI.HasTrailingReturn = false; 9780 EPI.TypeQuals |= DeclSpec::TQ_const; 9781 T = Context.getFunctionType(Context.DependentTy, None, EPI); 9782 Sig = Context.getTrivialTypeSourceInfo(T); 9783 } 9784 9785 // GetTypeForDeclarator always produces a function type for a block 9786 // literal signature. Furthermore, it is always a FunctionProtoType 9787 // unless the function was written with a typedef. 9788 assert(T->isFunctionType() && 9789 "GetTypeForDeclarator made a non-function block signature"); 9790 9791 // Look for an explicit signature in that function type. 9792 FunctionProtoTypeLoc ExplicitSignature; 9793 9794 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 9795 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 9796 9797 // Check whether that explicit signature was synthesized by 9798 // GetTypeForDeclarator. If so, don't save that as part of the 9799 // written signature. 9800 if (ExplicitSignature.getLocalRangeBegin() == 9801 ExplicitSignature.getLocalRangeEnd()) { 9802 // This would be much cheaper if we stored TypeLocs instead of 9803 // TypeSourceInfos. 9804 TypeLoc Result = ExplicitSignature.getResultLoc(); 9805 unsigned Size = Result.getFullDataSize(); 9806 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 9807 Sig->getTypeLoc().initializeFullCopy(Result, Size); 9808 9809 ExplicitSignature = FunctionProtoTypeLoc(); 9810 } 9811 } 9812 9813 CurBlock->TheDecl->setSignatureAsWritten(Sig); 9814 CurBlock->FunctionType = T; 9815 9816 const FunctionType *Fn = T->getAs<FunctionType>(); 9817 QualType RetTy = Fn->getResultType(); 9818 bool isVariadic = 9819 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 9820 9821 CurBlock->TheDecl->setIsVariadic(isVariadic); 9822 9823 // Don't allow returning a objc interface by value. 9824 if (RetTy->isObjCObjectType()) { 9825 Diag(ParamInfo.getLocStart(), 9826 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 9827 return; 9828 } 9829 9830 // Context.DependentTy is used as a placeholder for a missing block 9831 // return type. TODO: what should we do with declarators like: 9832 // ^ * { ... } 9833 // If the answer is "apply template argument deduction".... 9834 if (RetTy != Context.DependentTy) { 9835 CurBlock->ReturnType = RetTy; 9836 CurBlock->TheDecl->setBlockMissingReturnType(false); 9837 CurBlock->HasImplicitReturnType = false; 9838 } 9839 9840 // Push block parameters from the declarator if we had them. 9841 SmallVector<ParmVarDecl*, 8> Params; 9842 if (ExplicitSignature) { 9843 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 9844 ParmVarDecl *Param = ExplicitSignature.getArg(I); 9845 if (Param->getIdentifier() == 0 && 9846 !Param->isImplicit() && 9847 !Param->isInvalidDecl() && 9848 !getLangOpts().CPlusPlus) 9849 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9850 Params.push_back(Param); 9851 } 9852 9853 // Fake up parameter variables if we have a typedef, like 9854 // ^ fntype { ... } 9855 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 9856 for (FunctionProtoType::arg_type_iterator 9857 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 9858 ParmVarDecl *Param = 9859 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 9860 ParamInfo.getLocStart(), 9861 *I); 9862 Params.push_back(Param); 9863 } 9864 } 9865 9866 // Set the parameters on the block decl. 9867 if (!Params.empty()) { 9868 CurBlock->TheDecl->setParams(Params); 9869 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 9870 CurBlock->TheDecl->param_end(), 9871 /*CheckParameterNames=*/false); 9872 } 9873 9874 // Finally we can process decl attributes. 9875 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 9876 9877 // Put the parameter variables in scope. We can bail out immediately 9878 // if we don't have any. 9879 if (Params.empty()) 9880 return; 9881 9882 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 9883 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 9884 (*AI)->setOwningFunction(CurBlock->TheDecl); 9885 9886 // If this has an identifier, add it to the scope stack. 9887 if ((*AI)->getIdentifier()) { 9888 CheckShadow(CurBlock->TheScope, *AI); 9889 9890 PushOnScopeChains(*AI, CurBlock->TheScope); 9891 } 9892 } 9893 } 9894 9895 /// ActOnBlockError - If there is an error parsing a block, this callback 9896 /// is invoked to pop the information about the block from the action impl. 9897 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 9898 // Leave the expression-evaluation context. 9899 DiscardCleanupsInEvaluationContext(); 9900 PopExpressionEvaluationContext(); 9901 9902 // Pop off CurBlock, handle nested blocks. 9903 PopDeclContext(); 9904 PopFunctionScopeInfo(); 9905 } 9906 9907 /// ActOnBlockStmtExpr - This is called when the body of a block statement 9908 /// literal was successfully completed. ^(int x){...} 9909 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 9910 Stmt *Body, Scope *CurScope) { 9911 // If blocks are disabled, emit an error. 9912 if (!LangOpts.Blocks) 9913 Diag(CaretLoc, diag::err_blocks_disable); 9914 9915 // Leave the expression-evaluation context. 9916 if (hasAnyUnrecoverableErrorsInThisFunction()) 9917 DiscardCleanupsInEvaluationContext(); 9918 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 9919 PopExpressionEvaluationContext(); 9920 9921 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 9922 9923 if (BSI->HasImplicitReturnType) 9924 deduceClosureReturnType(*BSI); 9925 9926 PopDeclContext(); 9927 9928 QualType RetTy = Context.VoidTy; 9929 if (!BSI->ReturnType.isNull()) 9930 RetTy = BSI->ReturnType; 9931 9932 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 9933 QualType BlockTy; 9934 9935 // Set the captured variables on the block. 9936 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 9937 SmallVector<BlockDecl::Capture, 4> Captures; 9938 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 9939 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 9940 if (Cap.isThisCapture()) 9941 continue; 9942 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 9943 Cap.isNested(), Cap.getCopyExpr()); 9944 Captures.push_back(NewCap); 9945 } 9946 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 9947 BSI->CXXThisCaptureIndex != 0); 9948 9949 // If the user wrote a function type in some form, try to use that. 9950 if (!BSI->FunctionType.isNull()) { 9951 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 9952 9953 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 9954 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 9955 9956 // Turn protoless block types into nullary block types. 9957 if (isa<FunctionNoProtoType>(FTy)) { 9958 FunctionProtoType::ExtProtoInfo EPI; 9959 EPI.ExtInfo = Ext; 9960 BlockTy = Context.getFunctionType(RetTy, None, EPI); 9961 9962 // Otherwise, if we don't need to change anything about the function type, 9963 // preserve its sugar structure. 9964 } else if (FTy->getResultType() == RetTy && 9965 (!NoReturn || FTy->getNoReturnAttr())) { 9966 BlockTy = BSI->FunctionType; 9967 9968 // Otherwise, make the minimal modifications to the function type. 9969 } else { 9970 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 9971 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9972 EPI.TypeQuals = 0; // FIXME: silently? 9973 EPI.ExtInfo = Ext; 9974 BlockTy = 9975 Context.getFunctionType(RetTy, 9976 ArrayRef<QualType>(FPT->arg_type_begin(), 9977 FPT->getNumArgs()), 9978 EPI); 9979 } 9980 9981 // If we don't have a function type, just build one from nothing. 9982 } else { 9983 FunctionProtoType::ExtProtoInfo EPI; 9984 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 9985 BlockTy = Context.getFunctionType(RetTy, None, EPI); 9986 } 9987 9988 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 9989 BSI->TheDecl->param_end()); 9990 BlockTy = Context.getBlockPointerType(BlockTy); 9991 9992 // If needed, diagnose invalid gotos and switches in the block. 9993 if (getCurFunction()->NeedsScopeChecking() && 9994 !hasAnyUnrecoverableErrorsInThisFunction() && 9995 !PP.isCodeCompletionEnabled()) 9996 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 9997 9998 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 9999 10000 // Try to apply the named return value optimization. We have to check again 10001 // if we can do this, though, because blocks keep return statements around 10002 // to deduce an implicit return type. 10003 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10004 !BSI->TheDecl->isDependentContext()) 10005 computeNRVO(Body, getCurBlock()); 10006 10007 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10008 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 10009 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10010 10011 // If the block isn't obviously global, i.e. it captures anything at 10012 // all, then we need to do a few things in the surrounding context: 10013 if (Result->getBlockDecl()->hasCaptures()) { 10014 // First, this expression has a new cleanup object. 10015 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10016 ExprNeedsCleanups = true; 10017 10018 // It also gets a branch-protected scope if any of the captured 10019 // variables needs destruction. 10020 for (BlockDecl::capture_const_iterator 10021 ci = Result->getBlockDecl()->capture_begin(), 10022 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10023 const VarDecl *var = ci->getVariable(); 10024 if (var->getType().isDestructedType() != QualType::DK_none) { 10025 getCurFunction()->setHasBranchProtectedScope(); 10026 break; 10027 } 10028 } 10029 } 10030 10031 return Owned(Result); 10032 } 10033 10034 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10035 Expr *E, ParsedType Ty, 10036 SourceLocation RPLoc) { 10037 TypeSourceInfo *TInfo; 10038 GetTypeFromParser(Ty, &TInfo); 10039 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10040 } 10041 10042 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10043 Expr *E, TypeSourceInfo *TInfo, 10044 SourceLocation RPLoc) { 10045 Expr *OrigExpr = E; 10046 10047 // Get the va_list type 10048 QualType VaListType = Context.getBuiltinVaListType(); 10049 if (VaListType->isArrayType()) { 10050 // Deal with implicit array decay; for example, on x86-64, 10051 // va_list is an array, but it's supposed to decay to 10052 // a pointer for va_arg. 10053 VaListType = Context.getArrayDecayedType(VaListType); 10054 // Make sure the input expression also decays appropriately. 10055 ExprResult Result = UsualUnaryConversions(E); 10056 if (Result.isInvalid()) 10057 return ExprError(); 10058 E = Result.take(); 10059 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10060 // If va_list is a record type and we are compiling in C++ mode, 10061 // check the argument using reference binding. 10062 InitializedEntity Entity 10063 = InitializedEntity::InitializeParameter(Context, 10064 Context.getLValueReferenceType(VaListType), false); 10065 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10066 if (Init.isInvalid()) 10067 return ExprError(); 10068 E = Init.takeAs<Expr>(); 10069 } else { 10070 // Otherwise, the va_list argument must be an l-value because 10071 // it is modified by va_arg. 10072 if (!E->isTypeDependent() && 10073 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10074 return ExprError(); 10075 } 10076 10077 if (!E->isTypeDependent() && 10078 !Context.hasSameType(VaListType, E->getType())) { 10079 return ExprError(Diag(E->getLocStart(), 10080 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10081 << OrigExpr->getType() << E->getSourceRange()); 10082 } 10083 10084 if (!TInfo->getType()->isDependentType()) { 10085 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10086 diag::err_second_parameter_to_va_arg_incomplete, 10087 TInfo->getTypeLoc())) 10088 return ExprError(); 10089 10090 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10091 TInfo->getType(), 10092 diag::err_second_parameter_to_va_arg_abstract, 10093 TInfo->getTypeLoc())) 10094 return ExprError(); 10095 10096 if (!TInfo->getType().isPODType(Context)) { 10097 Diag(TInfo->getTypeLoc().getBeginLoc(), 10098 TInfo->getType()->isObjCLifetimeType() 10099 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10100 : diag::warn_second_parameter_to_va_arg_not_pod) 10101 << TInfo->getType() 10102 << TInfo->getTypeLoc().getSourceRange(); 10103 } 10104 10105 // Check for va_arg where arguments of the given type will be promoted 10106 // (i.e. this va_arg is guaranteed to have undefined behavior). 10107 QualType PromoteType; 10108 if (TInfo->getType()->isPromotableIntegerType()) { 10109 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10110 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10111 PromoteType = QualType(); 10112 } 10113 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10114 PromoteType = Context.DoubleTy; 10115 if (!PromoteType.isNull()) 10116 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10117 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10118 << TInfo->getType() 10119 << PromoteType 10120 << TInfo->getTypeLoc().getSourceRange()); 10121 } 10122 10123 QualType T = TInfo->getType().getNonLValueExprType(Context); 10124 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10125 } 10126 10127 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10128 // The type of __null will be int or long, depending on the size of 10129 // pointers on the target. 10130 QualType Ty; 10131 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10132 if (pw == Context.getTargetInfo().getIntWidth()) 10133 Ty = Context.IntTy; 10134 else if (pw == Context.getTargetInfo().getLongWidth()) 10135 Ty = Context.LongTy; 10136 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10137 Ty = Context.LongLongTy; 10138 else { 10139 llvm_unreachable("I don't know size of pointer!"); 10140 } 10141 10142 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10143 } 10144 10145 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 10146 Expr *SrcExpr, FixItHint &Hint) { 10147 if (!SemaRef.getLangOpts().ObjC1) 10148 return; 10149 10150 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10151 if (!PT) 10152 return; 10153 10154 // Check if the destination is of type 'id'. 10155 if (!PT->isObjCIdType()) { 10156 // Check if the destination is the 'NSString' interface. 10157 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10158 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10159 return; 10160 } 10161 10162 // Ignore any parens, implicit casts (should only be 10163 // array-to-pointer decays), and not-so-opaque values. The last is 10164 // important for making this trigger for property assignments. 10165 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 10166 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10167 if (OV->getSourceExpr()) 10168 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10169 10170 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10171 if (!SL || !SL->isAscii()) 10172 return; 10173 10174 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10175 } 10176 10177 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10178 SourceLocation Loc, 10179 QualType DstType, QualType SrcType, 10180 Expr *SrcExpr, AssignmentAction Action, 10181 bool *Complained) { 10182 if (Complained) 10183 *Complained = false; 10184 10185 // Decode the result (notice that AST's are still created for extensions). 10186 bool CheckInferredResultType = false; 10187 bool isInvalid = false; 10188 unsigned DiagKind = 0; 10189 FixItHint Hint; 10190 ConversionFixItGenerator ConvHints; 10191 bool MayHaveConvFixit = false; 10192 bool MayHaveFunctionDiff = false; 10193 10194 switch (ConvTy) { 10195 case Compatible: 10196 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10197 return false; 10198 10199 case PointerToInt: 10200 DiagKind = diag::ext_typecheck_convert_pointer_int; 10201 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10202 MayHaveConvFixit = true; 10203 break; 10204 case IntToPointer: 10205 DiagKind = diag::ext_typecheck_convert_int_pointer; 10206 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10207 MayHaveConvFixit = true; 10208 break; 10209 case IncompatiblePointer: 10210 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 10211 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 10212 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10213 SrcType->isObjCObjectPointerType(); 10214 if (Hint.isNull() && !CheckInferredResultType) { 10215 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10216 } 10217 else if (CheckInferredResultType) { 10218 SrcType = SrcType.getUnqualifiedType(); 10219 DstType = DstType.getUnqualifiedType(); 10220 } 10221 MayHaveConvFixit = true; 10222 break; 10223 case IncompatiblePointerSign: 10224 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10225 break; 10226 case FunctionVoidPointer: 10227 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10228 break; 10229 case IncompatiblePointerDiscardsQualifiers: { 10230 // Perform array-to-pointer decay if necessary. 10231 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10232 10233 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10234 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10235 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10236 DiagKind = diag::err_typecheck_incompatible_address_space; 10237 break; 10238 10239 10240 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10241 DiagKind = diag::err_typecheck_incompatible_ownership; 10242 break; 10243 } 10244 10245 llvm_unreachable("unknown error case for discarding qualifiers!"); 10246 // fallthrough 10247 } 10248 case CompatiblePointerDiscardsQualifiers: 10249 // If the qualifiers lost were because we were applying the 10250 // (deprecated) C++ conversion from a string literal to a char* 10251 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10252 // Ideally, this check would be performed in 10253 // checkPointerTypesForAssignment. However, that would require a 10254 // bit of refactoring (so that the second argument is an 10255 // expression, rather than a type), which should be done as part 10256 // of a larger effort to fix checkPointerTypesForAssignment for 10257 // C++ semantics. 10258 if (getLangOpts().CPlusPlus && 10259 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10260 return false; 10261 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10262 break; 10263 case IncompatibleNestedPointerQualifiers: 10264 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10265 break; 10266 case IntToBlockPointer: 10267 DiagKind = diag::err_int_to_block_pointer; 10268 break; 10269 case IncompatibleBlockPointer: 10270 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10271 break; 10272 case IncompatibleObjCQualifiedId: 10273 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10274 // it can give a more specific diagnostic. 10275 DiagKind = diag::warn_incompatible_qualified_id; 10276 break; 10277 case IncompatibleVectors: 10278 DiagKind = diag::warn_incompatible_vectors; 10279 break; 10280 case IncompatibleObjCWeakRef: 10281 DiagKind = diag::err_arc_weak_unavailable_assign; 10282 break; 10283 case Incompatible: 10284 DiagKind = diag::err_typecheck_convert_incompatible; 10285 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10286 MayHaveConvFixit = true; 10287 isInvalid = true; 10288 MayHaveFunctionDiff = true; 10289 break; 10290 } 10291 10292 QualType FirstType, SecondType; 10293 switch (Action) { 10294 case AA_Assigning: 10295 case AA_Initializing: 10296 // The destination type comes first. 10297 FirstType = DstType; 10298 SecondType = SrcType; 10299 break; 10300 10301 case AA_Returning: 10302 case AA_Passing: 10303 case AA_Converting: 10304 case AA_Sending: 10305 case AA_Casting: 10306 // The source type comes first. 10307 FirstType = SrcType; 10308 SecondType = DstType; 10309 break; 10310 } 10311 10312 PartialDiagnostic FDiag = PDiag(DiagKind); 10313 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10314 10315 // If we can fix the conversion, suggest the FixIts. 10316 assert(ConvHints.isNull() || Hint.isNull()); 10317 if (!ConvHints.isNull()) { 10318 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10319 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10320 FDiag << *HI; 10321 } else { 10322 FDiag << Hint; 10323 } 10324 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10325 10326 if (MayHaveFunctionDiff) 10327 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10328 10329 Diag(Loc, FDiag); 10330 10331 if (SecondType == Context.OverloadTy) 10332 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10333 FirstType); 10334 10335 if (CheckInferredResultType) 10336 EmitRelatedResultTypeNote(SrcExpr); 10337 10338 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10339 EmitRelatedResultTypeNoteForReturn(DstType); 10340 10341 if (Complained) 10342 *Complained = true; 10343 return isInvalid; 10344 } 10345 10346 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10347 llvm::APSInt *Result) { 10348 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10349 public: 10350 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10351 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10352 } 10353 } Diagnoser; 10354 10355 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10356 } 10357 10358 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10359 llvm::APSInt *Result, 10360 unsigned DiagID, 10361 bool AllowFold) { 10362 class IDDiagnoser : public VerifyICEDiagnoser { 10363 unsigned DiagID; 10364 10365 public: 10366 IDDiagnoser(unsigned DiagID) 10367 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10368 10369 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10370 S.Diag(Loc, DiagID) << SR; 10371 } 10372 } Diagnoser(DiagID); 10373 10374 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10375 } 10376 10377 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10378 SourceRange SR) { 10379 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10380 } 10381 10382 ExprResult 10383 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10384 VerifyICEDiagnoser &Diagnoser, 10385 bool AllowFold) { 10386 SourceLocation DiagLoc = E->getLocStart(); 10387 10388 if (getLangOpts().CPlusPlus11) { 10389 // C++11 [expr.const]p5: 10390 // If an expression of literal class type is used in a context where an 10391 // integral constant expression is required, then that class type shall 10392 // have a single non-explicit conversion function to an integral or 10393 // unscoped enumeration type 10394 ExprResult Converted; 10395 if (!Diagnoser.Suppress) { 10396 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10397 public: 10398 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { } 10399 10400 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10401 QualType T) { 10402 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10403 } 10404 10405 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10406 SourceLocation Loc, 10407 QualType T) { 10408 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10409 } 10410 10411 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10412 SourceLocation Loc, 10413 QualType T, 10414 QualType ConvTy) { 10415 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10416 } 10417 10418 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10419 CXXConversionDecl *Conv, 10420 QualType ConvTy) { 10421 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10422 << ConvTy->isEnumeralType() << ConvTy; 10423 } 10424 10425 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10426 QualType T) { 10427 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10428 } 10429 10430 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10431 CXXConversionDecl *Conv, 10432 QualType ConvTy) { 10433 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10434 << ConvTy->isEnumeralType() << ConvTy; 10435 } 10436 10437 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10438 SourceLocation Loc, 10439 QualType T, 10440 QualType ConvTy) { 10441 return DiagnosticBuilder::getEmpty(); 10442 } 10443 } ConvertDiagnoser; 10444 10445 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10446 ConvertDiagnoser, 10447 /*AllowScopedEnumerations*/ false); 10448 } else { 10449 // The caller wants to silently enquire whether this is an ICE. Don't 10450 // produce any diagnostics if it isn't. 10451 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser { 10452 public: 10453 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { } 10454 10455 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10456 QualType T) { 10457 return DiagnosticBuilder::getEmpty(); 10458 } 10459 10460 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10461 SourceLocation Loc, 10462 QualType T) { 10463 return DiagnosticBuilder::getEmpty(); 10464 } 10465 10466 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10467 SourceLocation Loc, 10468 QualType T, 10469 QualType ConvTy) { 10470 return DiagnosticBuilder::getEmpty(); 10471 } 10472 10473 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10474 CXXConversionDecl *Conv, 10475 QualType ConvTy) { 10476 return DiagnosticBuilder::getEmpty(); 10477 } 10478 10479 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10480 QualType T) { 10481 return DiagnosticBuilder::getEmpty(); 10482 } 10483 10484 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10485 CXXConversionDecl *Conv, 10486 QualType ConvTy) { 10487 return DiagnosticBuilder::getEmpty(); 10488 } 10489 10490 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10491 SourceLocation Loc, 10492 QualType T, 10493 QualType ConvTy) { 10494 return DiagnosticBuilder::getEmpty(); 10495 } 10496 } ConvertDiagnoser; 10497 10498 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10499 ConvertDiagnoser, false); 10500 } 10501 if (Converted.isInvalid()) 10502 return Converted; 10503 E = Converted.take(); 10504 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10505 return ExprError(); 10506 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10507 // An ICE must be of integral or unscoped enumeration type. 10508 if (!Diagnoser.Suppress) 10509 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10510 return ExprError(); 10511 } 10512 10513 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10514 // in the non-ICE case. 10515 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10516 if (Result) 10517 *Result = E->EvaluateKnownConstInt(Context); 10518 return Owned(E); 10519 } 10520 10521 Expr::EvalResult EvalResult; 10522 SmallVector<PartialDiagnosticAt, 8> Notes; 10523 EvalResult.Diag = &Notes; 10524 10525 // Try to evaluate the expression, and produce diagnostics explaining why it's 10526 // not a constant expression as a side-effect. 10527 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10528 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10529 10530 // In C++11, we can rely on diagnostics being produced for any expression 10531 // which is not a constant expression. If no diagnostics were produced, then 10532 // this is a constant expression. 10533 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10534 if (Result) 10535 *Result = EvalResult.Val.getInt(); 10536 return Owned(E); 10537 } 10538 10539 // If our only note is the usual "invalid subexpression" note, just point 10540 // the caret at its location rather than producing an essentially 10541 // redundant note. 10542 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10543 diag::note_invalid_subexpr_in_const_expr) { 10544 DiagLoc = Notes[0].first; 10545 Notes.clear(); 10546 } 10547 10548 if (!Folded || !AllowFold) { 10549 if (!Diagnoser.Suppress) { 10550 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10551 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10552 Diag(Notes[I].first, Notes[I].second); 10553 } 10554 10555 return ExprError(); 10556 } 10557 10558 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10559 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10560 Diag(Notes[I].first, Notes[I].second); 10561 10562 if (Result) 10563 *Result = EvalResult.Val.getInt(); 10564 return Owned(E); 10565 } 10566 10567 namespace { 10568 // Handle the case where we conclude a expression which we speculatively 10569 // considered to be unevaluated is actually evaluated. 10570 class TransformToPE : public TreeTransform<TransformToPE> { 10571 typedef TreeTransform<TransformToPE> BaseTransform; 10572 10573 public: 10574 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10575 10576 // Make sure we redo semantic analysis 10577 bool AlwaysRebuild() { return true; } 10578 10579 // Make sure we handle LabelStmts correctly. 10580 // FIXME: This does the right thing, but maybe we need a more general 10581 // fix to TreeTransform? 10582 StmtResult TransformLabelStmt(LabelStmt *S) { 10583 S->getDecl()->setStmt(0); 10584 return BaseTransform::TransformLabelStmt(S); 10585 } 10586 10587 // We need to special-case DeclRefExprs referring to FieldDecls which 10588 // are not part of a member pointer formation; normal TreeTransforming 10589 // doesn't catch this case because of the way we represent them in the AST. 10590 // FIXME: This is a bit ugly; is it really the best way to handle this 10591 // case? 10592 // 10593 // Error on DeclRefExprs referring to FieldDecls. 10594 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10595 if (isa<FieldDecl>(E->getDecl()) && 10596 !SemaRef.isUnevaluatedContext()) 10597 return SemaRef.Diag(E->getLocation(), 10598 diag::err_invalid_non_static_member_use) 10599 << E->getDecl() << E->getSourceRange(); 10600 10601 return BaseTransform::TransformDeclRefExpr(E); 10602 } 10603 10604 // Exception: filter out member pointer formation 10605 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10606 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10607 return E; 10608 10609 return BaseTransform::TransformUnaryOperator(E); 10610 } 10611 10612 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10613 // Lambdas never need to be transformed. 10614 return E; 10615 } 10616 }; 10617 } 10618 10619 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10620 assert(isUnevaluatedContext() && 10621 "Should only transform unevaluated expressions"); 10622 ExprEvalContexts.back().Context = 10623 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10624 if (isUnevaluatedContext()) 10625 return E; 10626 return TransformToPE(*this).TransformExpr(E); 10627 } 10628 10629 void 10630 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10631 Decl *LambdaContextDecl, 10632 bool IsDecltype) { 10633 ExprEvalContexts.push_back( 10634 ExpressionEvaluationContextRecord(NewContext, 10635 ExprCleanupObjects.size(), 10636 ExprNeedsCleanups, 10637 LambdaContextDecl, 10638 IsDecltype)); 10639 ExprNeedsCleanups = false; 10640 if (!MaybeODRUseExprs.empty()) 10641 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 10642 } 10643 10644 void 10645 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10646 ReuseLambdaContextDecl_t, 10647 bool IsDecltype) { 10648 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl; 10649 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype); 10650 } 10651 10652 void Sema::PopExpressionEvaluationContext() { 10653 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 10654 10655 if (!Rec.Lambdas.empty()) { 10656 if (Rec.isUnevaluated()) { 10657 // C++11 [expr.prim.lambda]p2: 10658 // A lambda-expression shall not appear in an unevaluated operand 10659 // (Clause 5). 10660 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 10661 Diag(Rec.Lambdas[I]->getLocStart(), 10662 diag::err_lambda_unevaluated_operand); 10663 } else { 10664 // Mark the capture expressions odr-used. This was deferred 10665 // during lambda expression creation. 10666 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 10667 LambdaExpr *Lambda = Rec.Lambdas[I]; 10668 for (LambdaExpr::capture_init_iterator 10669 C = Lambda->capture_init_begin(), 10670 CEnd = Lambda->capture_init_end(); 10671 C != CEnd; ++C) { 10672 MarkDeclarationsReferencedInExpr(*C); 10673 } 10674 } 10675 } 10676 } 10677 10678 // When are coming out of an unevaluated context, clear out any 10679 // temporaries that we may have created as part of the evaluation of 10680 // the expression in that context: they aren't relevant because they 10681 // will never be constructed. 10682 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 10683 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 10684 ExprCleanupObjects.end()); 10685 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 10686 CleanupVarDeclMarking(); 10687 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 10688 // Otherwise, merge the contexts together. 10689 } else { 10690 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 10691 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 10692 Rec.SavedMaybeODRUseExprs.end()); 10693 } 10694 10695 // Pop the current expression evaluation context off the stack. 10696 ExprEvalContexts.pop_back(); 10697 } 10698 10699 void Sema::DiscardCleanupsInEvaluationContext() { 10700 ExprCleanupObjects.erase( 10701 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 10702 ExprCleanupObjects.end()); 10703 ExprNeedsCleanups = false; 10704 MaybeODRUseExprs.clear(); 10705 } 10706 10707 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 10708 if (!E->getType()->isVariablyModifiedType()) 10709 return E; 10710 return TransformToPotentiallyEvaluated(E); 10711 } 10712 10713 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 10714 // Do not mark anything as "used" within a dependent context; wait for 10715 // an instantiation. 10716 if (SemaRef.CurContext->isDependentContext()) 10717 return false; 10718 10719 switch (SemaRef.ExprEvalContexts.back().Context) { 10720 case Sema::Unevaluated: 10721 case Sema::UnevaluatedAbstract: 10722 // We are in an expression that is not potentially evaluated; do nothing. 10723 // (Depending on how you read the standard, we actually do need to do 10724 // something here for null pointer constants, but the standard's 10725 // definition of a null pointer constant is completely crazy.) 10726 return false; 10727 10728 case Sema::ConstantEvaluated: 10729 case Sema::PotentiallyEvaluated: 10730 // We are in a potentially evaluated expression (or a constant-expression 10731 // in C++03); we need to do implicit template instantiation, implicitly 10732 // define class members, and mark most declarations as used. 10733 return true; 10734 10735 case Sema::PotentiallyEvaluatedIfUsed: 10736 // Referenced declarations will only be used if the construct in the 10737 // containing expression is used. 10738 return false; 10739 } 10740 llvm_unreachable("Invalid context"); 10741 } 10742 10743 /// \brief Mark a function referenced, and check whether it is odr-used 10744 /// (C++ [basic.def.odr]p2, C99 6.9p3) 10745 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 10746 assert(Func && "No function?"); 10747 10748 Func->setReferenced(); 10749 10750 // C++11 [basic.def.odr]p3: 10751 // A function whose name appears as a potentially-evaluated expression is 10752 // odr-used if it is the unique lookup result or the selected member of a 10753 // set of overloaded functions [...]. 10754 // 10755 // We (incorrectly) mark overload resolution as an unevaluated context, so we 10756 // can just check that here. Skip the rest of this function if we've already 10757 // marked the function as used. 10758 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 10759 // C++11 [temp.inst]p3: 10760 // Unless a function template specialization has been explicitly 10761 // instantiated or explicitly specialized, the function template 10762 // specialization is implicitly instantiated when the specialization is 10763 // referenced in a context that requires a function definition to exist. 10764 // 10765 // We consider constexpr function templates to be referenced in a context 10766 // that requires a definition to exist whenever they are referenced. 10767 // 10768 // FIXME: This instantiates constexpr functions too frequently. If this is 10769 // really an unevaluated context (and we're not just in the definition of a 10770 // function template or overload resolution or other cases which we 10771 // incorrectly consider to be unevaluated contexts), and we're not in a 10772 // subexpression which we actually need to evaluate (for instance, a 10773 // template argument, array bound or an expression in a braced-init-list), 10774 // we are not permitted to instantiate this constexpr function definition. 10775 // 10776 // FIXME: This also implicitly defines special members too frequently. They 10777 // are only supposed to be implicitly defined if they are odr-used, but they 10778 // are not odr-used from constant expressions in unevaluated contexts. 10779 // However, they cannot be referenced if they are deleted, and they are 10780 // deleted whenever the implicit definition of the special member would 10781 // fail. 10782 if (!Func->isConstexpr() || Func->getBody()) 10783 return; 10784 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 10785 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 10786 return; 10787 } 10788 10789 // Note that this declaration has been used. 10790 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 10791 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 10792 if (Constructor->isDefaultConstructor()) { 10793 if (Constructor->isTrivial()) 10794 return; 10795 if (!Constructor->isUsed(false)) 10796 DefineImplicitDefaultConstructor(Loc, Constructor); 10797 } else if (Constructor->isCopyConstructor()) { 10798 if (!Constructor->isUsed(false)) 10799 DefineImplicitCopyConstructor(Loc, Constructor); 10800 } else if (Constructor->isMoveConstructor()) { 10801 if (!Constructor->isUsed(false)) 10802 DefineImplicitMoveConstructor(Loc, Constructor); 10803 } 10804 } else if (Constructor->getInheritedConstructor()) { 10805 if (!Constructor->isUsed(false)) 10806 DefineInheritingConstructor(Loc, Constructor); 10807 } 10808 10809 MarkVTableUsed(Loc, Constructor->getParent()); 10810 } else if (CXXDestructorDecl *Destructor = 10811 dyn_cast<CXXDestructorDecl>(Func)) { 10812 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 10813 !Destructor->isUsed(false)) 10814 DefineImplicitDestructor(Loc, Destructor); 10815 if (Destructor->isVirtual()) 10816 MarkVTableUsed(Loc, Destructor->getParent()); 10817 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 10818 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 10819 MethodDecl->isOverloadedOperator() && 10820 MethodDecl->getOverloadedOperator() == OO_Equal) { 10821 if (!MethodDecl->isUsed(false)) { 10822 if (MethodDecl->isCopyAssignmentOperator()) 10823 DefineImplicitCopyAssignment(Loc, MethodDecl); 10824 else 10825 DefineImplicitMoveAssignment(Loc, MethodDecl); 10826 } 10827 } else if (isa<CXXConversionDecl>(MethodDecl) && 10828 MethodDecl->getParent()->isLambda()) { 10829 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 10830 if (Conversion->isLambdaToBlockPointerConversion()) 10831 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 10832 else 10833 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 10834 } else if (MethodDecl->isVirtual()) 10835 MarkVTableUsed(Loc, MethodDecl->getParent()); 10836 } 10837 10838 // Recursive functions should be marked when used from another function. 10839 // FIXME: Is this really right? 10840 if (CurContext == Func) return; 10841 10842 // Resolve the exception specification for any function which is 10843 // used: CodeGen will need it. 10844 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 10845 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 10846 ResolveExceptionSpec(Loc, FPT); 10847 10848 // Implicit instantiation of function templates and member functions of 10849 // class templates. 10850 if (Func->isImplicitlyInstantiable()) { 10851 bool AlreadyInstantiated = false; 10852 SourceLocation PointOfInstantiation = Loc; 10853 if (FunctionTemplateSpecializationInfo *SpecInfo 10854 = Func->getTemplateSpecializationInfo()) { 10855 if (SpecInfo->getPointOfInstantiation().isInvalid()) 10856 SpecInfo->setPointOfInstantiation(Loc); 10857 else if (SpecInfo->getTemplateSpecializationKind() 10858 == TSK_ImplicitInstantiation) { 10859 AlreadyInstantiated = true; 10860 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 10861 } 10862 } else if (MemberSpecializationInfo *MSInfo 10863 = Func->getMemberSpecializationInfo()) { 10864 if (MSInfo->getPointOfInstantiation().isInvalid()) 10865 MSInfo->setPointOfInstantiation(Loc); 10866 else if (MSInfo->getTemplateSpecializationKind() 10867 == TSK_ImplicitInstantiation) { 10868 AlreadyInstantiated = true; 10869 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10870 } 10871 } 10872 10873 if (!AlreadyInstantiated || Func->isConstexpr()) { 10874 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 10875 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass()) 10876 PendingLocalImplicitInstantiations.push_back( 10877 std::make_pair(Func, PointOfInstantiation)); 10878 else if (Func->isConstexpr()) 10879 // Do not defer instantiations of constexpr functions, to avoid the 10880 // expression evaluator needing to call back into Sema if it sees a 10881 // call to such a function. 10882 InstantiateFunctionDefinition(PointOfInstantiation, Func); 10883 else { 10884 PendingInstantiations.push_back(std::make_pair(Func, 10885 PointOfInstantiation)); 10886 // Notify the consumer that a function was implicitly instantiated. 10887 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 10888 } 10889 } 10890 } else { 10891 // Walk redefinitions, as some of them may be instantiable. 10892 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 10893 e(Func->redecls_end()); i != e; ++i) { 10894 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 10895 MarkFunctionReferenced(Loc, *i); 10896 } 10897 } 10898 10899 // Keep track of used but undefined functions. 10900 if (!Func->isDefined()) { 10901 if (mightHaveNonExternalLinkage(Func)) 10902 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 10903 else if (Func->getMostRecentDecl()->isInlined() && 10904 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10905 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 10906 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 10907 } 10908 10909 // Normally the must current decl is marked used while processing the use and 10910 // any subsequent decls are marked used by decl merging. This fails with 10911 // template instantiation since marking can happen at the end of the file 10912 // and, because of the two phase lookup, this function is called with at 10913 // decl in the middle of a decl chain. We loop to maintain the invariant 10914 // that once a decl is used, all decls after it are also used. 10915 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 10916 F->setUsed(true); 10917 if (F == Func) 10918 break; 10919 } 10920 } 10921 10922 static void 10923 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 10924 VarDecl *var, DeclContext *DC) { 10925 DeclContext *VarDC = var->getDeclContext(); 10926 10927 // If the parameter still belongs to the translation unit, then 10928 // we're actually just using one parameter in the declaration of 10929 // the next. 10930 if (isa<ParmVarDecl>(var) && 10931 isa<TranslationUnitDecl>(VarDC)) 10932 return; 10933 10934 // For C code, don't diagnose about capture if we're not actually in code 10935 // right now; it's impossible to write a non-constant expression outside of 10936 // function context, so we'll get other (more useful) diagnostics later. 10937 // 10938 // For C++, things get a bit more nasty... it would be nice to suppress this 10939 // diagnostic for certain cases like using a local variable in an array bound 10940 // for a member of a local class, but the correct predicate is not obvious. 10941 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 10942 return; 10943 10944 if (isa<CXXMethodDecl>(VarDC) && 10945 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 10946 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 10947 << var->getIdentifier(); 10948 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 10949 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 10950 << var->getIdentifier() << fn->getDeclName(); 10951 } else if (isa<BlockDecl>(VarDC)) { 10952 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 10953 << var->getIdentifier(); 10954 } else { 10955 // FIXME: Is there any other context where a local variable can be 10956 // declared? 10957 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 10958 << var->getIdentifier(); 10959 } 10960 10961 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 10962 << var->getIdentifier(); 10963 10964 // FIXME: Add additional diagnostic info about class etc. which prevents 10965 // capture. 10966 } 10967 10968 /// \brief Capture the given variable in the captured region. 10969 static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI, 10970 VarDecl *Var, QualType FieldType, 10971 QualType DeclRefType, 10972 SourceLocation Loc, 10973 bool RefersToEnclosingLocal) { 10974 // The current implemention assumes that all variables are captured 10975 // by references. Since there is no capture by copy, no expression evaluation 10976 // will be needed. 10977 // 10978 RecordDecl *RD = RSI->TheRecordDecl; 10979 10980 FieldDecl *Field 10981 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType, 10982 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 10983 0, false, ICIS_NoInit); 10984 Field->setImplicit(true); 10985 Field->setAccess(AS_private); 10986 RD->addDecl(Field); 10987 10988 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 10989 DeclRefType, VK_LValue, Loc); 10990 Var->setReferenced(true); 10991 Var->setUsed(true); 10992 10993 return Ref; 10994 } 10995 10996 /// \brief Capture the given variable in the given lambda expression. 10997 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 10998 VarDecl *Var, QualType FieldType, 10999 QualType DeclRefType, 11000 SourceLocation Loc, 11001 bool RefersToEnclosingLocal) { 11002 CXXRecordDecl *Lambda = LSI->Lambda; 11003 11004 // Build the non-static data member. 11005 FieldDecl *Field 11006 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11007 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11008 0, false, ICIS_NoInit); 11009 Field->setImplicit(true); 11010 Field->setAccess(AS_private); 11011 Lambda->addDecl(Field); 11012 11013 // C++11 [expr.prim.lambda]p21: 11014 // When the lambda-expression is evaluated, the entities that 11015 // are captured by copy are used to direct-initialize each 11016 // corresponding non-static data member of the resulting closure 11017 // object. (For array members, the array elements are 11018 // direct-initialized in increasing subscript order.) These 11019 // initializations are performed in the (unspecified) order in 11020 // which the non-static data members are declared. 11021 11022 // Introduce a new evaluation context for the initialization, so 11023 // that temporaries introduced as part of the capture are retained 11024 // to be re-"exported" from the lambda expression itself. 11025 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11026 11027 // C++ [expr.prim.labda]p12: 11028 // An entity captured by a lambda-expression is odr-used (3.2) in 11029 // the scope containing the lambda-expression. 11030 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11031 DeclRefType, VK_LValue, Loc); 11032 Var->setReferenced(true); 11033 Var->setUsed(true); 11034 11035 // When the field has array type, create index variables for each 11036 // dimension of the array. We use these index variables to subscript 11037 // the source array, and other clients (e.g., CodeGen) will perform 11038 // the necessary iteration with these index variables. 11039 SmallVector<VarDecl *, 4> IndexVariables; 11040 QualType BaseType = FieldType; 11041 QualType SizeType = S.Context.getSizeType(); 11042 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11043 while (const ConstantArrayType *Array 11044 = S.Context.getAsConstantArrayType(BaseType)) { 11045 // Create the iteration variable for this array index. 11046 IdentifierInfo *IterationVarName = 0; 11047 { 11048 SmallString<8> Str; 11049 llvm::raw_svector_ostream OS(Str); 11050 OS << "__i" << IndexVariables.size(); 11051 IterationVarName = &S.Context.Idents.get(OS.str()); 11052 } 11053 VarDecl *IterationVar 11054 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11055 IterationVarName, SizeType, 11056 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11057 SC_None); 11058 IndexVariables.push_back(IterationVar); 11059 LSI->ArrayIndexVars.push_back(IterationVar); 11060 11061 // Create a reference to the iteration variable. 11062 ExprResult IterationVarRef 11063 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11064 assert(!IterationVarRef.isInvalid() && 11065 "Reference to invented variable cannot fail!"); 11066 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11067 assert(!IterationVarRef.isInvalid() && 11068 "Conversion of invented variable cannot fail!"); 11069 11070 // Subscript the array with this iteration variable. 11071 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11072 Ref, Loc, IterationVarRef.take(), Loc); 11073 if (Subscript.isInvalid()) { 11074 S.CleanupVarDeclMarking(); 11075 S.DiscardCleanupsInEvaluationContext(); 11076 return ExprError(); 11077 } 11078 11079 Ref = Subscript.take(); 11080 BaseType = Array->getElementType(); 11081 } 11082 11083 // Construct the entity that we will be initializing. For an array, this 11084 // will be first element in the array, which may require several levels 11085 // of array-subscript entities. 11086 SmallVector<InitializedEntity, 4> Entities; 11087 Entities.reserve(1 + IndexVariables.size()); 11088 Entities.push_back( 11089 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 11090 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11091 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11092 0, 11093 Entities.back())); 11094 11095 InitializationKind InitKind 11096 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11097 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11098 ExprResult Result(true); 11099 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11100 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11101 11102 // If this initialization requires any cleanups (e.g., due to a 11103 // default argument to a copy constructor), note that for the 11104 // lambda. 11105 if (S.ExprNeedsCleanups) 11106 LSI->ExprNeedsCleanups = true; 11107 11108 // Exit the expression evaluation context used for the capture. 11109 S.CleanupVarDeclMarking(); 11110 S.DiscardCleanupsInEvaluationContext(); 11111 return Result; 11112 } 11113 11114 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11115 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11116 bool BuildAndDiagnose, 11117 QualType &CaptureType, 11118 QualType &DeclRefType) { 11119 bool Nested = false; 11120 11121 DeclContext *DC = CurContext; 11122 if (Var->getDeclContext() == DC) return true; 11123 if (!Var->hasLocalStorage()) return true; 11124 11125 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11126 11127 // Walk up the stack to determine whether we can capture the variable, 11128 // performing the "simple" checks that don't depend on type. We stop when 11129 // we've either hit the declared scope of the variable or find an existing 11130 // capture of that variable. 11131 CaptureType = Var->getType(); 11132 DeclRefType = CaptureType.getNonReferenceType(); 11133 bool Explicit = (Kind != TryCapture_Implicit); 11134 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 11135 do { 11136 // Only block literals, captured statements, and lambda expressions can 11137 // capture; other scopes don't work. 11138 DeclContext *ParentDC; 11139 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) 11140 ParentDC = DC->getParent(); 11141 else if (isa<CXXMethodDecl>(DC) && 11142 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 11143 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 11144 ParentDC = DC->getParent()->getParent(); 11145 else { 11146 if (BuildAndDiagnose) 11147 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 11148 return true; 11149 } 11150 11151 CapturingScopeInfo *CSI = 11152 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 11153 11154 // Check whether we've already captured it. 11155 if (CSI->CaptureMap.count(Var)) { 11156 // If we found a capture, any subcaptures are nested. 11157 Nested = true; 11158 11159 // Retrieve the capture type for this variable. 11160 CaptureType = CSI->getCapture(Var).getCaptureType(); 11161 11162 // Compute the type of an expression that refers to this variable. 11163 DeclRefType = CaptureType.getNonReferenceType(); 11164 11165 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11166 if (Cap.isCopyCapture() && 11167 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11168 DeclRefType.addConst(); 11169 break; 11170 } 11171 11172 bool IsBlock = isa<BlockScopeInfo>(CSI); 11173 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11174 11175 // Lambdas are not allowed to capture unnamed variables 11176 // (e.g. anonymous unions). 11177 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11178 // assuming that's the intent. 11179 if (IsLambda && !Var->getDeclName()) { 11180 if (BuildAndDiagnose) { 11181 Diag(Loc, diag::err_lambda_capture_anonymous_var); 11182 Diag(Var->getLocation(), diag::note_declared_at); 11183 } 11184 return true; 11185 } 11186 11187 // Prohibit variably-modified types; they're difficult to deal with. 11188 if (Var->getType()->isVariablyModifiedType()) { 11189 if (BuildAndDiagnose) { 11190 if (IsBlock) 11191 Diag(Loc, diag::err_ref_vm_type); 11192 else 11193 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11194 Diag(Var->getLocation(), diag::note_previous_decl) 11195 << Var->getDeclName(); 11196 } 11197 return true; 11198 } 11199 // Prohibit structs with flexible array members too. 11200 // We cannot capture what is in the tail end of the struct. 11201 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11202 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11203 if (BuildAndDiagnose) { 11204 if (IsBlock) 11205 Diag(Loc, diag::err_ref_flexarray_type); 11206 else 11207 Diag(Loc, diag::err_lambda_capture_flexarray_type) 11208 << Var->getDeclName(); 11209 Diag(Var->getLocation(), diag::note_previous_decl) 11210 << Var->getDeclName(); 11211 } 11212 return true; 11213 } 11214 } 11215 // Lambdas are not allowed to capture __block variables; they don't 11216 // support the expected semantics. 11217 if (IsLambda && HasBlocksAttr) { 11218 if (BuildAndDiagnose) { 11219 Diag(Loc, diag::err_lambda_capture_block) 11220 << Var->getDeclName(); 11221 Diag(Var->getLocation(), diag::note_previous_decl) 11222 << Var->getDeclName(); 11223 } 11224 return true; 11225 } 11226 11227 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 11228 // No capture-default 11229 if (BuildAndDiagnose) { 11230 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 11231 Diag(Var->getLocation(), diag::note_previous_decl) 11232 << Var->getDeclName(); 11233 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 11234 diag::note_lambda_decl); 11235 } 11236 return true; 11237 } 11238 11239 FunctionScopesIndex--; 11240 DC = ParentDC; 11241 Explicit = false; 11242 } while (!Var->getDeclContext()->Equals(DC)); 11243 11244 // Walk back down the scope stack, computing the type of the capture at 11245 // each step, checking type-specific requirements, and adding captures if 11246 // requested. 11247 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 11248 ++I) { 11249 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 11250 11251 // Compute the type of the capture and of a reference to the capture within 11252 // this scope. 11253 if (isa<BlockScopeInfo>(CSI)) { 11254 Expr *CopyExpr = 0; 11255 bool ByRef = false; 11256 11257 // Blocks are not allowed to capture arrays. 11258 if (CaptureType->isArrayType()) { 11259 if (BuildAndDiagnose) { 11260 Diag(Loc, diag::err_ref_array_type); 11261 Diag(Var->getLocation(), diag::note_previous_decl) 11262 << Var->getDeclName(); 11263 } 11264 return true; 11265 } 11266 11267 // Forbid the block-capture of autoreleasing variables. 11268 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11269 if (BuildAndDiagnose) { 11270 Diag(Loc, diag::err_arc_autoreleasing_capture) 11271 << /*block*/ 0; 11272 Diag(Var->getLocation(), diag::note_previous_decl) 11273 << Var->getDeclName(); 11274 } 11275 return true; 11276 } 11277 11278 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11279 // Block capture by reference does not change the capture or 11280 // declaration reference types. 11281 ByRef = true; 11282 } else { 11283 // Block capture by copy introduces 'const'. 11284 CaptureType = CaptureType.getNonReferenceType().withConst(); 11285 DeclRefType = CaptureType; 11286 11287 if (getLangOpts().CPlusPlus && BuildAndDiagnose) { 11288 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11289 // The capture logic needs the destructor, so make sure we mark it. 11290 // Usually this is unnecessary because most local variables have 11291 // their destructors marked at declaration time, but parameters are 11292 // an exception because it's technically only the call site that 11293 // actually requires the destructor. 11294 if (isa<ParmVarDecl>(Var)) 11295 FinalizeVarWithDestructor(Var, Record); 11296 11297 // Enter a new evaluation context to insulate the copy 11298 // full-expression. 11299 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11300 11301 // According to the blocks spec, the capture of a variable from 11302 // the stack requires a const copy constructor. This is not true 11303 // of the copy/move done to move a __block variable to the heap. 11304 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested, 11305 DeclRefType.withConst(), 11306 VK_LValue, Loc); 11307 11308 ExprResult Result 11309 = PerformCopyInitialization( 11310 InitializedEntity::InitializeBlock(Var->getLocation(), 11311 CaptureType, false), 11312 Loc, Owned(DeclRef)); 11313 11314 // Build a full-expression copy expression if initialization 11315 // succeeded and used a non-trivial constructor. Recover from 11316 // errors by pretending that the copy isn't necessary. 11317 if (!Result.isInvalid() && 11318 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11319 ->isTrivial()) { 11320 Result = MaybeCreateExprWithCleanups(Result); 11321 CopyExpr = Result.take(); 11322 } 11323 } 11324 } 11325 } 11326 11327 // Actually capture the variable. 11328 if (BuildAndDiagnose) 11329 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11330 SourceLocation(), CaptureType, CopyExpr); 11331 Nested = true; 11332 continue; 11333 } 11334 11335 if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 11336 // By default, capture variables by reference. 11337 bool ByRef = true; 11338 // Using an LValue reference type is consistent with Lambdas (see below). 11339 CaptureType = Context.getLValueReferenceType(DeclRefType); 11340 11341 Expr *CopyExpr = 0; 11342 if (BuildAndDiagnose) { 11343 ExprResult Result = captureInCapturedRegion(*this, RSI, Var, 11344 CaptureType, DeclRefType, 11345 Loc, Nested); 11346 if (!Result.isInvalid()) 11347 CopyExpr = Result.take(); 11348 } 11349 11350 // Actually capture the variable. 11351 if (BuildAndDiagnose) 11352 CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc, 11353 SourceLocation(), CaptureType, CopyExpr); 11354 Nested = true; 11355 continue; 11356 } 11357 11358 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11359 11360 // Determine whether we are capturing by reference or by value. 11361 bool ByRef = false; 11362 if (I == N - 1 && Kind != TryCapture_Implicit) { 11363 ByRef = (Kind == TryCapture_ExplicitByRef); 11364 } else { 11365 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11366 } 11367 11368 // Compute the type of the field that will capture this variable. 11369 if (ByRef) { 11370 // C++11 [expr.prim.lambda]p15: 11371 // An entity is captured by reference if it is implicitly or 11372 // explicitly captured but not captured by copy. It is 11373 // unspecified whether additional unnamed non-static data 11374 // members are declared in the closure type for entities 11375 // captured by reference. 11376 // 11377 // FIXME: It is not clear whether we want to build an lvalue reference 11378 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11379 // to do the former, while EDG does the latter. Core issue 1249 will 11380 // clarify, but for now we follow GCC because it's a more permissive and 11381 // easily defensible position. 11382 CaptureType = Context.getLValueReferenceType(DeclRefType); 11383 } else { 11384 // C++11 [expr.prim.lambda]p14: 11385 // For each entity captured by copy, an unnamed non-static 11386 // data member is declared in the closure type. The 11387 // declaration order of these members is unspecified. The type 11388 // of such a data member is the type of the corresponding 11389 // captured entity if the entity is not a reference to an 11390 // object, or the referenced type otherwise. [Note: If the 11391 // captured entity is a reference to a function, the 11392 // corresponding data member is also a reference to a 11393 // function. - end note ] 11394 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11395 if (!RefType->getPointeeType()->isFunctionType()) 11396 CaptureType = RefType->getPointeeType(); 11397 } 11398 11399 // Forbid the lambda copy-capture of autoreleasing variables. 11400 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11401 if (BuildAndDiagnose) { 11402 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11403 Diag(Var->getLocation(), diag::note_previous_decl) 11404 << Var->getDeclName(); 11405 } 11406 return true; 11407 } 11408 } 11409 11410 // Capture this variable in the lambda. 11411 Expr *CopyExpr = 0; 11412 if (BuildAndDiagnose) { 11413 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 11414 DeclRefType, Loc, 11415 Nested); 11416 if (!Result.isInvalid()) 11417 CopyExpr = Result.take(); 11418 } 11419 11420 // Compute the type of a reference to this captured variable. 11421 if (ByRef) 11422 DeclRefType = CaptureType.getNonReferenceType(); 11423 else { 11424 // C++ [expr.prim.lambda]p5: 11425 // The closure type for a lambda-expression has a public inline 11426 // function call operator [...]. This function call operator is 11427 // declared const (9.3.1) if and only if the lambda-expression’s 11428 // parameter-declaration-clause is not followed by mutable. 11429 DeclRefType = CaptureType.getNonReferenceType(); 11430 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11431 DeclRefType.addConst(); 11432 } 11433 11434 // Add the capture. 11435 if (BuildAndDiagnose) 11436 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 11437 EllipsisLoc, CaptureType, CopyExpr); 11438 Nested = true; 11439 } 11440 11441 return false; 11442 } 11443 11444 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11445 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 11446 QualType CaptureType; 11447 QualType DeclRefType; 11448 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 11449 /*BuildAndDiagnose=*/true, CaptureType, 11450 DeclRefType); 11451 } 11452 11453 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 11454 QualType CaptureType; 11455 QualType DeclRefType; 11456 11457 // Determine whether we can capture this variable. 11458 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 11459 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 11460 return QualType(); 11461 11462 return DeclRefType; 11463 } 11464 11465 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 11466 SourceLocation Loc) { 11467 // Keep track of used but undefined variables. 11468 // FIXME: We shouldn't suppress this warning for static data members. 11469 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 11470 Var->getLinkage() != ExternalLinkage && 11471 !(Var->isStaticDataMember() && Var->hasInit())) { 11472 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 11473 if (old.isInvalid()) old = Loc; 11474 } 11475 11476 SemaRef.tryCaptureVariable(Var, Loc); 11477 11478 Var->setUsed(true); 11479 } 11480 11481 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 11482 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 11483 // an object that satisfies the requirements for appearing in a 11484 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 11485 // is immediately applied." This function handles the lvalue-to-rvalue 11486 // conversion part. 11487 MaybeODRUseExprs.erase(E->IgnoreParens()); 11488 } 11489 11490 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 11491 if (!Res.isUsable()) 11492 return Res; 11493 11494 // If a constant-expression is a reference to a variable where we delay 11495 // deciding whether it is an odr-use, just assume we will apply the 11496 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 11497 // (a non-type template argument), we have special handling anyway. 11498 UpdateMarkingForLValueToRValue(Res.get()); 11499 return Res; 11500 } 11501 11502 void Sema::CleanupVarDeclMarking() { 11503 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 11504 e = MaybeODRUseExprs.end(); 11505 i != e; ++i) { 11506 VarDecl *Var; 11507 SourceLocation Loc; 11508 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 11509 Var = cast<VarDecl>(DRE->getDecl()); 11510 Loc = DRE->getLocation(); 11511 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 11512 Var = cast<VarDecl>(ME->getMemberDecl()); 11513 Loc = ME->getMemberLoc(); 11514 } else { 11515 llvm_unreachable("Unexpcted expression"); 11516 } 11517 11518 MarkVarDeclODRUsed(*this, Var, Loc); 11519 } 11520 11521 MaybeODRUseExprs.clear(); 11522 } 11523 11524 // Mark a VarDecl referenced, and perform the necessary handling to compute 11525 // odr-uses. 11526 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 11527 VarDecl *Var, Expr *E) { 11528 Var->setReferenced(); 11529 11530 if (!IsPotentiallyEvaluatedContext(SemaRef)) 11531 return; 11532 11533 // Implicit instantiation of static data members of class templates. 11534 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) { 11535 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 11536 assert(MSInfo && "Missing member specialization information?"); 11537 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 11538 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && 11539 (!AlreadyInstantiated || 11540 Var->isUsableInConstantExpressions(SemaRef.Context))) { 11541 if (!AlreadyInstantiated) { 11542 // This is a modification of an existing AST node. Notify listeners. 11543 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 11544 L->StaticDataMemberInstantiated(Var); 11545 MSInfo->setPointOfInstantiation(Loc); 11546 } 11547 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11548 if (Var->isUsableInConstantExpressions(SemaRef.Context)) 11549 // Do not defer instantiations of variables which could be used in a 11550 // constant expression. 11551 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var); 11552 else 11553 SemaRef.PendingInstantiations.push_back( 11554 std::make_pair(Var, PointOfInstantiation)); 11555 } 11556 } 11557 11558 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 11559 // the requirements for appearing in a constant expression (5.19) and, if 11560 // it is an object, the lvalue-to-rvalue conversion (4.1) 11561 // is immediately applied." We check the first part here, and 11562 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 11563 // Note that we use the C++11 definition everywhere because nothing in 11564 // C++03 depends on whether we get the C++03 version correct. The second 11565 // part does not apply to references, since they are not objects. 11566 const VarDecl *DefVD; 11567 if (E && !isa<ParmVarDecl>(Var) && 11568 Var->isUsableInConstantExpressions(SemaRef.Context) && 11569 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) { 11570 if (!Var->getType()->isReferenceType()) 11571 SemaRef.MaybeODRUseExprs.insert(E); 11572 } else 11573 MarkVarDeclODRUsed(SemaRef, Var, Loc); 11574 } 11575 11576 /// \brief Mark a variable referenced, and check whether it is odr-used 11577 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 11578 /// used directly for normal expressions referring to VarDecl. 11579 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 11580 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 11581 } 11582 11583 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 11584 Decl *D, Expr *E, bool OdrUse) { 11585 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 11586 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 11587 return; 11588 } 11589 11590 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 11591 11592 // If this is a call to a method via a cast, also mark the method in the 11593 // derived class used in case codegen can devirtualize the call. 11594 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11595 if (!ME) 11596 return; 11597 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 11598 if (!MD) 11599 return; 11600 const Expr *Base = ME->getBase(); 11601 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 11602 if (!MostDerivedClassDecl) 11603 return; 11604 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 11605 if (!DM || DM->isPure()) 11606 return; 11607 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 11608 } 11609 11610 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 11611 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 11612 // TODO: update this with DR# once a defect report is filed. 11613 // C++11 defect. The address of a pure member should not be an ODR use, even 11614 // if it's a qualified reference. 11615 bool OdrUse = true; 11616 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 11617 if (Method->isVirtual()) 11618 OdrUse = false; 11619 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 11620 } 11621 11622 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 11623 void Sema::MarkMemberReferenced(MemberExpr *E) { 11624 // C++11 [basic.def.odr]p2: 11625 // A non-overloaded function whose name appears as a potentially-evaluated 11626 // expression or a member of a set of candidate functions, if selected by 11627 // overload resolution when referred to from a potentially-evaluated 11628 // expression, is odr-used, unless it is a pure virtual function and its 11629 // name is not explicitly qualified. 11630 bool OdrUse = true; 11631 if (!E->hasQualifier()) { 11632 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 11633 if (Method->isPure()) 11634 OdrUse = false; 11635 } 11636 SourceLocation Loc = E->getMemberLoc().isValid() ? 11637 E->getMemberLoc() : E->getLocStart(); 11638 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 11639 } 11640 11641 /// \brief Perform marking for a reference to an arbitrary declaration. It 11642 /// marks the declaration referenced, and performs odr-use checking for functions 11643 /// and variables. This method should not be used when building an normal 11644 /// expression which refers to a variable. 11645 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 11646 if (OdrUse) { 11647 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11648 MarkVariableReferenced(Loc, VD); 11649 return; 11650 } 11651 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 11652 MarkFunctionReferenced(Loc, FD); 11653 return; 11654 } 11655 } 11656 D->setReferenced(); 11657 } 11658 11659 namespace { 11660 // Mark all of the declarations referenced 11661 // FIXME: Not fully implemented yet! We need to have a better understanding 11662 // of when we're entering 11663 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 11664 Sema &S; 11665 SourceLocation Loc; 11666 11667 public: 11668 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 11669 11670 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 11671 11672 bool TraverseTemplateArgument(const TemplateArgument &Arg); 11673 bool TraverseRecordType(RecordType *T); 11674 }; 11675 } 11676 11677 bool MarkReferencedDecls::TraverseTemplateArgument( 11678 const TemplateArgument &Arg) { 11679 if (Arg.getKind() == TemplateArgument::Declaration) { 11680 if (Decl *D = Arg.getAsDecl()) 11681 S.MarkAnyDeclReferenced(Loc, D, true); 11682 } 11683 11684 return Inherited::TraverseTemplateArgument(Arg); 11685 } 11686 11687 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 11688 if (ClassTemplateSpecializationDecl *Spec 11689 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 11690 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 11691 return TraverseTemplateArguments(Args.data(), Args.size()); 11692 } 11693 11694 return true; 11695 } 11696 11697 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 11698 MarkReferencedDecls Marker(*this, Loc); 11699 Marker.TraverseType(Context.getCanonicalType(T)); 11700 } 11701 11702 namespace { 11703 /// \brief Helper class that marks all of the declarations referenced by 11704 /// potentially-evaluated subexpressions as "referenced". 11705 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 11706 Sema &S; 11707 bool SkipLocalVariables; 11708 11709 public: 11710 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 11711 11712 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 11713 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 11714 11715 void VisitDeclRefExpr(DeclRefExpr *E) { 11716 // If we were asked not to visit local variables, don't. 11717 if (SkipLocalVariables) { 11718 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 11719 if (VD->hasLocalStorage()) 11720 return; 11721 } 11722 11723 S.MarkDeclRefReferenced(E); 11724 } 11725 11726 void VisitMemberExpr(MemberExpr *E) { 11727 S.MarkMemberReferenced(E); 11728 Inherited::VisitMemberExpr(E); 11729 } 11730 11731 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 11732 S.MarkFunctionReferenced(E->getLocStart(), 11733 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 11734 Visit(E->getSubExpr()); 11735 } 11736 11737 void VisitCXXNewExpr(CXXNewExpr *E) { 11738 if (E->getOperatorNew()) 11739 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 11740 if (E->getOperatorDelete()) 11741 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11742 Inherited::VisitCXXNewExpr(E); 11743 } 11744 11745 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 11746 if (E->getOperatorDelete()) 11747 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11748 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 11749 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 11750 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 11751 S.MarkFunctionReferenced(E->getLocStart(), 11752 S.LookupDestructor(Record)); 11753 } 11754 11755 Inherited::VisitCXXDeleteExpr(E); 11756 } 11757 11758 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11759 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 11760 Inherited::VisitCXXConstructExpr(E); 11761 } 11762 11763 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 11764 Visit(E->getExpr()); 11765 } 11766 11767 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11768 Inherited::VisitImplicitCastExpr(E); 11769 11770 if (E->getCastKind() == CK_LValueToRValue) 11771 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 11772 } 11773 }; 11774 } 11775 11776 /// \brief Mark any declarations that appear within this expression or any 11777 /// potentially-evaluated subexpressions as "referenced". 11778 /// 11779 /// \param SkipLocalVariables If true, don't mark local variables as 11780 /// 'referenced'. 11781 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 11782 bool SkipLocalVariables) { 11783 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 11784 } 11785 11786 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 11787 /// of the program being compiled. 11788 /// 11789 /// This routine emits the given diagnostic when the code currently being 11790 /// type-checked is "potentially evaluated", meaning that there is a 11791 /// possibility that the code will actually be executable. Code in sizeof() 11792 /// expressions, code used only during overload resolution, etc., are not 11793 /// potentially evaluated. This routine will suppress such diagnostics or, 11794 /// in the absolutely nutty case of potentially potentially evaluated 11795 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 11796 /// later. 11797 /// 11798 /// This routine should be used for all diagnostics that describe the run-time 11799 /// behavior of a program, such as passing a non-POD value through an ellipsis. 11800 /// Failure to do so will likely result in spurious diagnostics or failures 11801 /// during overload resolution or within sizeof/alignof/typeof/typeid. 11802 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 11803 const PartialDiagnostic &PD) { 11804 switch (ExprEvalContexts.back().Context) { 11805 case Unevaluated: 11806 case UnevaluatedAbstract: 11807 // The argument will never be evaluated, so don't complain. 11808 break; 11809 11810 case ConstantEvaluated: 11811 // Relevant diagnostics should be produced by constant evaluation. 11812 break; 11813 11814 case PotentiallyEvaluated: 11815 case PotentiallyEvaluatedIfUsed: 11816 if (Statement && getCurFunctionOrMethodDecl()) { 11817 FunctionScopes.back()->PossiblyUnreachableDiags. 11818 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 11819 } 11820 else 11821 Diag(Loc, PD); 11822 11823 return true; 11824 } 11825 11826 return false; 11827 } 11828 11829 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 11830 CallExpr *CE, FunctionDecl *FD) { 11831 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 11832 return false; 11833 11834 // If we're inside a decltype's expression, don't check for a valid return 11835 // type or construct temporaries until we know whether this is the last call. 11836 if (ExprEvalContexts.back().IsDecltype) { 11837 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 11838 return false; 11839 } 11840 11841 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 11842 FunctionDecl *FD; 11843 CallExpr *CE; 11844 11845 public: 11846 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 11847 : FD(FD), CE(CE) { } 11848 11849 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 11850 if (!FD) { 11851 S.Diag(Loc, diag::err_call_incomplete_return) 11852 << T << CE->getSourceRange(); 11853 return; 11854 } 11855 11856 S.Diag(Loc, diag::err_call_function_incomplete_return) 11857 << CE->getSourceRange() << FD->getDeclName() << T; 11858 S.Diag(FD->getLocation(), 11859 diag::note_function_with_incomplete_return_type_declared_here) 11860 << FD->getDeclName(); 11861 } 11862 } Diagnoser(FD, CE); 11863 11864 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 11865 return true; 11866 11867 return false; 11868 } 11869 11870 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 11871 // will prevent this condition from triggering, which is what we want. 11872 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 11873 SourceLocation Loc; 11874 11875 unsigned diagnostic = diag::warn_condition_is_assignment; 11876 bool IsOrAssign = false; 11877 11878 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 11879 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 11880 return; 11881 11882 IsOrAssign = Op->getOpcode() == BO_OrAssign; 11883 11884 // Greylist some idioms by putting them into a warning subcategory. 11885 if (ObjCMessageExpr *ME 11886 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 11887 Selector Sel = ME->getSelector(); 11888 11889 // self = [<foo> init...] 11890 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 11891 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11892 11893 // <foo> = [<bar> nextObject] 11894 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 11895 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11896 } 11897 11898 Loc = Op->getOperatorLoc(); 11899 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 11900 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 11901 return; 11902 11903 IsOrAssign = Op->getOperator() == OO_PipeEqual; 11904 Loc = Op->getOperatorLoc(); 11905 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 11906 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 11907 else { 11908 // Not an assignment. 11909 return; 11910 } 11911 11912 Diag(Loc, diagnostic) << E->getSourceRange(); 11913 11914 SourceLocation Open = E->getLocStart(); 11915 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 11916 Diag(Loc, diag::note_condition_assign_silence) 11917 << FixItHint::CreateInsertion(Open, "(") 11918 << FixItHint::CreateInsertion(Close, ")"); 11919 11920 if (IsOrAssign) 11921 Diag(Loc, diag::note_condition_or_assign_to_comparison) 11922 << FixItHint::CreateReplacement(Loc, "!="); 11923 else 11924 Diag(Loc, diag::note_condition_assign_to_comparison) 11925 << FixItHint::CreateReplacement(Loc, "=="); 11926 } 11927 11928 /// \brief Redundant parentheses over an equality comparison can indicate 11929 /// that the user intended an assignment used as condition. 11930 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 11931 // Don't warn if the parens came from a macro. 11932 SourceLocation parenLoc = ParenE->getLocStart(); 11933 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 11934 return; 11935 // Don't warn for dependent expressions. 11936 if (ParenE->isTypeDependent()) 11937 return; 11938 11939 Expr *E = ParenE->IgnoreParens(); 11940 11941 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 11942 if (opE->getOpcode() == BO_EQ && 11943 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 11944 == Expr::MLV_Valid) { 11945 SourceLocation Loc = opE->getOperatorLoc(); 11946 11947 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 11948 SourceRange ParenERange = ParenE->getSourceRange(); 11949 Diag(Loc, diag::note_equality_comparison_silence) 11950 << FixItHint::CreateRemoval(ParenERange.getBegin()) 11951 << FixItHint::CreateRemoval(ParenERange.getEnd()); 11952 Diag(Loc, diag::note_equality_comparison_to_assign) 11953 << FixItHint::CreateReplacement(Loc, "="); 11954 } 11955 } 11956 11957 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 11958 DiagnoseAssignmentAsCondition(E); 11959 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 11960 DiagnoseEqualityWithExtraParens(parenE); 11961 11962 ExprResult result = CheckPlaceholderExpr(E); 11963 if (result.isInvalid()) return ExprError(); 11964 E = result.take(); 11965 11966 if (!E->isTypeDependent()) { 11967 if (getLangOpts().CPlusPlus) 11968 return CheckCXXBooleanCondition(E); // C++ 6.4p4 11969 11970 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 11971 if (ERes.isInvalid()) 11972 return ExprError(); 11973 E = ERes.take(); 11974 11975 QualType T = E->getType(); 11976 if (!T->isScalarType()) { // C99 6.8.4.1p1 11977 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 11978 << T << E->getSourceRange(); 11979 return ExprError(); 11980 } 11981 } 11982 11983 return Owned(E); 11984 } 11985 11986 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 11987 Expr *SubExpr) { 11988 if (!SubExpr) 11989 return ExprError(); 11990 11991 return CheckBooleanCondition(SubExpr, Loc); 11992 } 11993 11994 namespace { 11995 /// A visitor for rebuilding a call to an __unknown_any expression 11996 /// to have an appropriate type. 11997 struct RebuildUnknownAnyFunction 11998 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 11999 12000 Sema &S; 12001 12002 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12003 12004 ExprResult VisitStmt(Stmt *S) { 12005 llvm_unreachable("unexpected statement!"); 12006 } 12007 12008 ExprResult VisitExpr(Expr *E) { 12009 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12010 << E->getSourceRange(); 12011 return ExprError(); 12012 } 12013 12014 /// Rebuild an expression which simply semantically wraps another 12015 /// expression which it shares the type and value kind of. 12016 template <class T> ExprResult rebuildSugarExpr(T *E) { 12017 ExprResult SubResult = Visit(E->getSubExpr()); 12018 if (SubResult.isInvalid()) return ExprError(); 12019 12020 Expr *SubExpr = SubResult.take(); 12021 E->setSubExpr(SubExpr); 12022 E->setType(SubExpr->getType()); 12023 E->setValueKind(SubExpr->getValueKind()); 12024 assert(E->getObjectKind() == OK_Ordinary); 12025 return E; 12026 } 12027 12028 ExprResult VisitParenExpr(ParenExpr *E) { 12029 return rebuildSugarExpr(E); 12030 } 12031 12032 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12033 return rebuildSugarExpr(E); 12034 } 12035 12036 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12037 ExprResult SubResult = Visit(E->getSubExpr()); 12038 if (SubResult.isInvalid()) return ExprError(); 12039 12040 Expr *SubExpr = SubResult.take(); 12041 E->setSubExpr(SubExpr); 12042 E->setType(S.Context.getPointerType(SubExpr->getType())); 12043 assert(E->getValueKind() == VK_RValue); 12044 assert(E->getObjectKind() == OK_Ordinary); 12045 return E; 12046 } 12047 12048 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12049 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12050 12051 E->setType(VD->getType()); 12052 12053 assert(E->getValueKind() == VK_RValue); 12054 if (S.getLangOpts().CPlusPlus && 12055 !(isa<CXXMethodDecl>(VD) && 12056 cast<CXXMethodDecl>(VD)->isInstance())) 12057 E->setValueKind(VK_LValue); 12058 12059 return E; 12060 } 12061 12062 ExprResult VisitMemberExpr(MemberExpr *E) { 12063 return resolveDecl(E, E->getMemberDecl()); 12064 } 12065 12066 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12067 return resolveDecl(E, E->getDecl()); 12068 } 12069 }; 12070 } 12071 12072 /// Given a function expression of unknown-any type, try to rebuild it 12073 /// to have a function type. 12074 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12075 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12076 if (Result.isInvalid()) return ExprError(); 12077 return S.DefaultFunctionArrayConversion(Result.take()); 12078 } 12079 12080 namespace { 12081 /// A visitor for rebuilding an expression of type __unknown_anytype 12082 /// into one which resolves the type directly on the referring 12083 /// expression. Strict preservation of the original source 12084 /// structure is not a goal. 12085 struct RebuildUnknownAnyExpr 12086 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12087 12088 Sema &S; 12089 12090 /// The current destination type. 12091 QualType DestType; 12092 12093 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12094 : S(S), DestType(CastType) {} 12095 12096 ExprResult VisitStmt(Stmt *S) { 12097 llvm_unreachable("unexpected statement!"); 12098 } 12099 12100 ExprResult VisitExpr(Expr *E) { 12101 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12102 << E->getSourceRange(); 12103 return ExprError(); 12104 } 12105 12106 ExprResult VisitCallExpr(CallExpr *E); 12107 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12108 12109 /// Rebuild an expression which simply semantically wraps another 12110 /// expression which it shares the type and value kind of. 12111 template <class T> ExprResult rebuildSugarExpr(T *E) { 12112 ExprResult SubResult = Visit(E->getSubExpr()); 12113 if (SubResult.isInvalid()) return ExprError(); 12114 Expr *SubExpr = SubResult.take(); 12115 E->setSubExpr(SubExpr); 12116 E->setType(SubExpr->getType()); 12117 E->setValueKind(SubExpr->getValueKind()); 12118 assert(E->getObjectKind() == OK_Ordinary); 12119 return E; 12120 } 12121 12122 ExprResult VisitParenExpr(ParenExpr *E) { 12123 return rebuildSugarExpr(E); 12124 } 12125 12126 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12127 return rebuildSugarExpr(E); 12128 } 12129 12130 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12131 const PointerType *Ptr = DestType->getAs<PointerType>(); 12132 if (!Ptr) { 12133 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12134 << E->getSourceRange(); 12135 return ExprError(); 12136 } 12137 assert(E->getValueKind() == VK_RValue); 12138 assert(E->getObjectKind() == OK_Ordinary); 12139 E->setType(DestType); 12140 12141 // Build the sub-expression as if it were an object of the pointee type. 12142 DestType = Ptr->getPointeeType(); 12143 ExprResult SubResult = Visit(E->getSubExpr()); 12144 if (SubResult.isInvalid()) return ExprError(); 12145 E->setSubExpr(SubResult.take()); 12146 return E; 12147 } 12148 12149 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12150 12151 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12152 12153 ExprResult VisitMemberExpr(MemberExpr *E) { 12154 return resolveDecl(E, E->getMemberDecl()); 12155 } 12156 12157 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12158 return resolveDecl(E, E->getDecl()); 12159 } 12160 }; 12161 } 12162 12163 /// Rebuilds a call expression which yielded __unknown_anytype. 12164 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12165 Expr *CalleeExpr = E->getCallee(); 12166 12167 enum FnKind { 12168 FK_MemberFunction, 12169 FK_FunctionPointer, 12170 FK_BlockPointer 12171 }; 12172 12173 FnKind Kind; 12174 QualType CalleeType = CalleeExpr->getType(); 12175 if (CalleeType == S.Context.BoundMemberTy) { 12176 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12177 Kind = FK_MemberFunction; 12178 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12179 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12180 CalleeType = Ptr->getPointeeType(); 12181 Kind = FK_FunctionPointer; 12182 } else { 12183 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12184 Kind = FK_BlockPointer; 12185 } 12186 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12187 12188 // Verify that this is a legal result type of a function. 12189 if (DestType->isArrayType() || DestType->isFunctionType()) { 12190 unsigned diagID = diag::err_func_returning_array_function; 12191 if (Kind == FK_BlockPointer) 12192 diagID = diag::err_block_returning_array_function; 12193 12194 S.Diag(E->getExprLoc(), diagID) 12195 << DestType->isFunctionType() << DestType; 12196 return ExprError(); 12197 } 12198 12199 // Otherwise, go ahead and set DestType as the call's result. 12200 E->setType(DestType.getNonLValueExprType(S.Context)); 12201 E->setValueKind(Expr::getValueKindForType(DestType)); 12202 assert(E->getObjectKind() == OK_Ordinary); 12203 12204 // Rebuild the function type, replacing the result type with DestType. 12205 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType)) 12206 DestType = 12207 S.Context.getFunctionType(DestType, 12208 ArrayRef<QualType>(Proto->arg_type_begin(), 12209 Proto->getNumArgs()), 12210 Proto->getExtProtoInfo()); 12211 else 12212 DestType = S.Context.getFunctionNoProtoType(DestType, 12213 FnType->getExtInfo()); 12214 12215 // Rebuild the appropriate pointer-to-function type. 12216 switch (Kind) { 12217 case FK_MemberFunction: 12218 // Nothing to do. 12219 break; 12220 12221 case FK_FunctionPointer: 12222 DestType = S.Context.getPointerType(DestType); 12223 break; 12224 12225 case FK_BlockPointer: 12226 DestType = S.Context.getBlockPointerType(DestType); 12227 break; 12228 } 12229 12230 // Finally, we can recurse. 12231 ExprResult CalleeResult = Visit(CalleeExpr); 12232 if (!CalleeResult.isUsable()) return ExprError(); 12233 E->setCallee(CalleeResult.take()); 12234 12235 // Bind a temporary if necessary. 12236 return S.MaybeBindToTemporary(E); 12237 } 12238 12239 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12240 // Verify that this is a legal result type of a call. 12241 if (DestType->isArrayType() || DestType->isFunctionType()) { 12242 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 12243 << DestType->isFunctionType() << DestType; 12244 return ExprError(); 12245 } 12246 12247 // Rewrite the method result type if available. 12248 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 12249 assert(Method->getResultType() == S.Context.UnknownAnyTy); 12250 Method->setResultType(DestType); 12251 } 12252 12253 // Change the type of the message. 12254 E->setType(DestType.getNonReferenceType()); 12255 E->setValueKind(Expr::getValueKindForType(DestType)); 12256 12257 return S.MaybeBindToTemporary(E); 12258 } 12259 12260 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 12261 // The only case we should ever see here is a function-to-pointer decay. 12262 if (E->getCastKind() == CK_FunctionToPointerDecay) { 12263 assert(E->getValueKind() == VK_RValue); 12264 assert(E->getObjectKind() == OK_Ordinary); 12265 12266 E->setType(DestType); 12267 12268 // Rebuild the sub-expression as the pointee (function) type. 12269 DestType = DestType->castAs<PointerType>()->getPointeeType(); 12270 12271 ExprResult Result = Visit(E->getSubExpr()); 12272 if (!Result.isUsable()) return ExprError(); 12273 12274 E->setSubExpr(Result.take()); 12275 return S.Owned(E); 12276 } else if (E->getCastKind() == CK_LValueToRValue) { 12277 assert(E->getValueKind() == VK_RValue); 12278 assert(E->getObjectKind() == OK_Ordinary); 12279 12280 assert(isa<BlockPointerType>(E->getType())); 12281 12282 E->setType(DestType); 12283 12284 // The sub-expression has to be a lvalue reference, so rebuild it as such. 12285 DestType = S.Context.getLValueReferenceType(DestType); 12286 12287 ExprResult Result = Visit(E->getSubExpr()); 12288 if (!Result.isUsable()) return ExprError(); 12289 12290 E->setSubExpr(Result.take()); 12291 return S.Owned(E); 12292 } else { 12293 llvm_unreachable("Unhandled cast type!"); 12294 } 12295 } 12296 12297 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 12298 ExprValueKind ValueKind = VK_LValue; 12299 QualType Type = DestType; 12300 12301 // We know how to make this work for certain kinds of decls: 12302 12303 // - functions 12304 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 12305 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 12306 DestType = Ptr->getPointeeType(); 12307 ExprResult Result = resolveDecl(E, VD); 12308 if (Result.isInvalid()) return ExprError(); 12309 return S.ImpCastExprToType(Result.take(), Type, 12310 CK_FunctionToPointerDecay, VK_RValue); 12311 } 12312 12313 if (!Type->isFunctionType()) { 12314 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 12315 << VD << E->getSourceRange(); 12316 return ExprError(); 12317 } 12318 12319 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 12320 if (MD->isInstance()) { 12321 ValueKind = VK_RValue; 12322 Type = S.Context.BoundMemberTy; 12323 } 12324 12325 // Function references aren't l-values in C. 12326 if (!S.getLangOpts().CPlusPlus) 12327 ValueKind = VK_RValue; 12328 12329 // - variables 12330 } else if (isa<VarDecl>(VD)) { 12331 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 12332 Type = RefTy->getPointeeType(); 12333 } else if (Type->isFunctionType()) { 12334 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 12335 << VD << E->getSourceRange(); 12336 return ExprError(); 12337 } 12338 12339 // - nothing else 12340 } else { 12341 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 12342 << VD << E->getSourceRange(); 12343 return ExprError(); 12344 } 12345 12346 VD->setType(DestType); 12347 E->setType(Type); 12348 E->setValueKind(ValueKind); 12349 return S.Owned(E); 12350 } 12351 12352 /// Check a cast of an unknown-any type. We intentionally only 12353 /// trigger this for C-style casts. 12354 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 12355 Expr *CastExpr, CastKind &CastKind, 12356 ExprValueKind &VK, CXXCastPath &Path) { 12357 // Rewrite the casted expression from scratch. 12358 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 12359 if (!result.isUsable()) return ExprError(); 12360 12361 CastExpr = result.take(); 12362 VK = CastExpr->getValueKind(); 12363 CastKind = CK_NoOp; 12364 12365 return CastExpr; 12366 } 12367 12368 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 12369 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 12370 } 12371 12372 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 12373 Expr *arg, QualType ¶mType) { 12374 // If the syntactic form of the argument is not an explicit cast of 12375 // any sort, just do default argument promotion. 12376 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 12377 if (!castArg) { 12378 ExprResult result = DefaultArgumentPromotion(arg); 12379 if (result.isInvalid()) return ExprError(); 12380 paramType = result.get()->getType(); 12381 return result; 12382 } 12383 12384 // Otherwise, use the type that was written in the explicit cast. 12385 assert(!arg->hasPlaceholderType()); 12386 paramType = castArg->getTypeAsWritten(); 12387 12388 // Copy-initialize a parameter of that type. 12389 InitializedEntity entity = 12390 InitializedEntity::InitializeParameter(Context, paramType, 12391 /*consumed*/ false); 12392 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 12393 } 12394 12395 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 12396 Expr *orig = E; 12397 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 12398 while (true) { 12399 E = E->IgnoreParenImpCasts(); 12400 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 12401 E = call->getCallee(); 12402 diagID = diag::err_uncasted_call_of_unknown_any; 12403 } else { 12404 break; 12405 } 12406 } 12407 12408 SourceLocation loc; 12409 NamedDecl *d; 12410 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 12411 loc = ref->getLocation(); 12412 d = ref->getDecl(); 12413 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 12414 loc = mem->getMemberLoc(); 12415 d = mem->getMemberDecl(); 12416 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 12417 diagID = diag::err_uncasted_call_of_unknown_any; 12418 loc = msg->getSelectorStartLoc(); 12419 d = msg->getMethodDecl(); 12420 if (!d) { 12421 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 12422 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 12423 << orig->getSourceRange(); 12424 return ExprError(); 12425 } 12426 } else { 12427 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12428 << E->getSourceRange(); 12429 return ExprError(); 12430 } 12431 12432 S.Diag(loc, diagID) << d << orig->getSourceRange(); 12433 12434 // Never recoverable. 12435 return ExprError(); 12436 } 12437 12438 /// Check for operands with placeholder types and complain if found. 12439 /// Returns true if there was an error and no recovery was possible. 12440 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 12441 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 12442 if (!placeholderType) return Owned(E); 12443 12444 switch (placeholderType->getKind()) { 12445 12446 // Overloaded expressions. 12447 case BuiltinType::Overload: { 12448 // Try to resolve a single function template specialization. 12449 // This is obligatory. 12450 ExprResult result = Owned(E); 12451 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 12452 return result; 12453 12454 // If that failed, try to recover with a call. 12455 } else { 12456 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 12457 /*complain*/ true); 12458 return result; 12459 } 12460 } 12461 12462 // Bound member functions. 12463 case BuiltinType::BoundMember: { 12464 ExprResult result = Owned(E); 12465 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 12466 /*complain*/ true); 12467 return result; 12468 } 12469 12470 // ARC unbridged casts. 12471 case BuiltinType::ARCUnbridgedCast: { 12472 Expr *realCast = stripARCUnbridgedCast(E); 12473 diagnoseARCUnbridgedCast(realCast); 12474 return Owned(realCast); 12475 } 12476 12477 // Expressions of unknown type. 12478 case BuiltinType::UnknownAny: 12479 return diagnoseUnknownAnyExpr(*this, E); 12480 12481 // Pseudo-objects. 12482 case BuiltinType::PseudoObject: 12483 return checkPseudoObjectRValue(E); 12484 12485 case BuiltinType::BuiltinFn: 12486 Diag(E->getLocStart(), diag::err_builtin_fn_use); 12487 return ExprError(); 12488 12489 // Everything else should be impossible. 12490 #define BUILTIN_TYPE(Id, SingletonId) \ 12491 case BuiltinType::Id: 12492 #define PLACEHOLDER_TYPE(Id, SingletonId) 12493 #include "clang/AST/BuiltinTypes.def" 12494 break; 12495 } 12496 12497 llvm_unreachable("invalid placeholder type!"); 12498 } 12499 12500 bool Sema::CheckCaseExpression(Expr *E) { 12501 if (E->isTypeDependent()) 12502 return true; 12503 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 12504 return E->getType()->isIntegralOrEnumerationType(); 12505 return false; 12506 } 12507 12508 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 12509 ExprResult 12510 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 12511 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 12512 "Unknown Objective-C Boolean value!"); 12513 QualType BoolT = Context.ObjCBuiltinBoolTy; 12514 if (!Context.getBOOLDecl()) { 12515 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 12516 Sema::LookupOrdinaryName); 12517 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 12518 NamedDecl *ND = Result.getFoundDecl(); 12519 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 12520 Context.setBOOLDecl(TD); 12521 } 12522 } 12523 if (Context.getBOOLDecl()) 12524 BoolT = Context.getBOOLType(); 12525 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 12526 BoolT, OpLoc)); 12527 } 12528