1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/Support/ConvertUTF.h" 46 using namespace clang; 47 using namespace sema; 48 49 /// \brief Determine whether the use of this declaration is valid, without 50 /// emitting diagnostics. 51 bool Sema::CanUseDecl(NamedDecl *D) { 52 // See if this is an auto-typed variable whose initializer we are parsing. 53 if (ParsingInitForAutoVars.count(D)) 54 return false; 55 56 // See if this is a deleted function. 57 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 58 if (FD->isDeleted()) 59 return false; 60 61 // If the function has a deduced return type, and we can't deduce it, 62 // then we can't use it either. 63 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 64 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 65 return false; 66 } 67 68 // See if this function is unavailable. 69 if (D->getAvailability() == AR_Unavailable && 70 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 71 return false; 72 73 return true; 74 } 75 76 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 77 // Warn if this is used but marked unused. 78 if (D->hasAttr<UnusedAttr>()) { 79 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 80 if (DC && !DC->hasAttr<UnusedAttr>()) 81 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 82 } 83 } 84 85 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 86 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 87 if (!OMD) 88 return false; 89 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 90 if (!OID) 91 return false; 92 93 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 94 if (ObjCMethodDecl *CatMeth = 95 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 96 if (!CatMeth->hasAttr<AvailabilityAttr>()) 97 return true; 98 return false; 99 } 100 101 static AvailabilityResult 102 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 103 const ObjCInterfaceDecl *UnknownObjCClass, 104 bool ObjCPropertyAccess) { 105 // See if this declaration is unavailable or deprecated. 106 std::string Message; 107 AvailabilityResult Result = D->getAvailability(&Message); 108 109 // For typedefs, if the typedef declaration appears available look 110 // to the underlying type to see if it is more restrictive. 111 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 112 if (Result == AR_Available) { 113 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 114 D = TT->getDecl(); 115 Result = D->getAvailability(&Message); 116 continue; 117 } 118 } 119 break; 120 } 121 122 // Forward class declarations get their attributes from their definition. 123 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 124 if (IDecl->getDefinition()) { 125 D = IDecl->getDefinition(); 126 Result = D->getAvailability(&Message); 127 } 128 } 129 130 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 131 if (Result == AR_Available) { 132 const DeclContext *DC = ECD->getDeclContext(); 133 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 134 Result = TheEnumDecl->getAvailability(&Message); 135 } 136 137 const ObjCPropertyDecl *ObjCPDecl = nullptr; 138 if (Result == AR_Deprecated || Result == AR_Unavailable || 139 AR_NotYetIntroduced) { 140 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 141 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 142 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 143 if (PDeclResult == Result) 144 ObjCPDecl = PD; 145 } 146 } 147 } 148 149 switch (Result) { 150 case AR_Available: 151 break; 152 153 case AR_Deprecated: 154 if (S.getCurContextAvailability() != AR_Deprecated) 155 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 156 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 157 ObjCPropertyAccess); 158 break; 159 160 case AR_NotYetIntroduced: { 161 // Don't do this for enums, they can't be redeclared. 162 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 163 break; 164 165 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 166 // Objective-C method declarations in categories are not modelled as 167 // redeclarations, so manually look for a redeclaration in a category 168 // if necessary. 169 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 170 Warn = false; 171 // In general, D will point to the most recent redeclaration. However, 172 // for `@class A;` decls, this isn't true -- manually go through the 173 // redecl chain in that case. 174 if (Warn && isa<ObjCInterfaceDecl>(D)) 175 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 176 Redecl = Redecl->getPreviousDecl()) 177 if (!Redecl->hasAttr<AvailabilityAttr>() || 178 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 179 Warn = false; 180 181 if (Warn) 182 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 183 UnknownObjCClass, ObjCPDecl, 184 ObjCPropertyAccess); 185 break; 186 } 187 188 case AR_Unavailable: 189 if (S.getCurContextAvailability() != AR_Unavailable) 190 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 191 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 192 ObjCPropertyAccess); 193 break; 194 195 } 196 return Result; 197 } 198 199 /// \brief Emit a note explaining that this function is deleted. 200 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 201 assert(Decl->isDeleted()); 202 203 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 204 205 if (Method && Method->isDeleted() && Method->isDefaulted()) { 206 // If the method was explicitly defaulted, point at that declaration. 207 if (!Method->isImplicit()) 208 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 209 210 // Try to diagnose why this special member function was implicitly 211 // deleted. This might fail, if that reason no longer applies. 212 CXXSpecialMember CSM = getSpecialMember(Method); 213 if (CSM != CXXInvalid) 214 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 215 216 return; 217 } 218 219 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 220 if (CXXConstructorDecl *BaseCD = 221 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 222 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 223 if (BaseCD->isDeleted()) { 224 NoteDeletedFunction(BaseCD); 225 } else { 226 // FIXME: An explanation of why exactly it can't be inherited 227 // would be nice. 228 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 229 } 230 return; 231 } 232 } 233 234 Diag(Decl->getLocation(), diag::note_availability_specified_here) 235 << Decl << true; 236 } 237 238 /// \brief Determine whether a FunctionDecl was ever declared with an 239 /// explicit storage class. 240 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 241 for (auto I : D->redecls()) { 242 if (I->getStorageClass() != SC_None) 243 return true; 244 } 245 return false; 246 } 247 248 /// \brief Check whether we're in an extern inline function and referring to a 249 /// variable or function with internal linkage (C11 6.7.4p3). 250 /// 251 /// This is only a warning because we used to silently accept this code, but 252 /// in many cases it will not behave correctly. This is not enabled in C++ mode 253 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 254 /// and so while there may still be user mistakes, most of the time we can't 255 /// prove that there are errors. 256 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 257 const NamedDecl *D, 258 SourceLocation Loc) { 259 // This is disabled under C++; there are too many ways for this to fire in 260 // contexts where the warning is a false positive, or where it is technically 261 // correct but benign. 262 if (S.getLangOpts().CPlusPlus) 263 return; 264 265 // Check if this is an inlined function or method. 266 FunctionDecl *Current = S.getCurFunctionDecl(); 267 if (!Current) 268 return; 269 if (!Current->isInlined()) 270 return; 271 if (!Current->isExternallyVisible()) 272 return; 273 274 // Check if the decl has internal linkage. 275 if (D->getFormalLinkage() != InternalLinkage) 276 return; 277 278 // Downgrade from ExtWarn to Extension if 279 // (1) the supposedly external inline function is in the main file, 280 // and probably won't be included anywhere else. 281 // (2) the thing we're referencing is a pure function. 282 // (3) the thing we're referencing is another inline function. 283 // This last can give us false negatives, but it's better than warning on 284 // wrappers for simple C library functions. 285 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 286 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 287 if (!DowngradeWarning && UsedFn) 288 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 289 290 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 291 : diag::ext_internal_in_extern_inline) 292 << /*IsVar=*/!UsedFn << D; 293 294 S.MaybeSuggestAddingStaticToDecl(Current); 295 296 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 297 << D; 298 } 299 300 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 301 const FunctionDecl *First = Cur->getFirstDecl(); 302 303 // Suggest "static" on the function, if possible. 304 if (!hasAnyExplicitStorageClass(First)) { 305 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 306 Diag(DeclBegin, diag::note_convert_inline_to_static) 307 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 308 } 309 } 310 311 /// \brief Determine whether the use of this declaration is valid, and 312 /// emit any corresponding diagnostics. 313 /// 314 /// This routine diagnoses various problems with referencing 315 /// declarations that can occur when using a declaration. For example, 316 /// it might warn if a deprecated or unavailable declaration is being 317 /// used, or produce an error (and return true) if a C++0x deleted 318 /// function is being used. 319 /// 320 /// \returns true if there was an error (this declaration cannot be 321 /// referenced), false otherwise. 322 /// 323 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 324 const ObjCInterfaceDecl *UnknownObjCClass, 325 bool ObjCPropertyAccess) { 326 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 327 // If there were any diagnostics suppressed by template argument deduction, 328 // emit them now. 329 SuppressedDiagnosticsMap::iterator 330 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 331 if (Pos != SuppressedDiagnostics.end()) { 332 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 333 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 334 Diag(Suppressed[I].first, Suppressed[I].second); 335 336 // Clear out the list of suppressed diagnostics, so that we don't emit 337 // them again for this specialization. However, we don't obsolete this 338 // entry from the table, because we want to avoid ever emitting these 339 // diagnostics again. 340 Suppressed.clear(); 341 } 342 343 // C++ [basic.start.main]p3: 344 // The function 'main' shall not be used within a program. 345 if (cast<FunctionDecl>(D)->isMain()) 346 Diag(Loc, diag::ext_main_used); 347 } 348 349 // See if this is an auto-typed variable whose initializer we are parsing. 350 if (ParsingInitForAutoVars.count(D)) { 351 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 352 << D->getDeclName(); 353 return true; 354 } 355 356 // See if this is a deleted function. 357 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 358 if (FD->isDeleted()) { 359 Diag(Loc, diag::err_deleted_function_use); 360 NoteDeletedFunction(FD); 361 return true; 362 } 363 364 // If the function has a deduced return type, and we can't deduce it, 365 // then we can't use it either. 366 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 367 DeduceReturnType(FD, Loc)) 368 return true; 369 } 370 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 371 ObjCPropertyAccess); 372 373 DiagnoseUnusedOfDecl(*this, D, Loc); 374 375 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 376 377 return false; 378 } 379 380 /// \brief Retrieve the message suffix that should be added to a 381 /// diagnostic complaining about the given function being deleted or 382 /// unavailable. 383 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 384 std::string Message; 385 if (FD->getAvailability(&Message)) 386 return ": " + Message; 387 388 return std::string(); 389 } 390 391 /// DiagnoseSentinelCalls - This routine checks whether a call or 392 /// message-send is to a declaration with the sentinel attribute, and 393 /// if so, it checks that the requirements of the sentinel are 394 /// satisfied. 395 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 396 ArrayRef<Expr *> Args) { 397 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 398 if (!attr) 399 return; 400 401 // The number of formal parameters of the declaration. 402 unsigned numFormalParams; 403 404 // The kind of declaration. This is also an index into a %select in 405 // the diagnostic. 406 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 407 408 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 409 numFormalParams = MD->param_size(); 410 calleeType = CT_Method; 411 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 412 numFormalParams = FD->param_size(); 413 calleeType = CT_Function; 414 } else if (isa<VarDecl>(D)) { 415 QualType type = cast<ValueDecl>(D)->getType(); 416 const FunctionType *fn = nullptr; 417 if (const PointerType *ptr = type->getAs<PointerType>()) { 418 fn = ptr->getPointeeType()->getAs<FunctionType>(); 419 if (!fn) return; 420 calleeType = CT_Function; 421 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 422 fn = ptr->getPointeeType()->castAs<FunctionType>(); 423 calleeType = CT_Block; 424 } else { 425 return; 426 } 427 428 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 429 numFormalParams = proto->getNumParams(); 430 } else { 431 numFormalParams = 0; 432 } 433 } else { 434 return; 435 } 436 437 // "nullPos" is the number of formal parameters at the end which 438 // effectively count as part of the variadic arguments. This is 439 // useful if you would prefer to not have *any* formal parameters, 440 // but the language forces you to have at least one. 441 unsigned nullPos = attr->getNullPos(); 442 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 443 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 444 445 // The number of arguments which should follow the sentinel. 446 unsigned numArgsAfterSentinel = attr->getSentinel(); 447 448 // If there aren't enough arguments for all the formal parameters, 449 // the sentinel, and the args after the sentinel, complain. 450 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 451 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 452 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 453 return; 454 } 455 456 // Otherwise, find the sentinel expression. 457 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 458 if (!sentinelExpr) return; 459 if (sentinelExpr->isValueDependent()) return; 460 if (Context.isSentinelNullExpr(sentinelExpr)) return; 461 462 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 463 // or 'NULL' if those are actually defined in the context. Only use 464 // 'nil' for ObjC methods, where it's much more likely that the 465 // variadic arguments form a list of object pointers. 466 SourceLocation MissingNilLoc 467 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 468 std::string NullValue; 469 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 470 NullValue = "nil"; 471 else if (getLangOpts().CPlusPlus11) 472 NullValue = "nullptr"; 473 else if (PP.isMacroDefined("NULL")) 474 NullValue = "NULL"; 475 else 476 NullValue = "(void*) 0"; 477 478 if (MissingNilLoc.isInvalid()) 479 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 480 else 481 Diag(MissingNilLoc, diag::warn_missing_sentinel) 482 << int(calleeType) 483 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 484 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 485 } 486 487 SourceRange Sema::getExprRange(Expr *E) const { 488 return E ? E->getSourceRange() : SourceRange(); 489 } 490 491 //===----------------------------------------------------------------------===// 492 // Standard Promotions and Conversions 493 //===----------------------------------------------------------------------===// 494 495 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 496 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 497 // Handle any placeholder expressions which made it here. 498 if (E->getType()->isPlaceholderType()) { 499 ExprResult result = CheckPlaceholderExpr(E); 500 if (result.isInvalid()) return ExprError(); 501 E = result.get(); 502 } 503 504 QualType Ty = E->getType(); 505 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 506 507 if (Ty->isFunctionType()) { 508 // If we are here, we are not calling a function but taking 509 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 510 if (getLangOpts().OpenCL) { 511 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 512 return ExprError(); 513 } 514 E = ImpCastExprToType(E, Context.getPointerType(Ty), 515 CK_FunctionToPointerDecay).get(); 516 } else if (Ty->isArrayType()) { 517 // In C90 mode, arrays only promote to pointers if the array expression is 518 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 519 // type 'array of type' is converted to an expression that has type 'pointer 520 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 521 // that has type 'array of type' ...". The relevant change is "an lvalue" 522 // (C90) to "an expression" (C99). 523 // 524 // C++ 4.2p1: 525 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 526 // T" can be converted to an rvalue of type "pointer to T". 527 // 528 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 529 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 530 CK_ArrayToPointerDecay).get(); 531 } 532 return E; 533 } 534 535 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 536 // Check to see if we are dereferencing a null pointer. If so, 537 // and if not volatile-qualified, this is undefined behavior that the 538 // optimizer will delete, so warn about it. People sometimes try to use this 539 // to get a deterministic trap and are surprised by clang's behavior. This 540 // only handles the pattern "*null", which is a very syntactic check. 541 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 542 if (UO->getOpcode() == UO_Deref && 543 UO->getSubExpr()->IgnoreParenCasts()-> 544 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 545 !UO->getType().isVolatileQualified()) { 546 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 547 S.PDiag(diag::warn_indirection_through_null) 548 << UO->getSubExpr()->getSourceRange()); 549 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 550 S.PDiag(diag::note_indirection_through_null)); 551 } 552 } 553 554 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 555 SourceLocation AssignLoc, 556 const Expr* RHS) { 557 const ObjCIvarDecl *IV = OIRE->getDecl(); 558 if (!IV) 559 return; 560 561 DeclarationName MemberName = IV->getDeclName(); 562 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 563 if (!Member || !Member->isStr("isa")) 564 return; 565 566 const Expr *Base = OIRE->getBase(); 567 QualType BaseType = Base->getType(); 568 if (OIRE->isArrow()) 569 BaseType = BaseType->getPointeeType(); 570 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 571 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 572 ObjCInterfaceDecl *ClassDeclared = nullptr; 573 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 574 if (!ClassDeclared->getSuperClass() 575 && (*ClassDeclared->ivar_begin()) == IV) { 576 if (RHS) { 577 NamedDecl *ObjectSetClass = 578 S.LookupSingleName(S.TUScope, 579 &S.Context.Idents.get("object_setClass"), 580 SourceLocation(), S.LookupOrdinaryName); 581 if (ObjectSetClass) { 582 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 583 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 584 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 585 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 586 AssignLoc), ",") << 587 FixItHint::CreateInsertion(RHSLocEnd, ")"); 588 } 589 else 590 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 591 } else { 592 NamedDecl *ObjectGetClass = 593 S.LookupSingleName(S.TUScope, 594 &S.Context.Idents.get("object_getClass"), 595 SourceLocation(), S.LookupOrdinaryName); 596 if (ObjectGetClass) 597 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 598 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 599 FixItHint::CreateReplacement( 600 SourceRange(OIRE->getOpLoc(), 601 OIRE->getLocEnd()), ")"); 602 else 603 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 604 } 605 S.Diag(IV->getLocation(), diag::note_ivar_decl); 606 } 607 } 608 } 609 610 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 611 // Handle any placeholder expressions which made it here. 612 if (E->getType()->isPlaceholderType()) { 613 ExprResult result = CheckPlaceholderExpr(E); 614 if (result.isInvalid()) return ExprError(); 615 E = result.get(); 616 } 617 618 // C++ [conv.lval]p1: 619 // A glvalue of a non-function, non-array type T can be 620 // converted to a prvalue. 621 if (!E->isGLValue()) return E; 622 623 QualType T = E->getType(); 624 assert(!T.isNull() && "r-value conversion on typeless expression?"); 625 626 // We don't want to throw lvalue-to-rvalue casts on top of 627 // expressions of certain types in C++. 628 if (getLangOpts().CPlusPlus && 629 (E->getType() == Context.OverloadTy || 630 T->isDependentType() || 631 T->isRecordType())) 632 return E; 633 634 // The C standard is actually really unclear on this point, and 635 // DR106 tells us what the result should be but not why. It's 636 // generally best to say that void types just doesn't undergo 637 // lvalue-to-rvalue at all. Note that expressions of unqualified 638 // 'void' type are never l-values, but qualified void can be. 639 if (T->isVoidType()) 640 return E; 641 642 // OpenCL usually rejects direct accesses to values of 'half' type. 643 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 644 T->isHalfType()) { 645 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 646 << 0 << T; 647 return ExprError(); 648 } 649 650 CheckForNullPointerDereference(*this, E); 651 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 652 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 653 &Context.Idents.get("object_getClass"), 654 SourceLocation(), LookupOrdinaryName); 655 if (ObjectGetClass) 656 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 657 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 658 FixItHint::CreateReplacement( 659 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 660 else 661 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 662 } 663 else if (const ObjCIvarRefExpr *OIRE = 664 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 665 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 666 667 // C++ [conv.lval]p1: 668 // [...] If T is a non-class type, the type of the prvalue is the 669 // cv-unqualified version of T. Otherwise, the type of the 670 // rvalue is T. 671 // 672 // C99 6.3.2.1p2: 673 // If the lvalue has qualified type, the value has the unqualified 674 // version of the type of the lvalue; otherwise, the value has the 675 // type of the lvalue. 676 if (T.hasQualifiers()) 677 T = T.getUnqualifiedType(); 678 679 UpdateMarkingForLValueToRValue(E); 680 681 // Loading a __weak object implicitly retains the value, so we need a cleanup to 682 // balance that. 683 if (getLangOpts().ObjCAutoRefCount && 684 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 685 ExprNeedsCleanups = true; 686 687 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 688 nullptr, VK_RValue); 689 690 // C11 6.3.2.1p2: 691 // ... if the lvalue has atomic type, the value has the non-atomic version 692 // of the type of the lvalue ... 693 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 694 T = Atomic->getValueType().getUnqualifiedType(); 695 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 696 nullptr, VK_RValue); 697 } 698 699 return Res; 700 } 701 702 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 703 ExprResult Res = DefaultFunctionArrayConversion(E); 704 if (Res.isInvalid()) 705 return ExprError(); 706 Res = DefaultLvalueConversion(Res.get()); 707 if (Res.isInvalid()) 708 return ExprError(); 709 return Res; 710 } 711 712 /// CallExprUnaryConversions - a special case of an unary conversion 713 /// performed on a function designator of a call expression. 714 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 715 QualType Ty = E->getType(); 716 ExprResult Res = E; 717 // Only do implicit cast for a function type, but not for a pointer 718 // to function type. 719 if (Ty->isFunctionType()) { 720 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 721 CK_FunctionToPointerDecay).get(); 722 if (Res.isInvalid()) 723 return ExprError(); 724 } 725 Res = DefaultLvalueConversion(Res.get()); 726 if (Res.isInvalid()) 727 return ExprError(); 728 return Res.get(); 729 } 730 731 /// UsualUnaryConversions - Performs various conversions that are common to most 732 /// operators (C99 6.3). The conversions of array and function types are 733 /// sometimes suppressed. For example, the array->pointer conversion doesn't 734 /// apply if the array is an argument to the sizeof or address (&) operators. 735 /// In these instances, this routine should *not* be called. 736 ExprResult Sema::UsualUnaryConversions(Expr *E) { 737 // First, convert to an r-value. 738 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 739 if (Res.isInvalid()) 740 return ExprError(); 741 E = Res.get(); 742 743 QualType Ty = E->getType(); 744 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 745 746 // Half FP have to be promoted to float unless it is natively supported 747 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 748 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 749 750 // Try to perform integral promotions if the object has a theoretically 751 // promotable type. 752 if (Ty->isIntegralOrUnscopedEnumerationType()) { 753 // C99 6.3.1.1p2: 754 // 755 // The following may be used in an expression wherever an int or 756 // unsigned int may be used: 757 // - an object or expression with an integer type whose integer 758 // conversion rank is less than or equal to the rank of int 759 // and unsigned int. 760 // - A bit-field of type _Bool, int, signed int, or unsigned int. 761 // 762 // If an int can represent all values of the original type, the 763 // value is converted to an int; otherwise, it is converted to an 764 // unsigned int. These are called the integer promotions. All 765 // other types are unchanged by the integer promotions. 766 767 QualType PTy = Context.isPromotableBitField(E); 768 if (!PTy.isNull()) { 769 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 770 return E; 771 } 772 if (Ty->isPromotableIntegerType()) { 773 QualType PT = Context.getPromotedIntegerType(Ty); 774 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 775 return E; 776 } 777 } 778 return E; 779 } 780 781 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 782 /// do not have a prototype. Arguments that have type float or __fp16 783 /// are promoted to double. All other argument types are converted by 784 /// UsualUnaryConversions(). 785 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 786 QualType Ty = E->getType(); 787 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 788 789 ExprResult Res = UsualUnaryConversions(E); 790 if (Res.isInvalid()) 791 return ExprError(); 792 E = Res.get(); 793 794 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 795 // double. 796 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 797 if (BTy && (BTy->getKind() == BuiltinType::Half || 798 BTy->getKind() == BuiltinType::Float)) 799 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 800 801 // C++ performs lvalue-to-rvalue conversion as a default argument 802 // promotion, even on class types, but note: 803 // C++11 [conv.lval]p2: 804 // When an lvalue-to-rvalue conversion occurs in an unevaluated 805 // operand or a subexpression thereof the value contained in the 806 // referenced object is not accessed. Otherwise, if the glvalue 807 // has a class type, the conversion copy-initializes a temporary 808 // of type T from the glvalue and the result of the conversion 809 // is a prvalue for the temporary. 810 // FIXME: add some way to gate this entire thing for correctness in 811 // potentially potentially evaluated contexts. 812 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 813 ExprResult Temp = PerformCopyInitialization( 814 InitializedEntity::InitializeTemporary(E->getType()), 815 E->getExprLoc(), E); 816 if (Temp.isInvalid()) 817 return ExprError(); 818 E = Temp.get(); 819 } 820 821 return E; 822 } 823 824 /// Determine the degree of POD-ness for an expression. 825 /// Incomplete types are considered POD, since this check can be performed 826 /// when we're in an unevaluated context. 827 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 828 if (Ty->isIncompleteType()) { 829 // C++11 [expr.call]p7: 830 // After these conversions, if the argument does not have arithmetic, 831 // enumeration, pointer, pointer to member, or class type, the program 832 // is ill-formed. 833 // 834 // Since we've already performed array-to-pointer and function-to-pointer 835 // decay, the only such type in C++ is cv void. This also handles 836 // initializer lists as variadic arguments. 837 if (Ty->isVoidType()) 838 return VAK_Invalid; 839 840 if (Ty->isObjCObjectType()) 841 return VAK_Invalid; 842 return VAK_Valid; 843 } 844 845 if (Ty.isCXX98PODType(Context)) 846 return VAK_Valid; 847 848 // C++11 [expr.call]p7: 849 // Passing a potentially-evaluated argument of class type (Clause 9) 850 // having a non-trivial copy constructor, a non-trivial move constructor, 851 // or a non-trivial destructor, with no corresponding parameter, 852 // is conditionally-supported with implementation-defined semantics. 853 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 854 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 855 if (!Record->hasNonTrivialCopyConstructor() && 856 !Record->hasNonTrivialMoveConstructor() && 857 !Record->hasNonTrivialDestructor()) 858 return VAK_ValidInCXX11; 859 860 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 861 return VAK_Valid; 862 863 if (Ty->isObjCObjectType()) 864 return VAK_Invalid; 865 866 if (getLangOpts().MSVCCompat) 867 return VAK_MSVCUndefined; 868 869 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 870 // permitted to reject them. We should consider doing so. 871 return VAK_Undefined; 872 } 873 874 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 875 // Don't allow one to pass an Objective-C interface to a vararg. 876 const QualType &Ty = E->getType(); 877 VarArgKind VAK = isValidVarArgType(Ty); 878 879 // Complain about passing non-POD types through varargs. 880 switch (VAK) { 881 case VAK_ValidInCXX11: 882 DiagRuntimeBehavior( 883 E->getLocStart(), nullptr, 884 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 885 << Ty << CT); 886 // Fall through. 887 case VAK_Valid: 888 if (Ty->isRecordType()) { 889 // This is unlikely to be what the user intended. If the class has a 890 // 'c_str' member function, the user probably meant to call that. 891 DiagRuntimeBehavior(E->getLocStart(), nullptr, 892 PDiag(diag::warn_pass_class_arg_to_vararg) 893 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 894 } 895 break; 896 897 case VAK_Undefined: 898 case VAK_MSVCUndefined: 899 DiagRuntimeBehavior( 900 E->getLocStart(), nullptr, 901 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 902 << getLangOpts().CPlusPlus11 << Ty << CT); 903 break; 904 905 case VAK_Invalid: 906 if (Ty->isObjCObjectType()) 907 DiagRuntimeBehavior( 908 E->getLocStart(), nullptr, 909 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 910 << Ty << CT); 911 else 912 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 913 << isa<InitListExpr>(E) << Ty << CT; 914 break; 915 } 916 } 917 918 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 919 /// will create a trap if the resulting type is not a POD type. 920 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 921 FunctionDecl *FDecl) { 922 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 923 // Strip the unbridged-cast placeholder expression off, if applicable. 924 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 925 (CT == VariadicMethod || 926 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 927 E = stripARCUnbridgedCast(E); 928 929 // Otherwise, do normal placeholder checking. 930 } else { 931 ExprResult ExprRes = CheckPlaceholderExpr(E); 932 if (ExprRes.isInvalid()) 933 return ExprError(); 934 E = ExprRes.get(); 935 } 936 } 937 938 ExprResult ExprRes = DefaultArgumentPromotion(E); 939 if (ExprRes.isInvalid()) 940 return ExprError(); 941 E = ExprRes.get(); 942 943 // Diagnostics regarding non-POD argument types are 944 // emitted along with format string checking in Sema::CheckFunctionCall(). 945 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 946 // Turn this into a trap. 947 CXXScopeSpec SS; 948 SourceLocation TemplateKWLoc; 949 UnqualifiedId Name; 950 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 951 E->getLocStart()); 952 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 953 Name, true, false); 954 if (TrapFn.isInvalid()) 955 return ExprError(); 956 957 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 958 E->getLocStart(), None, 959 E->getLocEnd()); 960 if (Call.isInvalid()) 961 return ExprError(); 962 963 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 964 Call.get(), E); 965 if (Comma.isInvalid()) 966 return ExprError(); 967 return Comma.get(); 968 } 969 970 if (!getLangOpts().CPlusPlus && 971 RequireCompleteType(E->getExprLoc(), E->getType(), 972 diag::err_call_incomplete_argument)) 973 return ExprError(); 974 975 return E; 976 } 977 978 /// \brief Converts an integer to complex float type. Helper function of 979 /// UsualArithmeticConversions() 980 /// 981 /// \return false if the integer expression is an integer type and is 982 /// successfully converted to the complex type. 983 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 984 ExprResult &ComplexExpr, 985 QualType IntTy, 986 QualType ComplexTy, 987 bool SkipCast) { 988 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 989 if (SkipCast) return false; 990 if (IntTy->isIntegerType()) { 991 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 992 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 993 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 994 CK_FloatingRealToComplex); 995 } else { 996 assert(IntTy->isComplexIntegerType()); 997 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 998 CK_IntegralComplexToFloatingComplex); 999 } 1000 return false; 1001 } 1002 1003 /// \brief Handle arithmetic conversion with complex types. Helper function of 1004 /// UsualArithmeticConversions() 1005 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1006 ExprResult &RHS, QualType LHSType, 1007 QualType RHSType, 1008 bool IsCompAssign) { 1009 // if we have an integer operand, the result is the complex type. 1010 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1011 /*skipCast*/false)) 1012 return LHSType; 1013 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1014 /*skipCast*/IsCompAssign)) 1015 return RHSType; 1016 1017 // This handles complex/complex, complex/float, or float/complex. 1018 // When both operands are complex, the shorter operand is converted to the 1019 // type of the longer, and that is the type of the result. This corresponds 1020 // to what is done when combining two real floating-point operands. 1021 // The fun begins when size promotion occur across type domains. 1022 // From H&S 6.3.4: When one operand is complex and the other is a real 1023 // floating-point type, the less precise type is converted, within it's 1024 // real or complex domain, to the precision of the other type. For example, 1025 // when combining a "long double" with a "double _Complex", the 1026 // "double _Complex" is promoted to "long double _Complex". 1027 1028 // Compute the rank of the two types, regardless of whether they are complex. 1029 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1030 1031 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1032 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1033 QualType LHSElementType = 1034 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1035 QualType RHSElementType = 1036 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1037 1038 QualType ResultType = S.Context.getComplexType(LHSElementType); 1039 if (Order < 0) { 1040 // Promote the precision of the LHS if not an assignment. 1041 ResultType = S.Context.getComplexType(RHSElementType); 1042 if (!IsCompAssign) { 1043 if (LHSComplexType) 1044 LHS = 1045 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1046 else 1047 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1048 } 1049 } else if (Order > 0) { 1050 // Promote the precision of the RHS. 1051 if (RHSComplexType) 1052 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1053 else 1054 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1055 } 1056 return ResultType; 1057 } 1058 1059 /// \brief Hande arithmetic conversion from integer to float. Helper function 1060 /// of UsualArithmeticConversions() 1061 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1062 ExprResult &IntExpr, 1063 QualType FloatTy, QualType IntTy, 1064 bool ConvertFloat, bool ConvertInt) { 1065 if (IntTy->isIntegerType()) { 1066 if (ConvertInt) 1067 // Convert intExpr to the lhs floating point type. 1068 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1069 CK_IntegralToFloating); 1070 return FloatTy; 1071 } 1072 1073 // Convert both sides to the appropriate complex float. 1074 assert(IntTy->isComplexIntegerType()); 1075 QualType result = S.Context.getComplexType(FloatTy); 1076 1077 // _Complex int -> _Complex float 1078 if (ConvertInt) 1079 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1080 CK_IntegralComplexToFloatingComplex); 1081 1082 // float -> _Complex float 1083 if (ConvertFloat) 1084 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1085 CK_FloatingRealToComplex); 1086 1087 return result; 1088 } 1089 1090 /// \brief Handle arithmethic conversion with floating point types. Helper 1091 /// function of UsualArithmeticConversions() 1092 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1093 ExprResult &RHS, QualType LHSType, 1094 QualType RHSType, bool IsCompAssign) { 1095 bool LHSFloat = LHSType->isRealFloatingType(); 1096 bool RHSFloat = RHSType->isRealFloatingType(); 1097 1098 // If we have two real floating types, convert the smaller operand 1099 // to the bigger result. 1100 if (LHSFloat && RHSFloat) { 1101 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1102 if (order > 0) { 1103 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1104 return LHSType; 1105 } 1106 1107 assert(order < 0 && "illegal float comparison"); 1108 if (!IsCompAssign) 1109 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1110 return RHSType; 1111 } 1112 1113 if (LHSFloat) 1114 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1115 /*convertFloat=*/!IsCompAssign, 1116 /*convertInt=*/ true); 1117 assert(RHSFloat); 1118 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1119 /*convertInt=*/ true, 1120 /*convertFloat=*/!IsCompAssign); 1121 } 1122 1123 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1124 1125 namespace { 1126 /// These helper callbacks are placed in an anonymous namespace to 1127 /// permit their use as function template parameters. 1128 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1129 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1130 } 1131 1132 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1133 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1134 CK_IntegralComplexCast); 1135 } 1136 } 1137 1138 /// \brief Handle integer arithmetic conversions. Helper function of 1139 /// UsualArithmeticConversions() 1140 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1141 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1142 ExprResult &RHS, QualType LHSType, 1143 QualType RHSType, bool IsCompAssign) { 1144 // The rules for this case are in C99 6.3.1.8 1145 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1146 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1147 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1148 if (LHSSigned == RHSSigned) { 1149 // Same signedness; use the higher-ranked type 1150 if (order >= 0) { 1151 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1152 return LHSType; 1153 } else if (!IsCompAssign) 1154 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1155 return RHSType; 1156 } else if (order != (LHSSigned ? 1 : -1)) { 1157 // The unsigned type has greater than or equal rank to the 1158 // signed type, so use the unsigned type 1159 if (RHSSigned) { 1160 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1161 return LHSType; 1162 } else if (!IsCompAssign) 1163 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1164 return RHSType; 1165 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1166 // The two types are different widths; if we are here, that 1167 // means the signed type is larger than the unsigned type, so 1168 // use the signed type. 1169 if (LHSSigned) { 1170 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1171 return LHSType; 1172 } else if (!IsCompAssign) 1173 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1174 return RHSType; 1175 } else { 1176 // The signed type is higher-ranked than the unsigned type, 1177 // but isn't actually any bigger (like unsigned int and long 1178 // on most 32-bit systems). Use the unsigned type corresponding 1179 // to the signed type. 1180 QualType result = 1181 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1182 RHS = (*doRHSCast)(S, RHS.get(), result); 1183 if (!IsCompAssign) 1184 LHS = (*doLHSCast)(S, LHS.get(), result); 1185 return result; 1186 } 1187 } 1188 1189 /// \brief Handle conversions with GCC complex int extension. Helper function 1190 /// of UsualArithmeticConversions() 1191 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1192 ExprResult &RHS, QualType LHSType, 1193 QualType RHSType, 1194 bool IsCompAssign) { 1195 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1196 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1197 1198 if (LHSComplexInt && RHSComplexInt) { 1199 QualType LHSEltType = LHSComplexInt->getElementType(); 1200 QualType RHSEltType = RHSComplexInt->getElementType(); 1201 QualType ScalarType = 1202 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1203 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1204 1205 return S.Context.getComplexType(ScalarType); 1206 } 1207 1208 if (LHSComplexInt) { 1209 QualType LHSEltType = LHSComplexInt->getElementType(); 1210 QualType ScalarType = 1211 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1212 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1213 QualType ComplexType = S.Context.getComplexType(ScalarType); 1214 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1215 CK_IntegralRealToComplex); 1216 1217 return ComplexType; 1218 } 1219 1220 assert(RHSComplexInt); 1221 1222 QualType RHSEltType = RHSComplexInt->getElementType(); 1223 QualType ScalarType = 1224 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1225 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1226 QualType ComplexType = S.Context.getComplexType(ScalarType); 1227 1228 if (!IsCompAssign) 1229 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1230 CK_IntegralRealToComplex); 1231 return ComplexType; 1232 } 1233 1234 /// UsualArithmeticConversions - Performs various conversions that are common to 1235 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1236 /// routine returns the first non-arithmetic type found. The client is 1237 /// responsible for emitting appropriate error diagnostics. 1238 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1239 bool IsCompAssign) { 1240 if (!IsCompAssign) { 1241 LHS = UsualUnaryConversions(LHS.get()); 1242 if (LHS.isInvalid()) 1243 return QualType(); 1244 } 1245 1246 RHS = UsualUnaryConversions(RHS.get()); 1247 if (RHS.isInvalid()) 1248 return QualType(); 1249 1250 // For conversion purposes, we ignore any qualifiers. 1251 // For example, "const float" and "float" are equivalent. 1252 QualType LHSType = 1253 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1254 QualType RHSType = 1255 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1256 1257 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1258 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1259 LHSType = AtomicLHS->getValueType(); 1260 1261 // If both types are identical, no conversion is needed. 1262 if (LHSType == RHSType) 1263 return LHSType; 1264 1265 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1266 // The caller can deal with this (e.g. pointer + int). 1267 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1268 return QualType(); 1269 1270 // Apply unary and bitfield promotions to the LHS's type. 1271 QualType LHSUnpromotedType = LHSType; 1272 if (LHSType->isPromotableIntegerType()) 1273 LHSType = Context.getPromotedIntegerType(LHSType); 1274 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1275 if (!LHSBitfieldPromoteTy.isNull()) 1276 LHSType = LHSBitfieldPromoteTy; 1277 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1278 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1279 1280 // If both types are identical, no conversion is needed. 1281 if (LHSType == RHSType) 1282 return LHSType; 1283 1284 // At this point, we have two different arithmetic types. 1285 1286 // Handle complex types first (C99 6.3.1.8p1). 1287 if (LHSType->isComplexType() || RHSType->isComplexType()) 1288 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1289 IsCompAssign); 1290 1291 // Now handle "real" floating types (i.e. float, double, long double). 1292 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1293 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1294 IsCompAssign); 1295 1296 // Handle GCC complex int extension. 1297 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1298 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1299 IsCompAssign); 1300 1301 // Finally, we have two differing integer types. 1302 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1303 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1304 } 1305 1306 1307 //===----------------------------------------------------------------------===// 1308 // Semantic Analysis for various Expression Types 1309 //===----------------------------------------------------------------------===// 1310 1311 1312 ExprResult 1313 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1314 SourceLocation DefaultLoc, 1315 SourceLocation RParenLoc, 1316 Expr *ControllingExpr, 1317 ArrayRef<ParsedType> ArgTypes, 1318 ArrayRef<Expr *> ArgExprs) { 1319 unsigned NumAssocs = ArgTypes.size(); 1320 assert(NumAssocs == ArgExprs.size()); 1321 1322 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1323 for (unsigned i = 0; i < NumAssocs; ++i) { 1324 if (ArgTypes[i]) 1325 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1326 else 1327 Types[i] = nullptr; 1328 } 1329 1330 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1331 ControllingExpr, 1332 llvm::makeArrayRef(Types, NumAssocs), 1333 ArgExprs); 1334 delete [] Types; 1335 return ER; 1336 } 1337 1338 ExprResult 1339 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1340 SourceLocation DefaultLoc, 1341 SourceLocation RParenLoc, 1342 Expr *ControllingExpr, 1343 ArrayRef<TypeSourceInfo *> Types, 1344 ArrayRef<Expr *> Exprs) { 1345 unsigned NumAssocs = Types.size(); 1346 assert(NumAssocs == Exprs.size()); 1347 if (ControllingExpr->getType()->isPlaceholderType()) { 1348 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1349 if (result.isInvalid()) return ExprError(); 1350 ControllingExpr = result.get(); 1351 } 1352 1353 // The controlling expression is an unevaluated operand, so side effects are 1354 // likely unintended. 1355 if (ActiveTemplateInstantiations.empty() && 1356 ControllingExpr->HasSideEffects(Context, false)) 1357 Diag(ControllingExpr->getExprLoc(), 1358 diag::warn_side_effects_unevaluated_context); 1359 1360 bool TypeErrorFound = false, 1361 IsResultDependent = ControllingExpr->isTypeDependent(), 1362 ContainsUnexpandedParameterPack 1363 = ControllingExpr->containsUnexpandedParameterPack(); 1364 1365 for (unsigned i = 0; i < NumAssocs; ++i) { 1366 if (Exprs[i]->containsUnexpandedParameterPack()) 1367 ContainsUnexpandedParameterPack = true; 1368 1369 if (Types[i]) { 1370 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1371 ContainsUnexpandedParameterPack = true; 1372 1373 if (Types[i]->getType()->isDependentType()) { 1374 IsResultDependent = true; 1375 } else { 1376 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1377 // complete object type other than a variably modified type." 1378 unsigned D = 0; 1379 if (Types[i]->getType()->isIncompleteType()) 1380 D = diag::err_assoc_type_incomplete; 1381 else if (!Types[i]->getType()->isObjectType()) 1382 D = diag::err_assoc_type_nonobject; 1383 else if (Types[i]->getType()->isVariablyModifiedType()) 1384 D = diag::err_assoc_type_variably_modified; 1385 1386 if (D != 0) { 1387 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1388 << Types[i]->getTypeLoc().getSourceRange() 1389 << Types[i]->getType(); 1390 TypeErrorFound = true; 1391 } 1392 1393 // C11 6.5.1.1p2 "No two generic associations in the same generic 1394 // selection shall specify compatible types." 1395 for (unsigned j = i+1; j < NumAssocs; ++j) 1396 if (Types[j] && !Types[j]->getType()->isDependentType() && 1397 Context.typesAreCompatible(Types[i]->getType(), 1398 Types[j]->getType())) { 1399 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1400 diag::err_assoc_compatible_types) 1401 << Types[j]->getTypeLoc().getSourceRange() 1402 << Types[j]->getType() 1403 << Types[i]->getType(); 1404 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1405 diag::note_compat_assoc) 1406 << Types[i]->getTypeLoc().getSourceRange() 1407 << Types[i]->getType(); 1408 TypeErrorFound = true; 1409 } 1410 } 1411 } 1412 } 1413 if (TypeErrorFound) 1414 return ExprError(); 1415 1416 // If we determined that the generic selection is result-dependent, don't 1417 // try to compute the result expression. 1418 if (IsResultDependent) 1419 return new (Context) GenericSelectionExpr( 1420 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1421 ContainsUnexpandedParameterPack); 1422 1423 SmallVector<unsigned, 1> CompatIndices; 1424 unsigned DefaultIndex = -1U; 1425 for (unsigned i = 0; i < NumAssocs; ++i) { 1426 if (!Types[i]) 1427 DefaultIndex = i; 1428 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1429 Types[i]->getType())) 1430 CompatIndices.push_back(i); 1431 } 1432 1433 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1434 // type compatible with at most one of the types named in its generic 1435 // association list." 1436 if (CompatIndices.size() > 1) { 1437 // We strip parens here because the controlling expression is typically 1438 // parenthesized in macro definitions. 1439 ControllingExpr = ControllingExpr->IgnoreParens(); 1440 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1441 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1442 << (unsigned) CompatIndices.size(); 1443 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1444 E = CompatIndices.end(); I != E; ++I) { 1445 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1446 diag::note_compat_assoc) 1447 << Types[*I]->getTypeLoc().getSourceRange() 1448 << Types[*I]->getType(); 1449 } 1450 return ExprError(); 1451 } 1452 1453 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1454 // its controlling expression shall have type compatible with exactly one of 1455 // the types named in its generic association list." 1456 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1457 // We strip parens here because the controlling expression is typically 1458 // parenthesized in macro definitions. 1459 ControllingExpr = ControllingExpr->IgnoreParens(); 1460 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1461 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1462 return ExprError(); 1463 } 1464 1465 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1466 // type name that is compatible with the type of the controlling expression, 1467 // then the result expression of the generic selection is the expression 1468 // in that generic association. Otherwise, the result expression of the 1469 // generic selection is the expression in the default generic association." 1470 unsigned ResultIndex = 1471 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1472 1473 return new (Context) GenericSelectionExpr( 1474 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1475 ContainsUnexpandedParameterPack, ResultIndex); 1476 } 1477 1478 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1479 /// location of the token and the offset of the ud-suffix within it. 1480 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1481 unsigned Offset) { 1482 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1483 S.getLangOpts()); 1484 } 1485 1486 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1487 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1488 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1489 IdentifierInfo *UDSuffix, 1490 SourceLocation UDSuffixLoc, 1491 ArrayRef<Expr*> Args, 1492 SourceLocation LitEndLoc) { 1493 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1494 1495 QualType ArgTy[2]; 1496 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1497 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1498 if (ArgTy[ArgIdx]->isArrayType()) 1499 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1500 } 1501 1502 DeclarationName OpName = 1503 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1504 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1505 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1506 1507 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1508 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1509 /*AllowRaw*/false, /*AllowTemplate*/false, 1510 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1511 return ExprError(); 1512 1513 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1514 } 1515 1516 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1517 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1518 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1519 /// multiple tokens. However, the common case is that StringToks points to one 1520 /// string. 1521 /// 1522 ExprResult 1523 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1524 assert(!StringToks.empty() && "Must have at least one string!"); 1525 1526 StringLiteralParser Literal(StringToks, PP); 1527 if (Literal.hadError) 1528 return ExprError(); 1529 1530 SmallVector<SourceLocation, 4> StringTokLocs; 1531 for (unsigned i = 0; i != StringToks.size(); ++i) 1532 StringTokLocs.push_back(StringToks[i].getLocation()); 1533 1534 QualType CharTy = Context.CharTy; 1535 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1536 if (Literal.isWide()) { 1537 CharTy = Context.getWideCharType(); 1538 Kind = StringLiteral::Wide; 1539 } else if (Literal.isUTF8()) { 1540 Kind = StringLiteral::UTF8; 1541 } else if (Literal.isUTF16()) { 1542 CharTy = Context.Char16Ty; 1543 Kind = StringLiteral::UTF16; 1544 } else if (Literal.isUTF32()) { 1545 CharTy = Context.Char32Ty; 1546 Kind = StringLiteral::UTF32; 1547 } else if (Literal.isPascal()) { 1548 CharTy = Context.UnsignedCharTy; 1549 } 1550 1551 QualType CharTyConst = CharTy; 1552 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1553 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1554 CharTyConst.addConst(); 1555 1556 // Get an array type for the string, according to C99 6.4.5. This includes 1557 // the nul terminator character as well as the string length for pascal 1558 // strings. 1559 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1560 llvm::APInt(32, Literal.GetNumStringChars()+1), 1561 ArrayType::Normal, 0); 1562 1563 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1564 if (getLangOpts().OpenCL) { 1565 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1566 } 1567 1568 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1569 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1570 Kind, Literal.Pascal, StrTy, 1571 &StringTokLocs[0], 1572 StringTokLocs.size()); 1573 if (Literal.getUDSuffix().empty()) 1574 return Lit; 1575 1576 // We're building a user-defined literal. 1577 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1578 SourceLocation UDSuffixLoc = 1579 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1580 Literal.getUDSuffixOffset()); 1581 1582 // Make sure we're allowed user-defined literals here. 1583 if (!UDLScope) 1584 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1585 1586 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1587 // operator "" X (str, len) 1588 QualType SizeType = Context.getSizeType(); 1589 1590 DeclarationName OpName = 1591 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1592 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1593 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1594 1595 QualType ArgTy[] = { 1596 Context.getArrayDecayedType(StrTy), SizeType 1597 }; 1598 1599 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1600 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1601 /*AllowRaw*/false, /*AllowTemplate*/false, 1602 /*AllowStringTemplate*/true)) { 1603 1604 case LOLR_Cooked: { 1605 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1606 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1607 StringTokLocs[0]); 1608 Expr *Args[] = { Lit, LenArg }; 1609 1610 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1611 } 1612 1613 case LOLR_StringTemplate: { 1614 TemplateArgumentListInfo ExplicitArgs; 1615 1616 unsigned CharBits = Context.getIntWidth(CharTy); 1617 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1618 llvm::APSInt Value(CharBits, CharIsUnsigned); 1619 1620 TemplateArgument TypeArg(CharTy); 1621 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1622 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1623 1624 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1625 Value = Lit->getCodeUnit(I); 1626 TemplateArgument Arg(Context, Value, CharTy); 1627 TemplateArgumentLocInfo ArgInfo; 1628 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1629 } 1630 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1631 &ExplicitArgs); 1632 } 1633 case LOLR_Raw: 1634 case LOLR_Template: 1635 llvm_unreachable("unexpected literal operator lookup result"); 1636 case LOLR_Error: 1637 return ExprError(); 1638 } 1639 llvm_unreachable("unexpected literal operator lookup result"); 1640 } 1641 1642 ExprResult 1643 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1644 SourceLocation Loc, 1645 const CXXScopeSpec *SS) { 1646 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1647 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1648 } 1649 1650 /// BuildDeclRefExpr - Build an expression that references a 1651 /// declaration that does not require a closure capture. 1652 ExprResult 1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1654 const DeclarationNameInfo &NameInfo, 1655 const CXXScopeSpec *SS, NamedDecl *FoundD, 1656 const TemplateArgumentListInfo *TemplateArgs) { 1657 if (getLangOpts().CUDA) 1658 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1659 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1660 if (CheckCUDATarget(Caller, Callee)) { 1661 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1662 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1663 << IdentifyCUDATarget(Caller); 1664 Diag(D->getLocation(), diag::note_previous_decl) 1665 << D->getIdentifier(); 1666 return ExprError(); 1667 } 1668 } 1669 1670 bool RefersToCapturedVariable = 1671 isa<VarDecl>(D) && 1672 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1673 1674 DeclRefExpr *E; 1675 if (isa<VarTemplateSpecializationDecl>(D)) { 1676 VarTemplateSpecializationDecl *VarSpec = 1677 cast<VarTemplateSpecializationDecl>(D); 1678 1679 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1680 : NestedNameSpecifierLoc(), 1681 VarSpec->getTemplateKeywordLoc(), D, 1682 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1683 FoundD, TemplateArgs); 1684 } else { 1685 assert(!TemplateArgs && "No template arguments for non-variable" 1686 " template specialization references"); 1687 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1688 : NestedNameSpecifierLoc(), 1689 SourceLocation(), D, RefersToCapturedVariable, 1690 NameInfo, Ty, VK, FoundD); 1691 } 1692 1693 MarkDeclRefReferenced(E); 1694 1695 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1696 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1697 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1698 recordUseOfEvaluatedWeak(E); 1699 1700 // Just in case we're building an illegal pointer-to-member. 1701 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1702 if (FD && FD->isBitField()) 1703 E->setObjectKind(OK_BitField); 1704 1705 return E; 1706 } 1707 1708 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1709 /// possibly a list of template arguments. 1710 /// 1711 /// If this produces template arguments, it is permitted to call 1712 /// DecomposeTemplateName. 1713 /// 1714 /// This actually loses a lot of source location information for 1715 /// non-standard name kinds; we should consider preserving that in 1716 /// some way. 1717 void 1718 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1719 TemplateArgumentListInfo &Buffer, 1720 DeclarationNameInfo &NameInfo, 1721 const TemplateArgumentListInfo *&TemplateArgs) { 1722 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1723 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1724 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1725 1726 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1727 Id.TemplateId->NumArgs); 1728 translateTemplateArguments(TemplateArgsPtr, Buffer); 1729 1730 TemplateName TName = Id.TemplateId->Template.get(); 1731 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1732 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1733 TemplateArgs = &Buffer; 1734 } else { 1735 NameInfo = GetNameFromUnqualifiedId(Id); 1736 TemplateArgs = nullptr; 1737 } 1738 } 1739 1740 static void emitEmptyLookupTypoDiagnostic( 1741 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1742 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1743 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1744 DeclContext *Ctx = 1745 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1746 if (!TC) { 1747 // Emit a special diagnostic for failed member lookups. 1748 // FIXME: computing the declaration context might fail here (?) 1749 if (Ctx) 1750 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1751 << SS.getRange(); 1752 else 1753 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1754 return; 1755 } 1756 1757 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1758 bool DroppedSpecifier = 1759 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1760 unsigned NoteID = 1761 (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl())) 1762 ? diag::note_implicit_param_decl 1763 : diag::note_previous_decl; 1764 if (!Ctx) 1765 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1766 SemaRef.PDiag(NoteID)); 1767 else 1768 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1769 << Typo << Ctx << DroppedSpecifier 1770 << SS.getRange(), 1771 SemaRef.PDiag(NoteID)); 1772 } 1773 1774 /// Diagnose an empty lookup. 1775 /// 1776 /// \return false if new lookup candidates were found 1777 bool 1778 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1779 std::unique_ptr<CorrectionCandidateCallback> CCC, 1780 TemplateArgumentListInfo *ExplicitTemplateArgs, 1781 ArrayRef<Expr *> Args, TypoExpr **Out) { 1782 DeclarationName Name = R.getLookupName(); 1783 1784 unsigned diagnostic = diag::err_undeclared_var_use; 1785 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1786 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1787 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1788 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1789 diagnostic = diag::err_undeclared_use; 1790 diagnostic_suggest = diag::err_undeclared_use_suggest; 1791 } 1792 1793 // If the original lookup was an unqualified lookup, fake an 1794 // unqualified lookup. This is useful when (for example) the 1795 // original lookup would not have found something because it was a 1796 // dependent name. 1797 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1798 ? CurContext : nullptr; 1799 while (DC) { 1800 if (isa<CXXRecordDecl>(DC)) { 1801 LookupQualifiedName(R, DC); 1802 1803 if (!R.empty()) { 1804 // Don't give errors about ambiguities in this lookup. 1805 R.suppressDiagnostics(); 1806 1807 // During a default argument instantiation the CurContext points 1808 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1809 // function parameter list, hence add an explicit check. 1810 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1811 ActiveTemplateInstantiations.back().Kind == 1812 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1813 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1814 bool isInstance = CurMethod && 1815 CurMethod->isInstance() && 1816 DC == CurMethod->getParent() && !isDefaultArgument; 1817 1818 1819 // Give a code modification hint to insert 'this->'. 1820 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1821 // Actually quite difficult! 1822 if (getLangOpts().MSVCCompat) 1823 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1824 if (isInstance) { 1825 Diag(R.getNameLoc(), diagnostic) << Name 1826 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1827 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1828 CallsUndergoingInstantiation.back()->getCallee()); 1829 1830 CXXMethodDecl *DepMethod; 1831 if (CurMethod->isDependentContext()) 1832 DepMethod = CurMethod; 1833 else if (CurMethod->getTemplatedKind() == 1834 FunctionDecl::TK_FunctionTemplateSpecialization) 1835 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1836 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1837 else 1838 DepMethod = cast<CXXMethodDecl>( 1839 CurMethod->getInstantiatedFromMemberFunction()); 1840 assert(DepMethod && "No template pattern found"); 1841 1842 QualType DepThisType = DepMethod->getThisType(Context); 1843 CheckCXXThisCapture(R.getNameLoc()); 1844 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1845 R.getNameLoc(), DepThisType, false); 1846 TemplateArgumentListInfo TList; 1847 if (ULE->hasExplicitTemplateArgs()) 1848 ULE->copyTemplateArgumentsInto(TList); 1849 1850 CXXScopeSpec SS; 1851 SS.Adopt(ULE->getQualifierLoc()); 1852 CXXDependentScopeMemberExpr *DepExpr = 1853 CXXDependentScopeMemberExpr::Create( 1854 Context, DepThis, DepThisType, true, SourceLocation(), 1855 SS.getWithLocInContext(Context), 1856 ULE->getTemplateKeywordLoc(), nullptr, 1857 R.getLookupNameInfo(), 1858 ULE->hasExplicitTemplateArgs() ? &TList : nullptr); 1859 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1860 } else { 1861 Diag(R.getNameLoc(), diagnostic) << Name; 1862 } 1863 1864 // Do we really want to note all of these? 1865 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1866 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1867 1868 // Return true if we are inside a default argument instantiation 1869 // and the found name refers to an instance member function, otherwise 1870 // the function calling DiagnoseEmptyLookup will try to create an 1871 // implicit member call and this is wrong for default argument. 1872 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1873 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1874 return true; 1875 } 1876 1877 // Tell the callee to try to recover. 1878 return false; 1879 } 1880 1881 R.clear(); 1882 } 1883 1884 // In Microsoft mode, if we are performing lookup from within a friend 1885 // function definition declared at class scope then we must set 1886 // DC to the lexical parent to be able to search into the parent 1887 // class. 1888 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1889 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1890 DC->getLexicalParent()->isRecord()) 1891 DC = DC->getLexicalParent(); 1892 else 1893 DC = DC->getParent(); 1894 } 1895 1896 // We didn't find anything, so try to correct for a typo. 1897 TypoCorrection Corrected; 1898 if (S && Out) { 1899 SourceLocation TypoLoc = R.getNameLoc(); 1900 assert(!ExplicitTemplateArgs && 1901 "Diagnosing an empty lookup with explicit template args!"); 1902 *Out = CorrectTypoDelayed( 1903 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1904 [=](const TypoCorrection &TC) { 1905 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1906 diagnostic, diagnostic_suggest); 1907 }, 1908 nullptr, CTK_ErrorRecovery); 1909 if (*Out) 1910 return true; 1911 } else if (S && (Corrected = 1912 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1913 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1914 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1915 bool DroppedSpecifier = 1916 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1917 R.setLookupName(Corrected.getCorrection()); 1918 1919 bool AcceptableWithRecovery = false; 1920 bool AcceptableWithoutRecovery = false; 1921 NamedDecl *ND = Corrected.getCorrectionDecl(); 1922 if (ND) { 1923 if (Corrected.isOverloaded()) { 1924 OverloadCandidateSet OCS(R.getNameLoc(), 1925 OverloadCandidateSet::CSK_Normal); 1926 OverloadCandidateSet::iterator Best; 1927 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1928 CDEnd = Corrected.end(); 1929 CD != CDEnd; ++CD) { 1930 if (FunctionTemplateDecl *FTD = 1931 dyn_cast<FunctionTemplateDecl>(*CD)) 1932 AddTemplateOverloadCandidate( 1933 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1934 Args, OCS); 1935 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1936 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1937 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1938 Args, OCS); 1939 } 1940 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1941 case OR_Success: 1942 ND = Best->Function; 1943 Corrected.setCorrectionDecl(ND); 1944 break; 1945 default: 1946 // FIXME: Arbitrarily pick the first declaration for the note. 1947 Corrected.setCorrectionDecl(ND); 1948 break; 1949 } 1950 } 1951 R.addDecl(ND); 1952 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1953 CXXRecordDecl *Record = nullptr; 1954 if (Corrected.getCorrectionSpecifier()) { 1955 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1956 Record = Ty->getAsCXXRecordDecl(); 1957 } 1958 if (!Record) 1959 Record = cast<CXXRecordDecl>( 1960 ND->getDeclContext()->getRedeclContext()); 1961 R.setNamingClass(Record); 1962 } 1963 1964 AcceptableWithRecovery = 1965 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1966 // FIXME: If we ended up with a typo for a type name or 1967 // Objective-C class name, we're in trouble because the parser 1968 // is in the wrong place to recover. Suggest the typo 1969 // correction, but don't make it a fix-it since we're not going 1970 // to recover well anyway. 1971 AcceptableWithoutRecovery = 1972 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1973 } else { 1974 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1975 // because we aren't able to recover. 1976 AcceptableWithoutRecovery = true; 1977 } 1978 1979 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1980 unsigned NoteID = (Corrected.getCorrectionDecl() && 1981 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1982 ? diag::note_implicit_param_decl 1983 : diag::note_previous_decl; 1984 if (SS.isEmpty()) 1985 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1986 PDiag(NoteID), AcceptableWithRecovery); 1987 else 1988 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1989 << Name << computeDeclContext(SS, false) 1990 << DroppedSpecifier << SS.getRange(), 1991 PDiag(NoteID), AcceptableWithRecovery); 1992 1993 // Tell the callee whether to try to recover. 1994 return !AcceptableWithRecovery; 1995 } 1996 } 1997 R.clear(); 1998 1999 // Emit a special diagnostic for failed member lookups. 2000 // FIXME: computing the declaration context might fail here (?) 2001 if (!SS.isEmpty()) { 2002 Diag(R.getNameLoc(), diag::err_no_member) 2003 << Name << computeDeclContext(SS, false) 2004 << SS.getRange(); 2005 return true; 2006 } 2007 2008 // Give up, we can't recover. 2009 Diag(R.getNameLoc(), diagnostic) << Name; 2010 return true; 2011 } 2012 2013 /// In Microsoft mode, if we are inside a template class whose parent class has 2014 /// dependent base classes, and we can't resolve an unqualified identifier, then 2015 /// assume the identifier is a member of a dependent base class. We can only 2016 /// recover successfully in static methods, instance methods, and other contexts 2017 /// where 'this' is available. This doesn't precisely match MSVC's 2018 /// instantiation model, but it's close enough. 2019 static Expr * 2020 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2021 DeclarationNameInfo &NameInfo, 2022 SourceLocation TemplateKWLoc, 2023 const TemplateArgumentListInfo *TemplateArgs) { 2024 // Only try to recover from lookup into dependent bases in static methods or 2025 // contexts where 'this' is available. 2026 QualType ThisType = S.getCurrentThisType(); 2027 const CXXRecordDecl *RD = nullptr; 2028 if (!ThisType.isNull()) 2029 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2030 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2031 RD = MD->getParent(); 2032 if (!RD || !RD->hasAnyDependentBases()) 2033 return nullptr; 2034 2035 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2036 // is available, suggest inserting 'this->' as a fixit. 2037 SourceLocation Loc = NameInfo.getLoc(); 2038 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2039 DB << NameInfo.getName() << RD; 2040 2041 if (!ThisType.isNull()) { 2042 DB << FixItHint::CreateInsertion(Loc, "this->"); 2043 return CXXDependentScopeMemberExpr::Create( 2044 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2045 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2046 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2047 } 2048 2049 // Synthesize a fake NNS that points to the derived class. This will 2050 // perform name lookup during template instantiation. 2051 CXXScopeSpec SS; 2052 auto *NNS = 2053 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2054 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2055 return DependentScopeDeclRefExpr::Create( 2056 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2057 TemplateArgs); 2058 } 2059 2060 ExprResult 2061 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2062 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2063 bool HasTrailingLParen, bool IsAddressOfOperand, 2064 std::unique_ptr<CorrectionCandidateCallback> CCC, 2065 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2066 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2067 "cannot be direct & operand and have a trailing lparen"); 2068 if (SS.isInvalid()) 2069 return ExprError(); 2070 2071 TemplateArgumentListInfo TemplateArgsBuffer; 2072 2073 // Decompose the UnqualifiedId into the following data. 2074 DeclarationNameInfo NameInfo; 2075 const TemplateArgumentListInfo *TemplateArgs; 2076 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2077 2078 DeclarationName Name = NameInfo.getName(); 2079 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2080 SourceLocation NameLoc = NameInfo.getLoc(); 2081 2082 // C++ [temp.dep.expr]p3: 2083 // An id-expression is type-dependent if it contains: 2084 // -- an identifier that was declared with a dependent type, 2085 // (note: handled after lookup) 2086 // -- a template-id that is dependent, 2087 // (note: handled in BuildTemplateIdExpr) 2088 // -- a conversion-function-id that specifies a dependent type, 2089 // -- a nested-name-specifier that contains a class-name that 2090 // names a dependent type. 2091 // Determine whether this is a member of an unknown specialization; 2092 // we need to handle these differently. 2093 bool DependentID = false; 2094 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2095 Name.getCXXNameType()->isDependentType()) { 2096 DependentID = true; 2097 } else if (SS.isSet()) { 2098 if (DeclContext *DC = computeDeclContext(SS, false)) { 2099 if (RequireCompleteDeclContext(SS, DC)) 2100 return ExprError(); 2101 } else { 2102 DependentID = true; 2103 } 2104 } 2105 2106 if (DependentID) 2107 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2108 IsAddressOfOperand, TemplateArgs); 2109 2110 // Perform the required lookup. 2111 LookupResult R(*this, NameInfo, 2112 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2113 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2114 if (TemplateArgs) { 2115 // Lookup the template name again to correctly establish the context in 2116 // which it was found. This is really unfortunate as we already did the 2117 // lookup to determine that it was a template name in the first place. If 2118 // this becomes a performance hit, we can work harder to preserve those 2119 // results until we get here but it's likely not worth it. 2120 bool MemberOfUnknownSpecialization; 2121 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2122 MemberOfUnknownSpecialization); 2123 2124 if (MemberOfUnknownSpecialization || 2125 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2126 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2127 IsAddressOfOperand, TemplateArgs); 2128 } else { 2129 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2130 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2131 2132 // If the result might be in a dependent base class, this is a dependent 2133 // id-expression. 2134 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2135 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2136 IsAddressOfOperand, TemplateArgs); 2137 2138 // If this reference is in an Objective-C method, then we need to do 2139 // some special Objective-C lookup, too. 2140 if (IvarLookupFollowUp) { 2141 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2142 if (E.isInvalid()) 2143 return ExprError(); 2144 2145 if (Expr *Ex = E.getAs<Expr>()) 2146 return Ex; 2147 } 2148 } 2149 2150 if (R.isAmbiguous()) 2151 return ExprError(); 2152 2153 // This could be an implicitly declared function reference (legal in C90, 2154 // extension in C99, forbidden in C++). 2155 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2156 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2157 if (D) R.addDecl(D); 2158 } 2159 2160 // Determine whether this name might be a candidate for 2161 // argument-dependent lookup. 2162 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2163 2164 if (R.empty() && !ADL) { 2165 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2166 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2167 TemplateKWLoc, TemplateArgs)) 2168 return E; 2169 } 2170 2171 // Don't diagnose an empty lookup for inline assembly. 2172 if (IsInlineAsmIdentifier) 2173 return ExprError(); 2174 2175 // If this name wasn't predeclared and if this is not a function 2176 // call, diagnose the problem. 2177 TypoExpr *TE = nullptr; 2178 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2179 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2180 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2181 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2182 "Typo correction callback misconfigured"); 2183 if (CCC) { 2184 // Make sure the callback knows what the typo being diagnosed is. 2185 CCC->setTypoName(II); 2186 if (SS.isValid()) 2187 CCC->setTypoNNS(SS.getScopeRep()); 2188 } 2189 if (DiagnoseEmptyLookup(S, SS, R, 2190 CCC ? std::move(CCC) : std::move(DefaultValidator), 2191 nullptr, None, &TE)) { 2192 if (TE && KeywordReplacement) { 2193 auto &State = getTypoExprState(TE); 2194 auto BestTC = State.Consumer->getNextCorrection(); 2195 if (BestTC.isKeyword()) { 2196 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2197 if (State.DiagHandler) 2198 State.DiagHandler(BestTC); 2199 KeywordReplacement->startToken(); 2200 KeywordReplacement->setKind(II->getTokenID()); 2201 KeywordReplacement->setIdentifierInfo(II); 2202 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2203 // Clean up the state associated with the TypoExpr, since it has 2204 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2205 clearDelayedTypo(TE); 2206 // Signal that a correction to a keyword was performed by returning a 2207 // valid-but-null ExprResult. 2208 return (Expr*)nullptr; 2209 } 2210 State.Consumer->resetCorrectionStream(); 2211 } 2212 return TE ? TE : ExprError(); 2213 } 2214 2215 assert(!R.empty() && 2216 "DiagnoseEmptyLookup returned false but added no results"); 2217 2218 // If we found an Objective-C instance variable, let 2219 // LookupInObjCMethod build the appropriate expression to 2220 // reference the ivar. 2221 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2222 R.clear(); 2223 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2224 // In a hopelessly buggy code, Objective-C instance variable 2225 // lookup fails and no expression will be built to reference it. 2226 if (!E.isInvalid() && !E.get()) 2227 return ExprError(); 2228 return E; 2229 } 2230 } 2231 2232 // This is guaranteed from this point on. 2233 assert(!R.empty() || ADL); 2234 2235 // Check whether this might be a C++ implicit instance member access. 2236 // C++ [class.mfct.non-static]p3: 2237 // When an id-expression that is not part of a class member access 2238 // syntax and not used to form a pointer to member is used in the 2239 // body of a non-static member function of class X, if name lookup 2240 // resolves the name in the id-expression to a non-static non-type 2241 // member of some class C, the id-expression is transformed into a 2242 // class member access expression using (*this) as the 2243 // postfix-expression to the left of the . operator. 2244 // 2245 // But we don't actually need to do this for '&' operands if R 2246 // resolved to a function or overloaded function set, because the 2247 // expression is ill-formed if it actually works out to be a 2248 // non-static member function: 2249 // 2250 // C++ [expr.ref]p4: 2251 // Otherwise, if E1.E2 refers to a non-static member function. . . 2252 // [t]he expression can be used only as the left-hand operand of a 2253 // member function call. 2254 // 2255 // There are other safeguards against such uses, but it's important 2256 // to get this right here so that we don't end up making a 2257 // spuriously dependent expression if we're inside a dependent 2258 // instance method. 2259 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2260 bool MightBeImplicitMember; 2261 if (!IsAddressOfOperand) 2262 MightBeImplicitMember = true; 2263 else if (!SS.isEmpty()) 2264 MightBeImplicitMember = false; 2265 else if (R.isOverloadedResult()) 2266 MightBeImplicitMember = false; 2267 else if (R.isUnresolvableResult()) 2268 MightBeImplicitMember = true; 2269 else 2270 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2271 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2272 isa<MSPropertyDecl>(R.getFoundDecl()); 2273 2274 if (MightBeImplicitMember) 2275 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2276 R, TemplateArgs); 2277 } 2278 2279 if (TemplateArgs || TemplateKWLoc.isValid()) { 2280 2281 // In C++1y, if this is a variable template id, then check it 2282 // in BuildTemplateIdExpr(). 2283 // The single lookup result must be a variable template declaration. 2284 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2285 Id.TemplateId->Kind == TNK_Var_template) { 2286 assert(R.getAsSingle<VarTemplateDecl>() && 2287 "There should only be one declaration found."); 2288 } 2289 2290 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2291 } 2292 2293 return BuildDeclarationNameExpr(SS, R, ADL); 2294 } 2295 2296 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2297 /// declaration name, generally during template instantiation. 2298 /// There's a large number of things which don't need to be done along 2299 /// this path. 2300 ExprResult 2301 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2302 const DeclarationNameInfo &NameInfo, 2303 bool IsAddressOfOperand, 2304 TypeSourceInfo **RecoveryTSI) { 2305 DeclContext *DC = computeDeclContext(SS, false); 2306 if (!DC) 2307 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2308 NameInfo, /*TemplateArgs=*/nullptr); 2309 2310 if (RequireCompleteDeclContext(SS, DC)) 2311 return ExprError(); 2312 2313 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2314 LookupQualifiedName(R, DC); 2315 2316 if (R.isAmbiguous()) 2317 return ExprError(); 2318 2319 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2320 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2321 NameInfo, /*TemplateArgs=*/nullptr); 2322 2323 if (R.empty()) { 2324 Diag(NameInfo.getLoc(), diag::err_no_member) 2325 << NameInfo.getName() << DC << SS.getRange(); 2326 return ExprError(); 2327 } 2328 2329 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2330 // Diagnose a missing typename if this resolved unambiguously to a type in 2331 // a dependent context. If we can recover with a type, downgrade this to 2332 // a warning in Microsoft compatibility mode. 2333 unsigned DiagID = diag::err_typename_missing; 2334 if (RecoveryTSI && getLangOpts().MSVCCompat) 2335 DiagID = diag::ext_typename_missing; 2336 SourceLocation Loc = SS.getBeginLoc(); 2337 auto D = Diag(Loc, DiagID); 2338 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2339 << SourceRange(Loc, NameInfo.getEndLoc()); 2340 2341 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2342 // context. 2343 if (!RecoveryTSI) 2344 return ExprError(); 2345 2346 // Only issue the fixit if we're prepared to recover. 2347 D << FixItHint::CreateInsertion(Loc, "typename "); 2348 2349 // Recover by pretending this was an elaborated type. 2350 QualType Ty = Context.getTypeDeclType(TD); 2351 TypeLocBuilder TLB; 2352 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2353 2354 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2355 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2356 QTL.setElaboratedKeywordLoc(SourceLocation()); 2357 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2358 2359 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2360 2361 return ExprEmpty(); 2362 } 2363 2364 // Defend against this resolving to an implicit member access. We usually 2365 // won't get here if this might be a legitimate a class member (we end up in 2366 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2367 // a pointer-to-member or in an unevaluated context in C++11. 2368 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2369 return BuildPossibleImplicitMemberExpr(SS, 2370 /*TemplateKWLoc=*/SourceLocation(), 2371 R, /*TemplateArgs=*/nullptr); 2372 2373 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2374 } 2375 2376 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2377 /// detected that we're currently inside an ObjC method. Perform some 2378 /// additional lookup. 2379 /// 2380 /// Ideally, most of this would be done by lookup, but there's 2381 /// actually quite a lot of extra work involved. 2382 /// 2383 /// Returns a null sentinel to indicate trivial success. 2384 ExprResult 2385 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2386 IdentifierInfo *II, bool AllowBuiltinCreation) { 2387 SourceLocation Loc = Lookup.getNameLoc(); 2388 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2389 2390 // Check for error condition which is already reported. 2391 if (!CurMethod) 2392 return ExprError(); 2393 2394 // There are two cases to handle here. 1) scoped lookup could have failed, 2395 // in which case we should look for an ivar. 2) scoped lookup could have 2396 // found a decl, but that decl is outside the current instance method (i.e. 2397 // a global variable). In these two cases, we do a lookup for an ivar with 2398 // this name, if the lookup sucedes, we replace it our current decl. 2399 2400 // If we're in a class method, we don't normally want to look for 2401 // ivars. But if we don't find anything else, and there's an 2402 // ivar, that's an error. 2403 bool IsClassMethod = CurMethod->isClassMethod(); 2404 2405 bool LookForIvars; 2406 if (Lookup.empty()) 2407 LookForIvars = true; 2408 else if (IsClassMethod) 2409 LookForIvars = false; 2410 else 2411 LookForIvars = (Lookup.isSingleResult() && 2412 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2413 ObjCInterfaceDecl *IFace = nullptr; 2414 if (LookForIvars) { 2415 IFace = CurMethod->getClassInterface(); 2416 ObjCInterfaceDecl *ClassDeclared; 2417 ObjCIvarDecl *IV = nullptr; 2418 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2419 // Diagnose using an ivar in a class method. 2420 if (IsClassMethod) 2421 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2422 << IV->getDeclName()); 2423 2424 // If we're referencing an invalid decl, just return this as a silent 2425 // error node. The error diagnostic was already emitted on the decl. 2426 if (IV->isInvalidDecl()) 2427 return ExprError(); 2428 2429 // Check if referencing a field with __attribute__((deprecated)). 2430 if (DiagnoseUseOfDecl(IV, Loc)) 2431 return ExprError(); 2432 2433 // Diagnose the use of an ivar outside of the declaring class. 2434 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2435 !declaresSameEntity(ClassDeclared, IFace) && 2436 !getLangOpts().DebuggerSupport) 2437 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2438 2439 // FIXME: This should use a new expr for a direct reference, don't 2440 // turn this into Self->ivar, just return a BareIVarExpr or something. 2441 IdentifierInfo &II = Context.Idents.get("self"); 2442 UnqualifiedId SelfName; 2443 SelfName.setIdentifier(&II, SourceLocation()); 2444 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2445 CXXScopeSpec SelfScopeSpec; 2446 SourceLocation TemplateKWLoc; 2447 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2448 SelfName, false, false); 2449 if (SelfExpr.isInvalid()) 2450 return ExprError(); 2451 2452 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2453 if (SelfExpr.isInvalid()) 2454 return ExprError(); 2455 2456 MarkAnyDeclReferenced(Loc, IV, true); 2457 2458 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2459 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2460 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2461 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2462 2463 ObjCIvarRefExpr *Result = new (Context) 2464 ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(), 2465 SelfExpr.get(), true, true); 2466 2467 if (getLangOpts().ObjCAutoRefCount) { 2468 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2469 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2470 recordUseOfEvaluatedWeak(Result); 2471 } 2472 if (CurContext->isClosure()) 2473 Diag(Loc, diag::warn_implicitly_retains_self) 2474 << FixItHint::CreateInsertion(Loc, "self->"); 2475 } 2476 2477 return Result; 2478 } 2479 } else if (CurMethod->isInstanceMethod()) { 2480 // We should warn if a local variable hides an ivar. 2481 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2482 ObjCInterfaceDecl *ClassDeclared; 2483 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2484 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2485 declaresSameEntity(IFace, ClassDeclared)) 2486 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2487 } 2488 } 2489 } else if (Lookup.isSingleResult() && 2490 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2491 // If accessing a stand-alone ivar in a class method, this is an error. 2492 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2493 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2494 << IV->getDeclName()); 2495 } 2496 2497 if (Lookup.empty() && II && AllowBuiltinCreation) { 2498 // FIXME. Consolidate this with similar code in LookupName. 2499 if (unsigned BuiltinID = II->getBuiltinID()) { 2500 if (!(getLangOpts().CPlusPlus && 2501 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2502 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2503 S, Lookup.isForRedeclaration(), 2504 Lookup.getNameLoc()); 2505 if (D) Lookup.addDecl(D); 2506 } 2507 } 2508 } 2509 // Sentinel value saying that we didn't do anything special. 2510 return ExprResult((Expr *)nullptr); 2511 } 2512 2513 /// \brief Cast a base object to a member's actual type. 2514 /// 2515 /// Logically this happens in three phases: 2516 /// 2517 /// * First we cast from the base type to the naming class. 2518 /// The naming class is the class into which we were looking 2519 /// when we found the member; it's the qualifier type if a 2520 /// qualifier was provided, and otherwise it's the base type. 2521 /// 2522 /// * Next we cast from the naming class to the declaring class. 2523 /// If the member we found was brought into a class's scope by 2524 /// a using declaration, this is that class; otherwise it's 2525 /// the class declaring the member. 2526 /// 2527 /// * Finally we cast from the declaring class to the "true" 2528 /// declaring class of the member. This conversion does not 2529 /// obey access control. 2530 ExprResult 2531 Sema::PerformObjectMemberConversion(Expr *From, 2532 NestedNameSpecifier *Qualifier, 2533 NamedDecl *FoundDecl, 2534 NamedDecl *Member) { 2535 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2536 if (!RD) 2537 return From; 2538 2539 QualType DestRecordType; 2540 QualType DestType; 2541 QualType FromRecordType; 2542 QualType FromType = From->getType(); 2543 bool PointerConversions = false; 2544 if (isa<FieldDecl>(Member)) { 2545 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2546 2547 if (FromType->getAs<PointerType>()) { 2548 DestType = Context.getPointerType(DestRecordType); 2549 FromRecordType = FromType->getPointeeType(); 2550 PointerConversions = true; 2551 } else { 2552 DestType = DestRecordType; 2553 FromRecordType = FromType; 2554 } 2555 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2556 if (Method->isStatic()) 2557 return From; 2558 2559 DestType = Method->getThisType(Context); 2560 DestRecordType = DestType->getPointeeType(); 2561 2562 if (FromType->getAs<PointerType>()) { 2563 FromRecordType = FromType->getPointeeType(); 2564 PointerConversions = true; 2565 } else { 2566 FromRecordType = FromType; 2567 DestType = DestRecordType; 2568 } 2569 } else { 2570 // No conversion necessary. 2571 return From; 2572 } 2573 2574 if (DestType->isDependentType() || FromType->isDependentType()) 2575 return From; 2576 2577 // If the unqualified types are the same, no conversion is necessary. 2578 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2579 return From; 2580 2581 SourceRange FromRange = From->getSourceRange(); 2582 SourceLocation FromLoc = FromRange.getBegin(); 2583 2584 ExprValueKind VK = From->getValueKind(); 2585 2586 // C++ [class.member.lookup]p8: 2587 // [...] Ambiguities can often be resolved by qualifying a name with its 2588 // class name. 2589 // 2590 // If the member was a qualified name and the qualified referred to a 2591 // specific base subobject type, we'll cast to that intermediate type 2592 // first and then to the object in which the member is declared. That allows 2593 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2594 // 2595 // class Base { public: int x; }; 2596 // class Derived1 : public Base { }; 2597 // class Derived2 : public Base { }; 2598 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2599 // 2600 // void VeryDerived::f() { 2601 // x = 17; // error: ambiguous base subobjects 2602 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2603 // } 2604 if (Qualifier && Qualifier->getAsType()) { 2605 QualType QType = QualType(Qualifier->getAsType(), 0); 2606 assert(QType->isRecordType() && "lookup done with non-record type"); 2607 2608 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2609 2610 // In C++98, the qualifier type doesn't actually have to be a base 2611 // type of the object type, in which case we just ignore it. 2612 // Otherwise build the appropriate casts. 2613 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2614 CXXCastPath BasePath; 2615 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2616 FromLoc, FromRange, &BasePath)) 2617 return ExprError(); 2618 2619 if (PointerConversions) 2620 QType = Context.getPointerType(QType); 2621 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2622 VK, &BasePath).get(); 2623 2624 FromType = QType; 2625 FromRecordType = QRecordType; 2626 2627 // If the qualifier type was the same as the destination type, 2628 // we're done. 2629 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2630 return From; 2631 } 2632 } 2633 2634 bool IgnoreAccess = false; 2635 2636 // If we actually found the member through a using declaration, cast 2637 // down to the using declaration's type. 2638 // 2639 // Pointer equality is fine here because only one declaration of a 2640 // class ever has member declarations. 2641 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2642 assert(isa<UsingShadowDecl>(FoundDecl)); 2643 QualType URecordType = Context.getTypeDeclType( 2644 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2645 2646 // We only need to do this if the naming-class to declaring-class 2647 // conversion is non-trivial. 2648 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2649 assert(IsDerivedFrom(FromRecordType, URecordType)); 2650 CXXCastPath BasePath; 2651 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2652 FromLoc, FromRange, &BasePath)) 2653 return ExprError(); 2654 2655 QualType UType = URecordType; 2656 if (PointerConversions) 2657 UType = Context.getPointerType(UType); 2658 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2659 VK, &BasePath).get(); 2660 FromType = UType; 2661 FromRecordType = URecordType; 2662 } 2663 2664 // We don't do access control for the conversion from the 2665 // declaring class to the true declaring class. 2666 IgnoreAccess = true; 2667 } 2668 2669 CXXCastPath BasePath; 2670 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2671 FromLoc, FromRange, &BasePath, 2672 IgnoreAccess)) 2673 return ExprError(); 2674 2675 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2676 VK, &BasePath); 2677 } 2678 2679 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2680 const LookupResult &R, 2681 bool HasTrailingLParen) { 2682 // Only when used directly as the postfix-expression of a call. 2683 if (!HasTrailingLParen) 2684 return false; 2685 2686 // Never if a scope specifier was provided. 2687 if (SS.isSet()) 2688 return false; 2689 2690 // Only in C++ or ObjC++. 2691 if (!getLangOpts().CPlusPlus) 2692 return false; 2693 2694 // Turn off ADL when we find certain kinds of declarations during 2695 // normal lookup: 2696 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2697 NamedDecl *D = *I; 2698 2699 // C++0x [basic.lookup.argdep]p3: 2700 // -- a declaration of a class member 2701 // Since using decls preserve this property, we check this on the 2702 // original decl. 2703 if (D->isCXXClassMember()) 2704 return false; 2705 2706 // C++0x [basic.lookup.argdep]p3: 2707 // -- a block-scope function declaration that is not a 2708 // using-declaration 2709 // NOTE: we also trigger this for function templates (in fact, we 2710 // don't check the decl type at all, since all other decl types 2711 // turn off ADL anyway). 2712 if (isa<UsingShadowDecl>(D)) 2713 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2714 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2715 return false; 2716 2717 // C++0x [basic.lookup.argdep]p3: 2718 // -- a declaration that is neither a function or a function 2719 // template 2720 // And also for builtin functions. 2721 if (isa<FunctionDecl>(D)) { 2722 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2723 2724 // But also builtin functions. 2725 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2726 return false; 2727 } else if (!isa<FunctionTemplateDecl>(D)) 2728 return false; 2729 } 2730 2731 return true; 2732 } 2733 2734 2735 /// Diagnoses obvious problems with the use of the given declaration 2736 /// as an expression. This is only actually called for lookups that 2737 /// were not overloaded, and it doesn't promise that the declaration 2738 /// will in fact be used. 2739 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2740 if (isa<TypedefNameDecl>(D)) { 2741 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2742 return true; 2743 } 2744 2745 if (isa<ObjCInterfaceDecl>(D)) { 2746 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2747 return true; 2748 } 2749 2750 if (isa<NamespaceDecl>(D)) { 2751 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2752 return true; 2753 } 2754 2755 return false; 2756 } 2757 2758 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2759 LookupResult &R, bool NeedsADL, 2760 bool AcceptInvalidDecl) { 2761 // If this is a single, fully-resolved result and we don't need ADL, 2762 // just build an ordinary singleton decl ref. 2763 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2764 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2765 R.getRepresentativeDecl(), nullptr, 2766 AcceptInvalidDecl); 2767 2768 // We only need to check the declaration if there's exactly one 2769 // result, because in the overloaded case the results can only be 2770 // functions and function templates. 2771 if (R.isSingleResult() && 2772 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2773 return ExprError(); 2774 2775 // Otherwise, just build an unresolved lookup expression. Suppress 2776 // any lookup-related diagnostics; we'll hash these out later, when 2777 // we've picked a target. 2778 R.suppressDiagnostics(); 2779 2780 UnresolvedLookupExpr *ULE 2781 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2782 SS.getWithLocInContext(Context), 2783 R.getLookupNameInfo(), 2784 NeedsADL, R.isOverloadedResult(), 2785 R.begin(), R.end()); 2786 2787 return ULE; 2788 } 2789 2790 /// \brief Complete semantic analysis for a reference to the given declaration. 2791 ExprResult Sema::BuildDeclarationNameExpr( 2792 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2793 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2794 bool AcceptInvalidDecl) { 2795 assert(D && "Cannot refer to a NULL declaration"); 2796 assert(!isa<FunctionTemplateDecl>(D) && 2797 "Cannot refer unambiguously to a function template"); 2798 2799 SourceLocation Loc = NameInfo.getLoc(); 2800 if (CheckDeclInExpr(*this, Loc, D)) 2801 return ExprError(); 2802 2803 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2804 // Specifically diagnose references to class templates that are missing 2805 // a template argument list. 2806 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2807 << Template << SS.getRange(); 2808 Diag(Template->getLocation(), diag::note_template_decl_here); 2809 return ExprError(); 2810 } 2811 2812 // Make sure that we're referring to a value. 2813 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2814 if (!VD) { 2815 Diag(Loc, diag::err_ref_non_value) 2816 << D << SS.getRange(); 2817 Diag(D->getLocation(), diag::note_declared_at); 2818 return ExprError(); 2819 } 2820 2821 // Check whether this declaration can be used. Note that we suppress 2822 // this check when we're going to perform argument-dependent lookup 2823 // on this function name, because this might not be the function 2824 // that overload resolution actually selects. 2825 if (DiagnoseUseOfDecl(VD, Loc)) 2826 return ExprError(); 2827 2828 // Only create DeclRefExpr's for valid Decl's. 2829 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2830 return ExprError(); 2831 2832 // Handle members of anonymous structs and unions. If we got here, 2833 // and the reference is to a class member indirect field, then this 2834 // must be the subject of a pointer-to-member expression. 2835 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2836 if (!indirectField->isCXXClassMember()) 2837 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2838 indirectField); 2839 2840 { 2841 QualType type = VD->getType(); 2842 ExprValueKind valueKind = VK_RValue; 2843 2844 switch (D->getKind()) { 2845 // Ignore all the non-ValueDecl kinds. 2846 #define ABSTRACT_DECL(kind) 2847 #define VALUE(type, base) 2848 #define DECL(type, base) \ 2849 case Decl::type: 2850 #include "clang/AST/DeclNodes.inc" 2851 llvm_unreachable("invalid value decl kind"); 2852 2853 // These shouldn't make it here. 2854 case Decl::ObjCAtDefsField: 2855 case Decl::ObjCIvar: 2856 llvm_unreachable("forming non-member reference to ivar?"); 2857 2858 // Enum constants are always r-values and never references. 2859 // Unresolved using declarations are dependent. 2860 case Decl::EnumConstant: 2861 case Decl::UnresolvedUsingValue: 2862 valueKind = VK_RValue; 2863 break; 2864 2865 // Fields and indirect fields that got here must be for 2866 // pointer-to-member expressions; we just call them l-values for 2867 // internal consistency, because this subexpression doesn't really 2868 // exist in the high-level semantics. 2869 case Decl::Field: 2870 case Decl::IndirectField: 2871 assert(getLangOpts().CPlusPlus && 2872 "building reference to field in C?"); 2873 2874 // These can't have reference type in well-formed programs, but 2875 // for internal consistency we do this anyway. 2876 type = type.getNonReferenceType(); 2877 valueKind = VK_LValue; 2878 break; 2879 2880 // Non-type template parameters are either l-values or r-values 2881 // depending on the type. 2882 case Decl::NonTypeTemplateParm: { 2883 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2884 type = reftype->getPointeeType(); 2885 valueKind = VK_LValue; // even if the parameter is an r-value reference 2886 break; 2887 } 2888 2889 // For non-references, we need to strip qualifiers just in case 2890 // the template parameter was declared as 'const int' or whatever. 2891 valueKind = VK_RValue; 2892 type = type.getUnqualifiedType(); 2893 break; 2894 } 2895 2896 case Decl::Var: 2897 case Decl::VarTemplateSpecialization: 2898 case Decl::VarTemplatePartialSpecialization: 2899 // In C, "extern void blah;" is valid and is an r-value. 2900 if (!getLangOpts().CPlusPlus && 2901 !type.hasQualifiers() && 2902 type->isVoidType()) { 2903 valueKind = VK_RValue; 2904 break; 2905 } 2906 // fallthrough 2907 2908 case Decl::ImplicitParam: 2909 case Decl::ParmVar: { 2910 // These are always l-values. 2911 valueKind = VK_LValue; 2912 type = type.getNonReferenceType(); 2913 2914 // FIXME: Does the addition of const really only apply in 2915 // potentially-evaluated contexts? Since the variable isn't actually 2916 // captured in an unevaluated context, it seems that the answer is no. 2917 if (!isUnevaluatedContext()) { 2918 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2919 if (!CapturedType.isNull()) 2920 type = CapturedType; 2921 } 2922 2923 break; 2924 } 2925 2926 case Decl::Function: { 2927 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2928 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2929 type = Context.BuiltinFnTy; 2930 valueKind = VK_RValue; 2931 break; 2932 } 2933 } 2934 2935 const FunctionType *fty = type->castAs<FunctionType>(); 2936 2937 // If we're referring to a function with an __unknown_anytype 2938 // result type, make the entire expression __unknown_anytype. 2939 if (fty->getReturnType() == Context.UnknownAnyTy) { 2940 type = Context.UnknownAnyTy; 2941 valueKind = VK_RValue; 2942 break; 2943 } 2944 2945 // Functions are l-values in C++. 2946 if (getLangOpts().CPlusPlus) { 2947 valueKind = VK_LValue; 2948 break; 2949 } 2950 2951 // C99 DR 316 says that, if a function type comes from a 2952 // function definition (without a prototype), that type is only 2953 // used for checking compatibility. Therefore, when referencing 2954 // the function, we pretend that we don't have the full function 2955 // type. 2956 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2957 isa<FunctionProtoType>(fty)) 2958 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2959 fty->getExtInfo()); 2960 2961 // Functions are r-values in C. 2962 valueKind = VK_RValue; 2963 break; 2964 } 2965 2966 case Decl::MSProperty: 2967 valueKind = VK_LValue; 2968 break; 2969 2970 case Decl::CXXMethod: 2971 // If we're referring to a method with an __unknown_anytype 2972 // result type, make the entire expression __unknown_anytype. 2973 // This should only be possible with a type written directly. 2974 if (const FunctionProtoType *proto 2975 = dyn_cast<FunctionProtoType>(VD->getType())) 2976 if (proto->getReturnType() == Context.UnknownAnyTy) { 2977 type = Context.UnknownAnyTy; 2978 valueKind = VK_RValue; 2979 break; 2980 } 2981 2982 // C++ methods are l-values if static, r-values if non-static. 2983 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2984 valueKind = VK_LValue; 2985 break; 2986 } 2987 // fallthrough 2988 2989 case Decl::CXXConversion: 2990 case Decl::CXXDestructor: 2991 case Decl::CXXConstructor: 2992 valueKind = VK_RValue; 2993 break; 2994 } 2995 2996 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2997 TemplateArgs); 2998 } 2999 } 3000 3001 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3002 SmallString<32> &Target) { 3003 Target.resize(CharByteWidth * (Source.size() + 1)); 3004 char *ResultPtr = &Target[0]; 3005 const UTF8 *ErrorPtr; 3006 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3007 (void)success; 3008 assert(success); 3009 Target.resize(ResultPtr - &Target[0]); 3010 } 3011 3012 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3013 PredefinedExpr::IdentType IT) { 3014 // Pick the current block, lambda, captured statement or function. 3015 Decl *currentDecl = nullptr; 3016 if (const BlockScopeInfo *BSI = getCurBlock()) 3017 currentDecl = BSI->TheDecl; 3018 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3019 currentDecl = LSI->CallOperator; 3020 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3021 currentDecl = CSI->TheCapturedDecl; 3022 else 3023 currentDecl = getCurFunctionOrMethodDecl(); 3024 3025 if (!currentDecl) { 3026 Diag(Loc, diag::ext_predef_outside_function); 3027 currentDecl = Context.getTranslationUnitDecl(); 3028 } 3029 3030 QualType ResTy; 3031 StringLiteral *SL = nullptr; 3032 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3033 ResTy = Context.DependentTy; 3034 else { 3035 // Pre-defined identifiers are of type char[x], where x is the length of 3036 // the string. 3037 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3038 unsigned Length = Str.length(); 3039 3040 llvm::APInt LengthI(32, Length + 1); 3041 if (IT == PredefinedExpr::LFunction) { 3042 ResTy = Context.WideCharTy.withConst(); 3043 SmallString<32> RawChars; 3044 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3045 Str, RawChars); 3046 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3047 /*IndexTypeQuals*/ 0); 3048 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3049 /*Pascal*/ false, ResTy, Loc); 3050 } else { 3051 ResTy = Context.CharTy.withConst(); 3052 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3053 /*IndexTypeQuals*/ 0); 3054 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3055 /*Pascal*/ false, ResTy, Loc); 3056 } 3057 } 3058 3059 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3060 } 3061 3062 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3063 PredefinedExpr::IdentType IT; 3064 3065 switch (Kind) { 3066 default: llvm_unreachable("Unknown simple primary expr!"); 3067 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3068 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3069 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3070 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3071 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3072 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3073 } 3074 3075 return BuildPredefinedExpr(Loc, IT); 3076 } 3077 3078 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3079 SmallString<16> CharBuffer; 3080 bool Invalid = false; 3081 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3082 if (Invalid) 3083 return ExprError(); 3084 3085 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3086 PP, Tok.getKind()); 3087 if (Literal.hadError()) 3088 return ExprError(); 3089 3090 QualType Ty; 3091 if (Literal.isWide()) 3092 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3093 else if (Literal.isUTF16()) 3094 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3095 else if (Literal.isUTF32()) 3096 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3097 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3098 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3099 else 3100 Ty = Context.CharTy; // 'x' -> char in C++ 3101 3102 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3103 if (Literal.isWide()) 3104 Kind = CharacterLiteral::Wide; 3105 else if (Literal.isUTF16()) 3106 Kind = CharacterLiteral::UTF16; 3107 else if (Literal.isUTF32()) 3108 Kind = CharacterLiteral::UTF32; 3109 3110 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3111 Tok.getLocation()); 3112 3113 if (Literal.getUDSuffix().empty()) 3114 return Lit; 3115 3116 // We're building a user-defined literal. 3117 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3118 SourceLocation UDSuffixLoc = 3119 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3120 3121 // Make sure we're allowed user-defined literals here. 3122 if (!UDLScope) 3123 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3124 3125 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3126 // operator "" X (ch) 3127 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3128 Lit, Tok.getLocation()); 3129 } 3130 3131 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3132 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3133 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3134 Context.IntTy, Loc); 3135 } 3136 3137 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3138 QualType Ty, SourceLocation Loc) { 3139 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3140 3141 using llvm::APFloat; 3142 APFloat Val(Format); 3143 3144 APFloat::opStatus result = Literal.GetFloatValue(Val); 3145 3146 // Overflow is always an error, but underflow is only an error if 3147 // we underflowed to zero (APFloat reports denormals as underflow). 3148 if ((result & APFloat::opOverflow) || 3149 ((result & APFloat::opUnderflow) && Val.isZero())) { 3150 unsigned diagnostic; 3151 SmallString<20> buffer; 3152 if (result & APFloat::opOverflow) { 3153 diagnostic = diag::warn_float_overflow; 3154 APFloat::getLargest(Format).toString(buffer); 3155 } else { 3156 diagnostic = diag::warn_float_underflow; 3157 APFloat::getSmallest(Format).toString(buffer); 3158 } 3159 3160 S.Diag(Loc, diagnostic) 3161 << Ty 3162 << StringRef(buffer.data(), buffer.size()); 3163 } 3164 3165 bool isExact = (result == APFloat::opOK); 3166 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3167 } 3168 3169 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3170 assert(E && "Invalid expression"); 3171 3172 if (E->isValueDependent()) 3173 return false; 3174 3175 QualType QT = E->getType(); 3176 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3177 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3178 return true; 3179 } 3180 3181 llvm::APSInt ValueAPS; 3182 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3183 3184 if (R.isInvalid()) 3185 return true; 3186 3187 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3188 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3189 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3190 << ValueAPS.toString(10) << ValueIsPositive; 3191 return true; 3192 } 3193 3194 return false; 3195 } 3196 3197 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3198 // Fast path for a single digit (which is quite common). A single digit 3199 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3200 if (Tok.getLength() == 1) { 3201 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3202 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3203 } 3204 3205 SmallString<128> SpellingBuffer; 3206 // NumericLiteralParser wants to overread by one character. Add padding to 3207 // the buffer in case the token is copied to the buffer. If getSpelling() 3208 // returns a StringRef to the memory buffer, it should have a null char at 3209 // the EOF, so it is also safe. 3210 SpellingBuffer.resize(Tok.getLength() + 1); 3211 3212 // Get the spelling of the token, which eliminates trigraphs, etc. 3213 bool Invalid = false; 3214 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3215 if (Invalid) 3216 return ExprError(); 3217 3218 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3219 if (Literal.hadError) 3220 return ExprError(); 3221 3222 if (Literal.hasUDSuffix()) { 3223 // We're building a user-defined literal. 3224 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3225 SourceLocation UDSuffixLoc = 3226 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3227 3228 // Make sure we're allowed user-defined literals here. 3229 if (!UDLScope) 3230 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3231 3232 QualType CookedTy; 3233 if (Literal.isFloatingLiteral()) { 3234 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3235 // long double, the literal is treated as a call of the form 3236 // operator "" X (f L) 3237 CookedTy = Context.LongDoubleTy; 3238 } else { 3239 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3240 // unsigned long long, the literal is treated as a call of the form 3241 // operator "" X (n ULL) 3242 CookedTy = Context.UnsignedLongLongTy; 3243 } 3244 3245 DeclarationName OpName = 3246 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3247 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3248 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3249 3250 SourceLocation TokLoc = Tok.getLocation(); 3251 3252 // Perform literal operator lookup to determine if we're building a raw 3253 // literal or a cooked one. 3254 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3255 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3256 /*AllowRaw*/true, /*AllowTemplate*/true, 3257 /*AllowStringTemplate*/false)) { 3258 case LOLR_Error: 3259 return ExprError(); 3260 3261 case LOLR_Cooked: { 3262 Expr *Lit; 3263 if (Literal.isFloatingLiteral()) { 3264 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3265 } else { 3266 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3267 if (Literal.GetIntegerValue(ResultVal)) 3268 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3269 << /* Unsigned */ 1; 3270 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3271 Tok.getLocation()); 3272 } 3273 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3274 } 3275 3276 case LOLR_Raw: { 3277 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3278 // literal is treated as a call of the form 3279 // operator "" X ("n") 3280 unsigned Length = Literal.getUDSuffixOffset(); 3281 QualType StrTy = Context.getConstantArrayType( 3282 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3283 ArrayType::Normal, 0); 3284 Expr *Lit = StringLiteral::Create( 3285 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3286 /*Pascal*/false, StrTy, &TokLoc, 1); 3287 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3288 } 3289 3290 case LOLR_Template: { 3291 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3292 // template), L is treated as a call fo the form 3293 // operator "" X <'c1', 'c2', ... 'ck'>() 3294 // where n is the source character sequence c1 c2 ... ck. 3295 TemplateArgumentListInfo ExplicitArgs; 3296 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3297 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3298 llvm::APSInt Value(CharBits, CharIsUnsigned); 3299 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3300 Value = TokSpelling[I]; 3301 TemplateArgument Arg(Context, Value, Context.CharTy); 3302 TemplateArgumentLocInfo ArgInfo; 3303 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3304 } 3305 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3306 &ExplicitArgs); 3307 } 3308 case LOLR_StringTemplate: 3309 llvm_unreachable("unexpected literal operator lookup result"); 3310 } 3311 } 3312 3313 Expr *Res; 3314 3315 if (Literal.isFloatingLiteral()) { 3316 QualType Ty; 3317 if (Literal.isFloat) 3318 Ty = Context.FloatTy; 3319 else if (!Literal.isLong) 3320 Ty = Context.DoubleTy; 3321 else 3322 Ty = Context.LongDoubleTy; 3323 3324 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3325 3326 if (Ty == Context.DoubleTy) { 3327 if (getLangOpts().SinglePrecisionConstants) { 3328 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3329 } else if (getLangOpts().OpenCL && 3330 !((getLangOpts().OpenCLVersion >= 120) || 3331 getOpenCLOptions().cl_khr_fp64)) { 3332 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3333 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3334 } 3335 } 3336 } else if (!Literal.isIntegerLiteral()) { 3337 return ExprError(); 3338 } else { 3339 QualType Ty; 3340 3341 // 'long long' is a C99 or C++11 feature. 3342 if (!getLangOpts().C99 && Literal.isLongLong) { 3343 if (getLangOpts().CPlusPlus) 3344 Diag(Tok.getLocation(), 3345 getLangOpts().CPlusPlus11 ? 3346 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3347 else 3348 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3349 } 3350 3351 // Get the value in the widest-possible width. 3352 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3353 // The microsoft literal suffix extensions support 128-bit literals, which 3354 // may be wider than [u]intmax_t. 3355 // FIXME: Actually, they don't. We seem to have accidentally invented the 3356 // i128 suffix. 3357 if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 && 3358 Context.getTargetInfo().hasInt128Type()) 3359 MaxWidth = 128; 3360 llvm::APInt ResultVal(MaxWidth, 0); 3361 3362 if (Literal.GetIntegerValue(ResultVal)) { 3363 // If this value didn't fit into uintmax_t, error and force to ull. 3364 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3365 << /* Unsigned */ 1; 3366 Ty = Context.UnsignedLongLongTy; 3367 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3368 "long long is not intmax_t?"); 3369 } else { 3370 // If this value fits into a ULL, try to figure out what else it fits into 3371 // according to the rules of C99 6.4.4.1p5. 3372 3373 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3374 // be an unsigned int. 3375 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3376 3377 // Check from smallest to largest, picking the smallest type we can. 3378 unsigned Width = 0; 3379 3380 // Microsoft specific integer suffixes are explicitly sized. 3381 if (Literal.MicrosoftInteger) { 3382 if (Literal.MicrosoftInteger > MaxWidth) { 3383 // If this target doesn't support __int128, error and force to ull. 3384 Diag(Tok.getLocation(), diag::err_int128_unsupported); 3385 Width = MaxWidth; 3386 Ty = Context.getIntMaxType(); 3387 } else if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3388 Width = 8; 3389 Ty = Context.CharTy; 3390 } else { 3391 Width = Literal.MicrosoftInteger; 3392 Ty = Context.getIntTypeForBitwidth(Width, 3393 /*Signed=*/!Literal.isUnsigned); 3394 } 3395 } 3396 3397 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3398 // Are int/unsigned possibilities? 3399 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3400 3401 // Does it fit in a unsigned int? 3402 if (ResultVal.isIntN(IntSize)) { 3403 // Does it fit in a signed int? 3404 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3405 Ty = Context.IntTy; 3406 else if (AllowUnsigned) 3407 Ty = Context.UnsignedIntTy; 3408 Width = IntSize; 3409 } 3410 } 3411 3412 // Are long/unsigned long possibilities? 3413 if (Ty.isNull() && !Literal.isLongLong) { 3414 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3415 3416 // Does it fit in a unsigned long? 3417 if (ResultVal.isIntN(LongSize)) { 3418 // Does it fit in a signed long? 3419 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3420 Ty = Context.LongTy; 3421 else if (AllowUnsigned) 3422 Ty = Context.UnsignedLongTy; 3423 Width = LongSize; 3424 } 3425 } 3426 3427 // Check long long if needed. 3428 if (Ty.isNull()) { 3429 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3430 3431 // Does it fit in a unsigned long long? 3432 if (ResultVal.isIntN(LongLongSize)) { 3433 // Does it fit in a signed long long? 3434 // To be compatible with MSVC, hex integer literals ending with the 3435 // LL or i64 suffix are always signed in Microsoft mode. 3436 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3437 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3438 Ty = Context.LongLongTy; 3439 else if (AllowUnsigned) 3440 Ty = Context.UnsignedLongLongTy; 3441 Width = LongLongSize; 3442 } 3443 } 3444 3445 // If we still couldn't decide a type, we probably have something that 3446 // does not fit in a signed long long, but has no U suffix. 3447 if (Ty.isNull()) { 3448 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3449 Ty = Context.UnsignedLongLongTy; 3450 Width = Context.getTargetInfo().getLongLongWidth(); 3451 } 3452 3453 if (ResultVal.getBitWidth() != Width) 3454 ResultVal = ResultVal.trunc(Width); 3455 } 3456 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3457 } 3458 3459 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3460 if (Literal.isImaginary) 3461 Res = new (Context) ImaginaryLiteral(Res, 3462 Context.getComplexType(Res->getType())); 3463 3464 return Res; 3465 } 3466 3467 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3468 assert(E && "ActOnParenExpr() missing expr"); 3469 return new (Context) ParenExpr(L, R, E); 3470 } 3471 3472 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3473 SourceLocation Loc, 3474 SourceRange ArgRange) { 3475 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3476 // scalar or vector data type argument..." 3477 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3478 // type (C99 6.2.5p18) or void. 3479 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3480 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3481 << T << ArgRange; 3482 return true; 3483 } 3484 3485 assert((T->isVoidType() || !T->isIncompleteType()) && 3486 "Scalar types should always be complete"); 3487 return false; 3488 } 3489 3490 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3491 SourceLocation Loc, 3492 SourceRange ArgRange, 3493 UnaryExprOrTypeTrait TraitKind) { 3494 // Invalid types must be hard errors for SFINAE in C++. 3495 if (S.LangOpts.CPlusPlus) 3496 return true; 3497 3498 // C99 6.5.3.4p1: 3499 if (T->isFunctionType() && 3500 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3501 // sizeof(function)/alignof(function) is allowed as an extension. 3502 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3503 << TraitKind << ArgRange; 3504 return false; 3505 } 3506 3507 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3508 // this is an error (OpenCL v1.1 s6.3.k) 3509 if (T->isVoidType()) { 3510 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3511 : diag::ext_sizeof_alignof_void_type; 3512 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3513 return false; 3514 } 3515 3516 return true; 3517 } 3518 3519 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3520 SourceLocation Loc, 3521 SourceRange ArgRange, 3522 UnaryExprOrTypeTrait TraitKind) { 3523 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3524 // runtime doesn't allow it. 3525 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3526 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3527 << T << (TraitKind == UETT_SizeOf) 3528 << ArgRange; 3529 return true; 3530 } 3531 3532 return false; 3533 } 3534 3535 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3536 /// pointer type is equal to T) and emit a warning if it is. 3537 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3538 Expr *E) { 3539 // Don't warn if the operation changed the type. 3540 if (T != E->getType()) 3541 return; 3542 3543 // Now look for array decays. 3544 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3545 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3546 return; 3547 3548 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3549 << ICE->getType() 3550 << ICE->getSubExpr()->getType(); 3551 } 3552 3553 /// \brief Check the constraints on expression operands to unary type expression 3554 /// and type traits. 3555 /// 3556 /// Completes any types necessary and validates the constraints on the operand 3557 /// expression. The logic mostly mirrors the type-based overload, but may modify 3558 /// the expression as it completes the type for that expression through template 3559 /// instantiation, etc. 3560 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3561 UnaryExprOrTypeTrait ExprKind) { 3562 QualType ExprTy = E->getType(); 3563 assert(!ExprTy->isReferenceType()); 3564 3565 if (ExprKind == UETT_VecStep) 3566 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3567 E->getSourceRange()); 3568 3569 // Whitelist some types as extensions 3570 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3571 E->getSourceRange(), ExprKind)) 3572 return false; 3573 3574 // 'alignof' applied to an expression only requires the base element type of 3575 // the expression to be complete. 'sizeof' requires the expression's type to 3576 // be complete (and will attempt to complete it if it's an array of unknown 3577 // bound). 3578 if (ExprKind == UETT_AlignOf) { 3579 if (RequireCompleteType(E->getExprLoc(), 3580 Context.getBaseElementType(E->getType()), 3581 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3582 E->getSourceRange())) 3583 return true; 3584 } else { 3585 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3586 ExprKind, E->getSourceRange())) 3587 return true; 3588 } 3589 3590 // Completing the expression's type may have changed it. 3591 ExprTy = E->getType(); 3592 assert(!ExprTy->isReferenceType()); 3593 3594 if (ExprTy->isFunctionType()) { 3595 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3596 << ExprKind << E->getSourceRange(); 3597 return true; 3598 } 3599 3600 // The operand for sizeof and alignof is in an unevaluated expression context, 3601 // so side effects could result in unintended consequences. 3602 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3603 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3604 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3605 3606 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3607 E->getSourceRange(), ExprKind)) 3608 return true; 3609 3610 if (ExprKind == UETT_SizeOf) { 3611 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3612 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3613 QualType OType = PVD->getOriginalType(); 3614 QualType Type = PVD->getType(); 3615 if (Type->isPointerType() && OType->isArrayType()) { 3616 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3617 << Type << OType; 3618 Diag(PVD->getLocation(), diag::note_declared_at); 3619 } 3620 } 3621 } 3622 3623 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3624 // decays into a pointer and returns an unintended result. This is most 3625 // likely a typo for "sizeof(array) op x". 3626 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3627 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3628 BO->getLHS()); 3629 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3630 BO->getRHS()); 3631 } 3632 } 3633 3634 return false; 3635 } 3636 3637 /// \brief Check the constraints on operands to unary expression and type 3638 /// traits. 3639 /// 3640 /// This will complete any types necessary, and validate the various constraints 3641 /// on those operands. 3642 /// 3643 /// The UsualUnaryConversions() function is *not* called by this routine. 3644 /// C99 6.3.2.1p[2-4] all state: 3645 /// Except when it is the operand of the sizeof operator ... 3646 /// 3647 /// C++ [expr.sizeof]p4 3648 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3649 /// standard conversions are not applied to the operand of sizeof. 3650 /// 3651 /// This policy is followed for all of the unary trait expressions. 3652 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3653 SourceLocation OpLoc, 3654 SourceRange ExprRange, 3655 UnaryExprOrTypeTrait ExprKind) { 3656 if (ExprType->isDependentType()) 3657 return false; 3658 3659 // C++ [expr.sizeof]p2: 3660 // When applied to a reference or a reference type, the result 3661 // is the size of the referenced type. 3662 // C++11 [expr.alignof]p3: 3663 // When alignof is applied to a reference type, the result 3664 // shall be the alignment of the referenced type. 3665 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3666 ExprType = Ref->getPointeeType(); 3667 3668 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3669 // When alignof or _Alignof is applied to an array type, the result 3670 // is the alignment of the element type. 3671 if (ExprKind == UETT_AlignOf) 3672 ExprType = Context.getBaseElementType(ExprType); 3673 3674 if (ExprKind == UETT_VecStep) 3675 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3676 3677 // Whitelist some types as extensions 3678 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3679 ExprKind)) 3680 return false; 3681 3682 if (RequireCompleteType(OpLoc, ExprType, 3683 diag::err_sizeof_alignof_incomplete_type, 3684 ExprKind, ExprRange)) 3685 return true; 3686 3687 if (ExprType->isFunctionType()) { 3688 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3689 << ExprKind << ExprRange; 3690 return true; 3691 } 3692 3693 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3694 ExprKind)) 3695 return true; 3696 3697 return false; 3698 } 3699 3700 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3701 E = E->IgnoreParens(); 3702 3703 // Cannot know anything else if the expression is dependent. 3704 if (E->isTypeDependent()) 3705 return false; 3706 3707 if (E->getObjectKind() == OK_BitField) { 3708 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3709 << 1 << E->getSourceRange(); 3710 return true; 3711 } 3712 3713 ValueDecl *D = nullptr; 3714 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3715 D = DRE->getDecl(); 3716 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3717 D = ME->getMemberDecl(); 3718 } 3719 3720 // If it's a field, require the containing struct to have a 3721 // complete definition so that we can compute the layout. 3722 // 3723 // This can happen in C++11 onwards, either by naming the member 3724 // in a way that is not transformed into a member access expression 3725 // (in an unevaluated operand, for instance), or by naming the member 3726 // in a trailing-return-type. 3727 // 3728 // For the record, since __alignof__ on expressions is a GCC 3729 // extension, GCC seems to permit this but always gives the 3730 // nonsensical answer 0. 3731 // 3732 // We don't really need the layout here --- we could instead just 3733 // directly check for all the appropriate alignment-lowing 3734 // attributes --- but that would require duplicating a lot of 3735 // logic that just isn't worth duplicating for such a marginal 3736 // use-case. 3737 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3738 // Fast path this check, since we at least know the record has a 3739 // definition if we can find a member of it. 3740 if (!FD->getParent()->isCompleteDefinition()) { 3741 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3742 << E->getSourceRange(); 3743 return true; 3744 } 3745 3746 // Otherwise, if it's a field, and the field doesn't have 3747 // reference type, then it must have a complete type (or be a 3748 // flexible array member, which we explicitly want to 3749 // white-list anyway), which makes the following checks trivial. 3750 if (!FD->getType()->isReferenceType()) 3751 return false; 3752 } 3753 3754 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3755 } 3756 3757 bool Sema::CheckVecStepExpr(Expr *E) { 3758 E = E->IgnoreParens(); 3759 3760 // Cannot know anything else if the expression is dependent. 3761 if (E->isTypeDependent()) 3762 return false; 3763 3764 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3765 } 3766 3767 /// \brief Build a sizeof or alignof expression given a type operand. 3768 ExprResult 3769 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3770 SourceLocation OpLoc, 3771 UnaryExprOrTypeTrait ExprKind, 3772 SourceRange R) { 3773 if (!TInfo) 3774 return ExprError(); 3775 3776 QualType T = TInfo->getType(); 3777 3778 if (!T->isDependentType() && 3779 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3780 return ExprError(); 3781 3782 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3783 return new (Context) UnaryExprOrTypeTraitExpr( 3784 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3785 } 3786 3787 /// \brief Build a sizeof or alignof expression given an expression 3788 /// operand. 3789 ExprResult 3790 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3791 UnaryExprOrTypeTrait ExprKind) { 3792 ExprResult PE = CheckPlaceholderExpr(E); 3793 if (PE.isInvalid()) 3794 return ExprError(); 3795 3796 E = PE.get(); 3797 3798 // Verify that the operand is valid. 3799 bool isInvalid = false; 3800 if (E->isTypeDependent()) { 3801 // Delay type-checking for type-dependent expressions. 3802 } else if (ExprKind == UETT_AlignOf) { 3803 isInvalid = CheckAlignOfExpr(*this, E); 3804 } else if (ExprKind == UETT_VecStep) { 3805 isInvalid = CheckVecStepExpr(E); 3806 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3807 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3808 isInvalid = true; 3809 } else { 3810 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3811 } 3812 3813 if (isInvalid) 3814 return ExprError(); 3815 3816 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3817 PE = TransformToPotentiallyEvaluated(E); 3818 if (PE.isInvalid()) return ExprError(); 3819 E = PE.get(); 3820 } 3821 3822 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3823 return new (Context) UnaryExprOrTypeTraitExpr( 3824 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3825 } 3826 3827 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3828 /// expr and the same for @c alignof and @c __alignof 3829 /// Note that the ArgRange is invalid if isType is false. 3830 ExprResult 3831 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3832 UnaryExprOrTypeTrait ExprKind, bool IsType, 3833 void *TyOrEx, const SourceRange &ArgRange) { 3834 // If error parsing type, ignore. 3835 if (!TyOrEx) return ExprError(); 3836 3837 if (IsType) { 3838 TypeSourceInfo *TInfo; 3839 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3840 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3841 } 3842 3843 Expr *ArgEx = (Expr *)TyOrEx; 3844 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3845 return Result; 3846 } 3847 3848 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3849 bool IsReal) { 3850 if (V.get()->isTypeDependent()) 3851 return S.Context.DependentTy; 3852 3853 // _Real and _Imag are only l-values for normal l-values. 3854 if (V.get()->getObjectKind() != OK_Ordinary) { 3855 V = S.DefaultLvalueConversion(V.get()); 3856 if (V.isInvalid()) 3857 return QualType(); 3858 } 3859 3860 // These operators return the element type of a complex type. 3861 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3862 return CT->getElementType(); 3863 3864 // Otherwise they pass through real integer and floating point types here. 3865 if (V.get()->getType()->isArithmeticType()) 3866 return V.get()->getType(); 3867 3868 // Test for placeholders. 3869 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3870 if (PR.isInvalid()) return QualType(); 3871 if (PR.get() != V.get()) { 3872 V = PR; 3873 return CheckRealImagOperand(S, V, Loc, IsReal); 3874 } 3875 3876 // Reject anything else. 3877 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3878 << (IsReal ? "__real" : "__imag"); 3879 return QualType(); 3880 } 3881 3882 3883 3884 ExprResult 3885 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3886 tok::TokenKind Kind, Expr *Input) { 3887 UnaryOperatorKind Opc; 3888 switch (Kind) { 3889 default: llvm_unreachable("Unknown unary op!"); 3890 case tok::plusplus: Opc = UO_PostInc; break; 3891 case tok::minusminus: Opc = UO_PostDec; break; 3892 } 3893 3894 // Since this might is a postfix expression, get rid of ParenListExprs. 3895 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3896 if (Result.isInvalid()) return ExprError(); 3897 Input = Result.get(); 3898 3899 return BuildUnaryOp(S, OpLoc, Opc, Input); 3900 } 3901 3902 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3903 /// 3904 /// \return true on error 3905 static bool checkArithmeticOnObjCPointer(Sema &S, 3906 SourceLocation opLoc, 3907 Expr *op) { 3908 assert(op->getType()->isObjCObjectPointerType()); 3909 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3910 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3911 return false; 3912 3913 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3914 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3915 << op->getSourceRange(); 3916 return true; 3917 } 3918 3919 ExprResult 3920 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3921 Expr *idx, SourceLocation rbLoc) { 3922 // Since this might be a postfix expression, get rid of ParenListExprs. 3923 if (isa<ParenListExpr>(base)) { 3924 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3925 if (result.isInvalid()) return ExprError(); 3926 base = result.get(); 3927 } 3928 3929 // Handle any non-overload placeholder types in the base and index 3930 // expressions. We can't handle overloads here because the other 3931 // operand might be an overloadable type, in which case the overload 3932 // resolution for the operator overload should get the first crack 3933 // at the overload. 3934 if (base->getType()->isNonOverloadPlaceholderType()) { 3935 ExprResult result = CheckPlaceholderExpr(base); 3936 if (result.isInvalid()) return ExprError(); 3937 base = result.get(); 3938 } 3939 if (idx->getType()->isNonOverloadPlaceholderType()) { 3940 ExprResult result = CheckPlaceholderExpr(idx); 3941 if (result.isInvalid()) return ExprError(); 3942 idx = result.get(); 3943 } 3944 3945 // Build an unanalyzed expression if either operand is type-dependent. 3946 if (getLangOpts().CPlusPlus && 3947 (base->isTypeDependent() || idx->isTypeDependent())) { 3948 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3949 VK_LValue, OK_Ordinary, rbLoc); 3950 } 3951 3952 // Use C++ overloaded-operator rules if either operand has record 3953 // type. The spec says to do this if either type is *overloadable*, 3954 // but enum types can't declare subscript operators or conversion 3955 // operators, so there's nothing interesting for overload resolution 3956 // to do if there aren't any record types involved. 3957 // 3958 // ObjC pointers have their own subscripting logic that is not tied 3959 // to overload resolution and so should not take this path. 3960 if (getLangOpts().CPlusPlus && 3961 (base->getType()->isRecordType() || 3962 (!base->getType()->isObjCObjectPointerType() && 3963 idx->getType()->isRecordType()))) { 3964 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3965 } 3966 3967 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3968 } 3969 3970 ExprResult 3971 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3972 Expr *Idx, SourceLocation RLoc) { 3973 Expr *LHSExp = Base; 3974 Expr *RHSExp = Idx; 3975 3976 // Perform default conversions. 3977 if (!LHSExp->getType()->getAs<VectorType>()) { 3978 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3979 if (Result.isInvalid()) 3980 return ExprError(); 3981 LHSExp = Result.get(); 3982 } 3983 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3984 if (Result.isInvalid()) 3985 return ExprError(); 3986 RHSExp = Result.get(); 3987 3988 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3989 ExprValueKind VK = VK_LValue; 3990 ExprObjectKind OK = OK_Ordinary; 3991 3992 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3993 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3994 // in the subscript position. As a result, we need to derive the array base 3995 // and index from the expression types. 3996 Expr *BaseExpr, *IndexExpr; 3997 QualType ResultType; 3998 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3999 BaseExpr = LHSExp; 4000 IndexExpr = RHSExp; 4001 ResultType = Context.DependentTy; 4002 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4003 BaseExpr = LHSExp; 4004 IndexExpr = RHSExp; 4005 ResultType = PTy->getPointeeType(); 4006 } else if (const ObjCObjectPointerType *PTy = 4007 LHSTy->getAs<ObjCObjectPointerType>()) { 4008 BaseExpr = LHSExp; 4009 IndexExpr = RHSExp; 4010 4011 // Use custom logic if this should be the pseudo-object subscript 4012 // expression. 4013 if (!LangOpts.isSubscriptPointerArithmetic()) 4014 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4015 nullptr); 4016 4017 ResultType = PTy->getPointeeType(); 4018 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4019 // Handle the uncommon case of "123[Ptr]". 4020 BaseExpr = RHSExp; 4021 IndexExpr = LHSExp; 4022 ResultType = PTy->getPointeeType(); 4023 } else if (const ObjCObjectPointerType *PTy = 4024 RHSTy->getAs<ObjCObjectPointerType>()) { 4025 // Handle the uncommon case of "123[Ptr]". 4026 BaseExpr = RHSExp; 4027 IndexExpr = LHSExp; 4028 ResultType = PTy->getPointeeType(); 4029 if (!LangOpts.isSubscriptPointerArithmetic()) { 4030 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4031 << ResultType << BaseExpr->getSourceRange(); 4032 return ExprError(); 4033 } 4034 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4035 BaseExpr = LHSExp; // vectors: V[123] 4036 IndexExpr = RHSExp; 4037 VK = LHSExp->getValueKind(); 4038 if (VK != VK_RValue) 4039 OK = OK_VectorComponent; 4040 4041 // FIXME: need to deal with const... 4042 ResultType = VTy->getElementType(); 4043 } else if (LHSTy->isArrayType()) { 4044 // If we see an array that wasn't promoted by 4045 // DefaultFunctionArrayLvalueConversion, it must be an array that 4046 // wasn't promoted because of the C90 rule that doesn't 4047 // allow promoting non-lvalue arrays. Warn, then 4048 // force the promotion here. 4049 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4050 LHSExp->getSourceRange(); 4051 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4052 CK_ArrayToPointerDecay).get(); 4053 LHSTy = LHSExp->getType(); 4054 4055 BaseExpr = LHSExp; 4056 IndexExpr = RHSExp; 4057 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4058 } else if (RHSTy->isArrayType()) { 4059 // Same as previous, except for 123[f().a] case 4060 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4061 RHSExp->getSourceRange(); 4062 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4063 CK_ArrayToPointerDecay).get(); 4064 RHSTy = RHSExp->getType(); 4065 4066 BaseExpr = RHSExp; 4067 IndexExpr = LHSExp; 4068 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4069 } else { 4070 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4071 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4072 } 4073 // C99 6.5.2.1p1 4074 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4075 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4076 << IndexExpr->getSourceRange()); 4077 4078 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4079 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4080 && !IndexExpr->isTypeDependent()) 4081 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4082 4083 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4084 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4085 // type. Note that Functions are not objects, and that (in C99 parlance) 4086 // incomplete types are not object types. 4087 if (ResultType->isFunctionType()) { 4088 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4089 << ResultType << BaseExpr->getSourceRange(); 4090 return ExprError(); 4091 } 4092 4093 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4094 // GNU extension: subscripting on pointer to void 4095 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4096 << BaseExpr->getSourceRange(); 4097 4098 // C forbids expressions of unqualified void type from being l-values. 4099 // See IsCForbiddenLValueType. 4100 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4101 } else if (!ResultType->isDependentType() && 4102 RequireCompleteType(LLoc, ResultType, 4103 diag::err_subscript_incomplete_type, BaseExpr)) 4104 return ExprError(); 4105 4106 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4107 !ResultType.isCForbiddenLValueType()); 4108 4109 return new (Context) 4110 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4111 } 4112 4113 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4114 FunctionDecl *FD, 4115 ParmVarDecl *Param) { 4116 if (Param->hasUnparsedDefaultArg()) { 4117 Diag(CallLoc, 4118 diag::err_use_of_default_argument_to_function_declared_later) << 4119 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4120 Diag(UnparsedDefaultArgLocs[Param], 4121 diag::note_default_argument_declared_here); 4122 return ExprError(); 4123 } 4124 4125 if (Param->hasUninstantiatedDefaultArg()) { 4126 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4127 4128 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4129 Param); 4130 4131 // Instantiate the expression. 4132 MultiLevelTemplateArgumentList MutiLevelArgList 4133 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4134 4135 InstantiatingTemplate Inst(*this, CallLoc, Param, 4136 MutiLevelArgList.getInnermost()); 4137 if (Inst.isInvalid()) 4138 return ExprError(); 4139 4140 ExprResult Result; 4141 { 4142 // C++ [dcl.fct.default]p5: 4143 // The names in the [default argument] expression are bound, and 4144 // the semantic constraints are checked, at the point where the 4145 // default argument expression appears. 4146 ContextRAII SavedContext(*this, FD); 4147 LocalInstantiationScope Local(*this); 4148 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4149 } 4150 if (Result.isInvalid()) 4151 return ExprError(); 4152 4153 // Check the expression as an initializer for the parameter. 4154 InitializedEntity Entity 4155 = InitializedEntity::InitializeParameter(Context, Param); 4156 InitializationKind Kind 4157 = InitializationKind::CreateCopy(Param->getLocation(), 4158 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4159 Expr *ResultE = Result.getAs<Expr>(); 4160 4161 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4162 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4163 if (Result.isInvalid()) 4164 return ExprError(); 4165 4166 Expr *Arg = Result.getAs<Expr>(); 4167 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4168 // Build the default argument expression. 4169 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4170 } 4171 4172 // If the default expression creates temporaries, we need to 4173 // push them to the current stack of expression temporaries so they'll 4174 // be properly destroyed. 4175 // FIXME: We should really be rebuilding the default argument with new 4176 // bound temporaries; see the comment in PR5810. 4177 // We don't need to do that with block decls, though, because 4178 // blocks in default argument expression can never capture anything. 4179 if (isa<ExprWithCleanups>(Param->getInit())) { 4180 // Set the "needs cleanups" bit regardless of whether there are 4181 // any explicit objects. 4182 ExprNeedsCleanups = true; 4183 4184 // Append all the objects to the cleanup list. Right now, this 4185 // should always be a no-op, because blocks in default argument 4186 // expressions should never be able to capture anything. 4187 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4188 "default argument expression has capturing blocks?"); 4189 } 4190 4191 // We already type-checked the argument, so we know it works. 4192 // Just mark all of the declarations in this potentially-evaluated expression 4193 // as being "referenced". 4194 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4195 /*SkipLocalVariables=*/true); 4196 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4197 } 4198 4199 4200 Sema::VariadicCallType 4201 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4202 Expr *Fn) { 4203 if (Proto && Proto->isVariadic()) { 4204 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4205 return VariadicConstructor; 4206 else if (Fn && Fn->getType()->isBlockPointerType()) 4207 return VariadicBlock; 4208 else if (FDecl) { 4209 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4210 if (Method->isInstance()) 4211 return VariadicMethod; 4212 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4213 return VariadicMethod; 4214 return VariadicFunction; 4215 } 4216 return VariadicDoesNotApply; 4217 } 4218 4219 namespace { 4220 class FunctionCallCCC : public FunctionCallFilterCCC { 4221 public: 4222 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4223 unsigned NumArgs, MemberExpr *ME) 4224 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4225 FunctionName(FuncName) {} 4226 4227 bool ValidateCandidate(const TypoCorrection &candidate) override { 4228 if (!candidate.getCorrectionSpecifier() || 4229 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4230 return false; 4231 } 4232 4233 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4234 } 4235 4236 private: 4237 const IdentifierInfo *const FunctionName; 4238 }; 4239 } 4240 4241 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4242 FunctionDecl *FDecl, 4243 ArrayRef<Expr *> Args) { 4244 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4245 DeclarationName FuncName = FDecl->getDeclName(); 4246 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4247 4248 if (TypoCorrection Corrected = S.CorrectTypo( 4249 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4250 S.getScopeForContext(S.CurContext), nullptr, 4251 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4252 Args.size(), ME), 4253 Sema::CTK_ErrorRecovery)) { 4254 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4255 if (Corrected.isOverloaded()) { 4256 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4257 OverloadCandidateSet::iterator Best; 4258 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4259 CDEnd = Corrected.end(); 4260 CD != CDEnd; ++CD) { 4261 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4262 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4263 OCS); 4264 } 4265 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4266 case OR_Success: 4267 ND = Best->Function; 4268 Corrected.setCorrectionDecl(ND); 4269 break; 4270 default: 4271 break; 4272 } 4273 } 4274 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4275 return Corrected; 4276 } 4277 } 4278 } 4279 return TypoCorrection(); 4280 } 4281 4282 /// ConvertArgumentsForCall - Converts the arguments specified in 4283 /// Args/NumArgs to the parameter types of the function FDecl with 4284 /// function prototype Proto. Call is the call expression itself, and 4285 /// Fn is the function expression. For a C++ member function, this 4286 /// routine does not attempt to convert the object argument. Returns 4287 /// true if the call is ill-formed. 4288 bool 4289 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4290 FunctionDecl *FDecl, 4291 const FunctionProtoType *Proto, 4292 ArrayRef<Expr *> Args, 4293 SourceLocation RParenLoc, 4294 bool IsExecConfig) { 4295 // Bail out early if calling a builtin with custom typechecking. 4296 // We don't need to do this in the 4297 if (FDecl) 4298 if (unsigned ID = FDecl->getBuiltinID()) 4299 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4300 return false; 4301 4302 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4303 // assignment, to the types of the corresponding parameter, ... 4304 unsigned NumParams = Proto->getNumParams(); 4305 bool Invalid = false; 4306 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4307 unsigned FnKind = Fn->getType()->isBlockPointerType() 4308 ? 1 /* block */ 4309 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4310 : 0 /* function */); 4311 4312 // If too few arguments are available (and we don't have default 4313 // arguments for the remaining parameters), don't make the call. 4314 if (Args.size() < NumParams) { 4315 if (Args.size() < MinArgs) { 4316 TypoCorrection TC; 4317 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4318 unsigned diag_id = 4319 MinArgs == NumParams && !Proto->isVariadic() 4320 ? diag::err_typecheck_call_too_few_args_suggest 4321 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4322 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4323 << static_cast<unsigned>(Args.size()) 4324 << TC.getCorrectionRange()); 4325 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4326 Diag(RParenLoc, 4327 MinArgs == NumParams && !Proto->isVariadic() 4328 ? diag::err_typecheck_call_too_few_args_one 4329 : diag::err_typecheck_call_too_few_args_at_least_one) 4330 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4331 else 4332 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4333 ? diag::err_typecheck_call_too_few_args 4334 : diag::err_typecheck_call_too_few_args_at_least) 4335 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4336 << Fn->getSourceRange(); 4337 4338 // Emit the location of the prototype. 4339 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4340 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4341 << FDecl; 4342 4343 return true; 4344 } 4345 Call->setNumArgs(Context, NumParams); 4346 } 4347 4348 // If too many are passed and not variadic, error on the extras and drop 4349 // them. 4350 if (Args.size() > NumParams) { 4351 if (!Proto->isVariadic()) { 4352 TypoCorrection TC; 4353 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4354 unsigned diag_id = 4355 MinArgs == NumParams && !Proto->isVariadic() 4356 ? diag::err_typecheck_call_too_many_args_suggest 4357 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4358 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4359 << static_cast<unsigned>(Args.size()) 4360 << TC.getCorrectionRange()); 4361 } else if (NumParams == 1 && FDecl && 4362 FDecl->getParamDecl(0)->getDeclName()) 4363 Diag(Args[NumParams]->getLocStart(), 4364 MinArgs == NumParams 4365 ? diag::err_typecheck_call_too_many_args_one 4366 : diag::err_typecheck_call_too_many_args_at_most_one) 4367 << FnKind << FDecl->getParamDecl(0) 4368 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4369 << SourceRange(Args[NumParams]->getLocStart(), 4370 Args.back()->getLocEnd()); 4371 else 4372 Diag(Args[NumParams]->getLocStart(), 4373 MinArgs == NumParams 4374 ? diag::err_typecheck_call_too_many_args 4375 : diag::err_typecheck_call_too_many_args_at_most) 4376 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4377 << Fn->getSourceRange() 4378 << SourceRange(Args[NumParams]->getLocStart(), 4379 Args.back()->getLocEnd()); 4380 4381 // Emit the location of the prototype. 4382 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4383 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4384 << FDecl; 4385 4386 // This deletes the extra arguments. 4387 Call->setNumArgs(Context, NumParams); 4388 return true; 4389 } 4390 } 4391 SmallVector<Expr *, 8> AllArgs; 4392 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4393 4394 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4395 Proto, 0, Args, AllArgs, CallType); 4396 if (Invalid) 4397 return true; 4398 unsigned TotalNumArgs = AllArgs.size(); 4399 for (unsigned i = 0; i < TotalNumArgs; ++i) 4400 Call->setArg(i, AllArgs[i]); 4401 4402 return false; 4403 } 4404 4405 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4406 const FunctionProtoType *Proto, 4407 unsigned FirstParam, ArrayRef<Expr *> Args, 4408 SmallVectorImpl<Expr *> &AllArgs, 4409 VariadicCallType CallType, bool AllowExplicit, 4410 bool IsListInitialization) { 4411 unsigned NumParams = Proto->getNumParams(); 4412 bool Invalid = false; 4413 unsigned ArgIx = 0; 4414 // Continue to check argument types (even if we have too few/many args). 4415 for (unsigned i = FirstParam; i < NumParams; i++) { 4416 QualType ProtoArgType = Proto->getParamType(i); 4417 4418 Expr *Arg; 4419 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4420 if (ArgIx < Args.size()) { 4421 Arg = Args[ArgIx++]; 4422 4423 if (RequireCompleteType(Arg->getLocStart(), 4424 ProtoArgType, 4425 diag::err_call_incomplete_argument, Arg)) 4426 return true; 4427 4428 // Strip the unbridged-cast placeholder expression off, if applicable. 4429 bool CFAudited = false; 4430 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4431 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4432 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4433 Arg = stripARCUnbridgedCast(Arg); 4434 else if (getLangOpts().ObjCAutoRefCount && 4435 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4436 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4437 CFAudited = true; 4438 4439 InitializedEntity Entity = 4440 Param ? InitializedEntity::InitializeParameter(Context, Param, 4441 ProtoArgType) 4442 : InitializedEntity::InitializeParameter( 4443 Context, ProtoArgType, Proto->isParamConsumed(i)); 4444 4445 // Remember that parameter belongs to a CF audited API. 4446 if (CFAudited) 4447 Entity.setParameterCFAudited(); 4448 4449 ExprResult ArgE = PerformCopyInitialization( 4450 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4451 if (ArgE.isInvalid()) 4452 return true; 4453 4454 Arg = ArgE.getAs<Expr>(); 4455 } else { 4456 assert(Param && "can't use default arguments without a known callee"); 4457 4458 ExprResult ArgExpr = 4459 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4460 if (ArgExpr.isInvalid()) 4461 return true; 4462 4463 Arg = ArgExpr.getAs<Expr>(); 4464 } 4465 4466 // Check for array bounds violations for each argument to the call. This 4467 // check only triggers warnings when the argument isn't a more complex Expr 4468 // with its own checking, such as a BinaryOperator. 4469 CheckArrayAccess(Arg); 4470 4471 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4472 CheckStaticArrayArgument(CallLoc, Param, Arg); 4473 4474 AllArgs.push_back(Arg); 4475 } 4476 4477 // If this is a variadic call, handle args passed through "...". 4478 if (CallType != VariadicDoesNotApply) { 4479 // Assume that extern "C" functions with variadic arguments that 4480 // return __unknown_anytype aren't *really* variadic. 4481 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4482 FDecl->isExternC()) { 4483 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4484 QualType paramType; // ignored 4485 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4486 Invalid |= arg.isInvalid(); 4487 AllArgs.push_back(arg.get()); 4488 } 4489 4490 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4491 } else { 4492 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4493 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4494 FDecl); 4495 Invalid |= Arg.isInvalid(); 4496 AllArgs.push_back(Arg.get()); 4497 } 4498 } 4499 4500 // Check for array bounds violations. 4501 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4502 CheckArrayAccess(Args[i]); 4503 } 4504 return Invalid; 4505 } 4506 4507 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4508 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4509 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4510 TL = DTL.getOriginalLoc(); 4511 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4512 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4513 << ATL.getLocalSourceRange(); 4514 } 4515 4516 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4517 /// array parameter, check that it is non-null, and that if it is formed by 4518 /// array-to-pointer decay, the underlying array is sufficiently large. 4519 /// 4520 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4521 /// array type derivation, then for each call to the function, the value of the 4522 /// corresponding actual argument shall provide access to the first element of 4523 /// an array with at least as many elements as specified by the size expression. 4524 void 4525 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4526 ParmVarDecl *Param, 4527 const Expr *ArgExpr) { 4528 // Static array parameters are not supported in C++. 4529 if (!Param || getLangOpts().CPlusPlus) 4530 return; 4531 4532 QualType OrigTy = Param->getOriginalType(); 4533 4534 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4535 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4536 return; 4537 4538 if (ArgExpr->isNullPointerConstant(Context, 4539 Expr::NPC_NeverValueDependent)) { 4540 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4541 DiagnoseCalleeStaticArrayParam(*this, Param); 4542 return; 4543 } 4544 4545 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4546 if (!CAT) 4547 return; 4548 4549 const ConstantArrayType *ArgCAT = 4550 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4551 if (!ArgCAT) 4552 return; 4553 4554 if (ArgCAT->getSize().ult(CAT->getSize())) { 4555 Diag(CallLoc, diag::warn_static_array_too_small) 4556 << ArgExpr->getSourceRange() 4557 << (unsigned) ArgCAT->getSize().getZExtValue() 4558 << (unsigned) CAT->getSize().getZExtValue(); 4559 DiagnoseCalleeStaticArrayParam(*this, Param); 4560 } 4561 } 4562 4563 /// Given a function expression of unknown-any type, try to rebuild it 4564 /// to have a function type. 4565 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4566 4567 /// Is the given type a placeholder that we need to lower out 4568 /// immediately during argument processing? 4569 static bool isPlaceholderToRemoveAsArg(QualType type) { 4570 // Placeholders are never sugared. 4571 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4572 if (!placeholder) return false; 4573 4574 switch (placeholder->getKind()) { 4575 // Ignore all the non-placeholder types. 4576 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4577 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4578 #include "clang/AST/BuiltinTypes.def" 4579 return false; 4580 4581 // We cannot lower out overload sets; they might validly be resolved 4582 // by the call machinery. 4583 case BuiltinType::Overload: 4584 return false; 4585 4586 // Unbridged casts in ARC can be handled in some call positions and 4587 // should be left in place. 4588 case BuiltinType::ARCUnbridgedCast: 4589 return false; 4590 4591 // Pseudo-objects should be converted as soon as possible. 4592 case BuiltinType::PseudoObject: 4593 return true; 4594 4595 // The debugger mode could theoretically but currently does not try 4596 // to resolve unknown-typed arguments based on known parameter types. 4597 case BuiltinType::UnknownAny: 4598 return true; 4599 4600 // These are always invalid as call arguments and should be reported. 4601 case BuiltinType::BoundMember: 4602 case BuiltinType::BuiltinFn: 4603 return true; 4604 } 4605 llvm_unreachable("bad builtin type kind"); 4606 } 4607 4608 /// Check an argument list for placeholders that we won't try to 4609 /// handle later. 4610 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4611 // Apply this processing to all the arguments at once instead of 4612 // dying at the first failure. 4613 bool hasInvalid = false; 4614 for (size_t i = 0, e = args.size(); i != e; i++) { 4615 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4616 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4617 if (result.isInvalid()) hasInvalid = true; 4618 else args[i] = result.get(); 4619 } else if (hasInvalid) { 4620 (void)S.CorrectDelayedTyposInExpr(args[i]); 4621 } 4622 } 4623 return hasInvalid; 4624 } 4625 4626 /// If a builtin function has a pointer argument with no explicit address 4627 /// space, than it should be able to accept a pointer to any address 4628 /// space as input. In order to do this, we need to replace the 4629 /// standard builtin declaration with one that uses the same address space 4630 /// as the call. 4631 /// 4632 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4633 /// it does not contain any pointer arguments without 4634 /// an address space qualifer. Otherwise the rewritten 4635 /// FunctionDecl is returned. 4636 /// TODO: Handle pointer return types. 4637 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4638 const FunctionDecl *FDecl, 4639 MultiExprArg ArgExprs) { 4640 4641 QualType DeclType = FDecl->getType(); 4642 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4643 4644 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4645 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4646 return nullptr; 4647 4648 bool NeedsNewDecl = false; 4649 unsigned i = 0; 4650 SmallVector<QualType, 8> OverloadParams; 4651 4652 for (QualType ParamType : FT->param_types()) { 4653 4654 // Convert array arguments to pointer to simplify type lookup. 4655 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4656 QualType ArgType = Arg->getType(); 4657 if (!ParamType->isPointerType() || 4658 ParamType.getQualifiers().hasAddressSpace() || 4659 !ArgType->isPointerType() || 4660 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4661 OverloadParams.push_back(ParamType); 4662 continue; 4663 } 4664 4665 NeedsNewDecl = true; 4666 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 4667 4668 QualType PointeeType = ParamType->getPointeeType(); 4669 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 4670 OverloadParams.push_back(Context.getPointerType(PointeeType)); 4671 } 4672 4673 if (!NeedsNewDecl) 4674 return nullptr; 4675 4676 FunctionProtoType::ExtProtoInfo EPI; 4677 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 4678 OverloadParams, EPI); 4679 DeclContext *Parent = Context.getTranslationUnitDecl(); 4680 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 4681 FDecl->getLocation(), 4682 FDecl->getLocation(), 4683 FDecl->getIdentifier(), 4684 OverloadTy, 4685 /*TInfo=*/nullptr, 4686 SC_Extern, false, 4687 /*hasPrototype=*/true); 4688 SmallVector<ParmVarDecl*, 16> Params; 4689 FT = cast<FunctionProtoType>(OverloadTy); 4690 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 4691 QualType ParamType = FT->getParamType(i); 4692 ParmVarDecl *Parm = 4693 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 4694 SourceLocation(), nullptr, ParamType, 4695 /*TInfo=*/nullptr, SC_None, nullptr); 4696 Parm->setScopeInfo(0, i); 4697 Params.push_back(Parm); 4698 } 4699 OverloadDecl->setParams(Params); 4700 return OverloadDecl; 4701 } 4702 4703 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4704 /// This provides the location of the left/right parens and a list of comma 4705 /// locations. 4706 ExprResult 4707 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4708 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4709 Expr *ExecConfig, bool IsExecConfig) { 4710 // Since this might be a postfix expression, get rid of ParenListExprs. 4711 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4712 if (Result.isInvalid()) return ExprError(); 4713 Fn = Result.get(); 4714 4715 if (checkArgsForPlaceholders(*this, ArgExprs)) 4716 return ExprError(); 4717 4718 if (getLangOpts().CPlusPlus) { 4719 // If this is a pseudo-destructor expression, build the call immediately. 4720 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4721 if (!ArgExprs.empty()) { 4722 // Pseudo-destructor calls should not have any arguments. 4723 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4724 << FixItHint::CreateRemoval( 4725 SourceRange(ArgExprs[0]->getLocStart(), 4726 ArgExprs.back()->getLocEnd())); 4727 } 4728 4729 return new (Context) 4730 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4731 } 4732 if (Fn->getType() == Context.PseudoObjectTy) { 4733 ExprResult result = CheckPlaceholderExpr(Fn); 4734 if (result.isInvalid()) return ExprError(); 4735 Fn = result.get(); 4736 } 4737 4738 // Determine whether this is a dependent call inside a C++ template, 4739 // in which case we won't do any semantic analysis now. 4740 // FIXME: Will need to cache the results of name lookup (including ADL) in 4741 // Fn. 4742 bool Dependent = false; 4743 if (Fn->isTypeDependent()) 4744 Dependent = true; 4745 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4746 Dependent = true; 4747 4748 if (Dependent) { 4749 if (ExecConfig) { 4750 return new (Context) CUDAKernelCallExpr( 4751 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4752 Context.DependentTy, VK_RValue, RParenLoc); 4753 } else { 4754 return new (Context) CallExpr( 4755 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4756 } 4757 } 4758 4759 // Determine whether this is a call to an object (C++ [over.call.object]). 4760 if (Fn->getType()->isRecordType()) 4761 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4762 RParenLoc); 4763 4764 if (Fn->getType() == Context.UnknownAnyTy) { 4765 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4766 if (result.isInvalid()) return ExprError(); 4767 Fn = result.get(); 4768 } 4769 4770 if (Fn->getType() == Context.BoundMemberTy) { 4771 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4772 } 4773 } 4774 4775 // Check for overloaded calls. This can happen even in C due to extensions. 4776 if (Fn->getType() == Context.OverloadTy) { 4777 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4778 4779 // We aren't supposed to apply this logic for if there's an '&' involved. 4780 if (!find.HasFormOfMemberPointer) { 4781 OverloadExpr *ovl = find.Expression; 4782 if (isa<UnresolvedLookupExpr>(ovl)) { 4783 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4784 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4785 RParenLoc, ExecConfig); 4786 } else { 4787 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4788 RParenLoc); 4789 } 4790 } 4791 } 4792 4793 // If we're directly calling a function, get the appropriate declaration. 4794 if (Fn->getType() == Context.UnknownAnyTy) { 4795 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4796 if (result.isInvalid()) return ExprError(); 4797 Fn = result.get(); 4798 } 4799 4800 Expr *NakedFn = Fn->IgnoreParens(); 4801 4802 NamedDecl *NDecl = nullptr; 4803 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4804 if (UnOp->getOpcode() == UO_AddrOf) 4805 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4806 4807 if (isa<DeclRefExpr>(NakedFn)) { 4808 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4809 4810 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 4811 if (FDecl && FDecl->getBuiltinID()) { 4812 // Rewrite the function decl for this builtin by replacing paramaters 4813 // with no explicit address space with the address space of the arguments 4814 // in ArgExprs. 4815 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 4816 NDecl = FDecl; 4817 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 4818 SourceLocation(), FDecl, false, 4819 SourceLocation(), FDecl->getType(), 4820 Fn->getValueKind(), FDecl); 4821 } 4822 } 4823 } else if (isa<MemberExpr>(NakedFn)) 4824 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4825 4826 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4827 if (FD->hasAttr<EnableIfAttr>()) { 4828 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4829 Diag(Fn->getLocStart(), 4830 isa<CXXMethodDecl>(FD) ? 4831 diag::err_ovl_no_viable_member_function_in_call : 4832 diag::err_ovl_no_viable_function_in_call) 4833 << FD << FD->getSourceRange(); 4834 Diag(FD->getLocation(), 4835 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4836 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4837 } 4838 } 4839 } 4840 4841 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4842 ExecConfig, IsExecConfig); 4843 } 4844 4845 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4846 /// 4847 /// __builtin_astype( value, dst type ) 4848 /// 4849 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4850 SourceLocation BuiltinLoc, 4851 SourceLocation RParenLoc) { 4852 ExprValueKind VK = VK_RValue; 4853 ExprObjectKind OK = OK_Ordinary; 4854 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4855 QualType SrcTy = E->getType(); 4856 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4857 return ExprError(Diag(BuiltinLoc, 4858 diag::err_invalid_astype_of_different_size) 4859 << DstTy 4860 << SrcTy 4861 << E->getSourceRange()); 4862 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4863 } 4864 4865 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4866 /// provided arguments. 4867 /// 4868 /// __builtin_convertvector( value, dst type ) 4869 /// 4870 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4871 SourceLocation BuiltinLoc, 4872 SourceLocation RParenLoc) { 4873 TypeSourceInfo *TInfo; 4874 GetTypeFromParser(ParsedDestTy, &TInfo); 4875 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4876 } 4877 4878 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4879 /// i.e. an expression not of \p OverloadTy. The expression should 4880 /// unary-convert to an expression of function-pointer or 4881 /// block-pointer type. 4882 /// 4883 /// \param NDecl the declaration being called, if available 4884 ExprResult 4885 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4886 SourceLocation LParenLoc, 4887 ArrayRef<Expr *> Args, 4888 SourceLocation RParenLoc, 4889 Expr *Config, bool IsExecConfig) { 4890 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4891 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4892 4893 // Promote the function operand. 4894 // We special-case function promotion here because we only allow promoting 4895 // builtin functions to function pointers in the callee of a call. 4896 ExprResult Result; 4897 if (BuiltinID && 4898 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4899 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4900 CK_BuiltinFnToFnPtr).get(); 4901 } else { 4902 Result = CallExprUnaryConversions(Fn); 4903 } 4904 if (Result.isInvalid()) 4905 return ExprError(); 4906 Fn = Result.get(); 4907 4908 // Make the call expr early, before semantic checks. This guarantees cleanup 4909 // of arguments and function on error. 4910 CallExpr *TheCall; 4911 if (Config) 4912 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4913 cast<CallExpr>(Config), Args, 4914 Context.BoolTy, VK_RValue, 4915 RParenLoc); 4916 else 4917 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4918 VK_RValue, RParenLoc); 4919 4920 // Bail out early if calling a builtin with custom typechecking. 4921 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4922 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 4923 4924 retry: 4925 const FunctionType *FuncT; 4926 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4927 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4928 // have type pointer to function". 4929 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4930 if (!FuncT) 4931 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4932 << Fn->getType() << Fn->getSourceRange()); 4933 } else if (const BlockPointerType *BPT = 4934 Fn->getType()->getAs<BlockPointerType>()) { 4935 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4936 } else { 4937 // Handle calls to expressions of unknown-any type. 4938 if (Fn->getType() == Context.UnknownAnyTy) { 4939 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4940 if (rewrite.isInvalid()) return ExprError(); 4941 Fn = rewrite.get(); 4942 TheCall->setCallee(Fn); 4943 goto retry; 4944 } 4945 4946 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4947 << Fn->getType() << Fn->getSourceRange()); 4948 } 4949 4950 if (getLangOpts().CUDA) { 4951 if (Config) { 4952 // CUDA: Kernel calls must be to global functions 4953 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4954 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4955 << FDecl->getName() << Fn->getSourceRange()); 4956 4957 // CUDA: Kernel function must have 'void' return type 4958 if (!FuncT->getReturnType()->isVoidType()) 4959 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4960 << Fn->getType() << Fn->getSourceRange()); 4961 } else { 4962 // CUDA: Calls to global functions must be configured 4963 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4964 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4965 << FDecl->getName() << Fn->getSourceRange()); 4966 } 4967 } 4968 4969 // Check for a valid return type 4970 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 4971 FDecl)) 4972 return ExprError(); 4973 4974 // We know the result type of the call, set it. 4975 TheCall->setType(FuncT->getCallResultType(Context)); 4976 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 4977 4978 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4979 if (Proto) { 4980 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4981 IsExecConfig)) 4982 return ExprError(); 4983 } else { 4984 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4985 4986 if (FDecl) { 4987 // Check if we have too few/too many template arguments, based 4988 // on our knowledge of the function definition. 4989 const FunctionDecl *Def = nullptr; 4990 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4991 Proto = Def->getType()->getAs<FunctionProtoType>(); 4992 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4993 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4994 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4995 } 4996 4997 // If the function we're calling isn't a function prototype, but we have 4998 // a function prototype from a prior declaratiom, use that prototype. 4999 if (!FDecl->hasPrototype()) 5000 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5001 } 5002 5003 // Promote the arguments (C99 6.5.2.2p6). 5004 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5005 Expr *Arg = Args[i]; 5006 5007 if (Proto && i < Proto->getNumParams()) { 5008 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5009 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5010 ExprResult ArgE = 5011 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5012 if (ArgE.isInvalid()) 5013 return true; 5014 5015 Arg = ArgE.getAs<Expr>(); 5016 5017 } else { 5018 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5019 5020 if (ArgE.isInvalid()) 5021 return true; 5022 5023 Arg = ArgE.getAs<Expr>(); 5024 } 5025 5026 if (RequireCompleteType(Arg->getLocStart(), 5027 Arg->getType(), 5028 diag::err_call_incomplete_argument, Arg)) 5029 return ExprError(); 5030 5031 TheCall->setArg(i, Arg); 5032 } 5033 } 5034 5035 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5036 if (!Method->isStatic()) 5037 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5038 << Fn->getSourceRange()); 5039 5040 // Check for sentinels 5041 if (NDecl) 5042 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5043 5044 // Do special checking on direct calls to functions. 5045 if (FDecl) { 5046 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5047 return ExprError(); 5048 5049 if (BuiltinID) 5050 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5051 } else if (NDecl) { 5052 if (CheckPointerCall(NDecl, TheCall, Proto)) 5053 return ExprError(); 5054 } else { 5055 if (CheckOtherCall(TheCall, Proto)) 5056 return ExprError(); 5057 } 5058 5059 return MaybeBindToTemporary(TheCall); 5060 } 5061 5062 ExprResult 5063 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5064 SourceLocation RParenLoc, Expr *InitExpr) { 5065 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5066 // FIXME: put back this assert when initializers are worked out. 5067 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 5068 5069 TypeSourceInfo *TInfo; 5070 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5071 if (!TInfo) 5072 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5073 5074 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5075 } 5076 5077 ExprResult 5078 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5079 SourceLocation RParenLoc, Expr *LiteralExpr) { 5080 QualType literalType = TInfo->getType(); 5081 5082 if (literalType->isArrayType()) { 5083 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5084 diag::err_illegal_decl_array_incomplete_type, 5085 SourceRange(LParenLoc, 5086 LiteralExpr->getSourceRange().getEnd()))) 5087 return ExprError(); 5088 if (literalType->isVariableArrayType()) 5089 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5090 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5091 } else if (!literalType->isDependentType() && 5092 RequireCompleteType(LParenLoc, literalType, 5093 diag::err_typecheck_decl_incomplete_type, 5094 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5095 return ExprError(); 5096 5097 InitializedEntity Entity 5098 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5099 InitializationKind Kind 5100 = InitializationKind::CreateCStyleCast(LParenLoc, 5101 SourceRange(LParenLoc, RParenLoc), 5102 /*InitList=*/true); 5103 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5104 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5105 &literalType); 5106 if (Result.isInvalid()) 5107 return ExprError(); 5108 LiteralExpr = Result.get(); 5109 5110 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5111 if (isFileScope && 5112 !LiteralExpr->isTypeDependent() && 5113 !LiteralExpr->isValueDependent() && 5114 !literalType->isDependentType()) { // 6.5.2.5p3 5115 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5116 return ExprError(); 5117 } 5118 5119 // In C, compound literals are l-values for some reason. 5120 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5121 5122 return MaybeBindToTemporary( 5123 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5124 VK, LiteralExpr, isFileScope)); 5125 } 5126 5127 ExprResult 5128 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5129 SourceLocation RBraceLoc) { 5130 // Immediately handle non-overload placeholders. Overloads can be 5131 // resolved contextually, but everything else here can't. 5132 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5133 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5134 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5135 5136 // Ignore failures; dropping the entire initializer list because 5137 // of one failure would be terrible for indexing/etc. 5138 if (result.isInvalid()) continue; 5139 5140 InitArgList[I] = result.get(); 5141 } 5142 } 5143 5144 // Semantic analysis for initializers is done by ActOnDeclarator() and 5145 // CheckInitializer() - it requires knowledge of the object being intialized. 5146 5147 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5148 RBraceLoc); 5149 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5150 return E; 5151 } 5152 5153 /// Do an explicit extend of the given block pointer if we're in ARC. 5154 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 5155 assert(E.get()->getType()->isBlockPointerType()); 5156 assert(E.get()->isRValue()); 5157 5158 // Only do this in an r-value context. 5159 if (!S.getLangOpts().ObjCAutoRefCount) return; 5160 5161 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 5162 CK_ARCExtendBlockObject, E.get(), 5163 /*base path*/ nullptr, VK_RValue); 5164 S.ExprNeedsCleanups = true; 5165 } 5166 5167 /// Prepare a conversion of the given expression to an ObjC object 5168 /// pointer type. 5169 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5170 QualType type = E.get()->getType(); 5171 if (type->isObjCObjectPointerType()) { 5172 return CK_BitCast; 5173 } else if (type->isBlockPointerType()) { 5174 maybeExtendBlockObject(*this, E); 5175 return CK_BlockPointerToObjCPointerCast; 5176 } else { 5177 assert(type->isPointerType()); 5178 return CK_CPointerToObjCPointerCast; 5179 } 5180 } 5181 5182 /// Prepares for a scalar cast, performing all the necessary stages 5183 /// except the final cast and returning the kind required. 5184 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5185 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5186 // Also, callers should have filtered out the invalid cases with 5187 // pointers. Everything else should be possible. 5188 5189 QualType SrcTy = Src.get()->getType(); 5190 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5191 return CK_NoOp; 5192 5193 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5194 case Type::STK_MemberPointer: 5195 llvm_unreachable("member pointer type in C"); 5196 5197 case Type::STK_CPointer: 5198 case Type::STK_BlockPointer: 5199 case Type::STK_ObjCObjectPointer: 5200 switch (DestTy->getScalarTypeKind()) { 5201 case Type::STK_CPointer: { 5202 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5203 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5204 if (SrcAS != DestAS) 5205 return CK_AddressSpaceConversion; 5206 return CK_BitCast; 5207 } 5208 case Type::STK_BlockPointer: 5209 return (SrcKind == Type::STK_BlockPointer 5210 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5211 case Type::STK_ObjCObjectPointer: 5212 if (SrcKind == Type::STK_ObjCObjectPointer) 5213 return CK_BitCast; 5214 if (SrcKind == Type::STK_CPointer) 5215 return CK_CPointerToObjCPointerCast; 5216 maybeExtendBlockObject(*this, Src); 5217 return CK_BlockPointerToObjCPointerCast; 5218 case Type::STK_Bool: 5219 return CK_PointerToBoolean; 5220 case Type::STK_Integral: 5221 return CK_PointerToIntegral; 5222 case Type::STK_Floating: 5223 case Type::STK_FloatingComplex: 5224 case Type::STK_IntegralComplex: 5225 case Type::STK_MemberPointer: 5226 llvm_unreachable("illegal cast from pointer"); 5227 } 5228 llvm_unreachable("Should have returned before this"); 5229 5230 case Type::STK_Bool: // casting from bool is like casting from an integer 5231 case Type::STK_Integral: 5232 switch (DestTy->getScalarTypeKind()) { 5233 case Type::STK_CPointer: 5234 case Type::STK_ObjCObjectPointer: 5235 case Type::STK_BlockPointer: 5236 if (Src.get()->isNullPointerConstant(Context, 5237 Expr::NPC_ValueDependentIsNull)) 5238 return CK_NullToPointer; 5239 return CK_IntegralToPointer; 5240 case Type::STK_Bool: 5241 return CK_IntegralToBoolean; 5242 case Type::STK_Integral: 5243 return CK_IntegralCast; 5244 case Type::STK_Floating: 5245 return CK_IntegralToFloating; 5246 case Type::STK_IntegralComplex: 5247 Src = ImpCastExprToType(Src.get(), 5248 DestTy->castAs<ComplexType>()->getElementType(), 5249 CK_IntegralCast); 5250 return CK_IntegralRealToComplex; 5251 case Type::STK_FloatingComplex: 5252 Src = ImpCastExprToType(Src.get(), 5253 DestTy->castAs<ComplexType>()->getElementType(), 5254 CK_IntegralToFloating); 5255 return CK_FloatingRealToComplex; 5256 case Type::STK_MemberPointer: 5257 llvm_unreachable("member pointer type in C"); 5258 } 5259 llvm_unreachable("Should have returned before this"); 5260 5261 case Type::STK_Floating: 5262 switch (DestTy->getScalarTypeKind()) { 5263 case Type::STK_Floating: 5264 return CK_FloatingCast; 5265 case Type::STK_Bool: 5266 return CK_FloatingToBoolean; 5267 case Type::STK_Integral: 5268 return CK_FloatingToIntegral; 5269 case Type::STK_FloatingComplex: 5270 Src = ImpCastExprToType(Src.get(), 5271 DestTy->castAs<ComplexType>()->getElementType(), 5272 CK_FloatingCast); 5273 return CK_FloatingRealToComplex; 5274 case Type::STK_IntegralComplex: 5275 Src = ImpCastExprToType(Src.get(), 5276 DestTy->castAs<ComplexType>()->getElementType(), 5277 CK_FloatingToIntegral); 5278 return CK_IntegralRealToComplex; 5279 case Type::STK_CPointer: 5280 case Type::STK_ObjCObjectPointer: 5281 case Type::STK_BlockPointer: 5282 llvm_unreachable("valid float->pointer cast?"); 5283 case Type::STK_MemberPointer: 5284 llvm_unreachable("member pointer type in C"); 5285 } 5286 llvm_unreachable("Should have returned before this"); 5287 5288 case Type::STK_FloatingComplex: 5289 switch (DestTy->getScalarTypeKind()) { 5290 case Type::STK_FloatingComplex: 5291 return CK_FloatingComplexCast; 5292 case Type::STK_IntegralComplex: 5293 return CK_FloatingComplexToIntegralComplex; 5294 case Type::STK_Floating: { 5295 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5296 if (Context.hasSameType(ET, DestTy)) 5297 return CK_FloatingComplexToReal; 5298 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5299 return CK_FloatingCast; 5300 } 5301 case Type::STK_Bool: 5302 return CK_FloatingComplexToBoolean; 5303 case Type::STK_Integral: 5304 Src = ImpCastExprToType(Src.get(), 5305 SrcTy->castAs<ComplexType>()->getElementType(), 5306 CK_FloatingComplexToReal); 5307 return CK_FloatingToIntegral; 5308 case Type::STK_CPointer: 5309 case Type::STK_ObjCObjectPointer: 5310 case Type::STK_BlockPointer: 5311 llvm_unreachable("valid complex float->pointer cast?"); 5312 case Type::STK_MemberPointer: 5313 llvm_unreachable("member pointer type in C"); 5314 } 5315 llvm_unreachable("Should have returned before this"); 5316 5317 case Type::STK_IntegralComplex: 5318 switch (DestTy->getScalarTypeKind()) { 5319 case Type::STK_FloatingComplex: 5320 return CK_IntegralComplexToFloatingComplex; 5321 case Type::STK_IntegralComplex: 5322 return CK_IntegralComplexCast; 5323 case Type::STK_Integral: { 5324 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5325 if (Context.hasSameType(ET, DestTy)) 5326 return CK_IntegralComplexToReal; 5327 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5328 return CK_IntegralCast; 5329 } 5330 case Type::STK_Bool: 5331 return CK_IntegralComplexToBoolean; 5332 case Type::STK_Floating: 5333 Src = ImpCastExprToType(Src.get(), 5334 SrcTy->castAs<ComplexType>()->getElementType(), 5335 CK_IntegralComplexToReal); 5336 return CK_IntegralToFloating; 5337 case Type::STK_CPointer: 5338 case Type::STK_ObjCObjectPointer: 5339 case Type::STK_BlockPointer: 5340 llvm_unreachable("valid complex int->pointer cast?"); 5341 case Type::STK_MemberPointer: 5342 llvm_unreachable("member pointer type in C"); 5343 } 5344 llvm_unreachable("Should have returned before this"); 5345 } 5346 5347 llvm_unreachable("Unhandled scalar cast"); 5348 } 5349 5350 static bool breakDownVectorType(QualType type, uint64_t &len, 5351 QualType &eltType) { 5352 // Vectors are simple. 5353 if (const VectorType *vecType = type->getAs<VectorType>()) { 5354 len = vecType->getNumElements(); 5355 eltType = vecType->getElementType(); 5356 assert(eltType->isScalarType()); 5357 return true; 5358 } 5359 5360 // We allow lax conversion to and from non-vector types, but only if 5361 // they're real types (i.e. non-complex, non-pointer scalar types). 5362 if (!type->isRealType()) return false; 5363 5364 len = 1; 5365 eltType = type; 5366 return true; 5367 } 5368 5369 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) { 5370 uint64_t srcLen, destLen; 5371 QualType srcElt, destElt; 5372 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 5373 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 5374 5375 // ASTContext::getTypeSize will return the size rounded up to a 5376 // power of 2, so instead of using that, we need to use the raw 5377 // element size multiplied by the element count. 5378 uint64_t srcEltSize = S.Context.getTypeSize(srcElt); 5379 uint64_t destEltSize = S.Context.getTypeSize(destElt); 5380 5381 return (srcLen * srcEltSize == destLen * destEltSize); 5382 } 5383 5384 /// Is this a legal conversion between two known vector types? 5385 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5386 assert(destTy->isVectorType() || srcTy->isVectorType()); 5387 5388 if (!Context.getLangOpts().LaxVectorConversions) 5389 return false; 5390 return VectorTypesMatch(*this, srcTy, destTy); 5391 } 5392 5393 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5394 CastKind &Kind) { 5395 assert(VectorTy->isVectorType() && "Not a vector type!"); 5396 5397 if (Ty->isVectorType() || Ty->isIntegerType()) { 5398 if (!VectorTypesMatch(*this, Ty, VectorTy)) 5399 return Diag(R.getBegin(), 5400 Ty->isVectorType() ? 5401 diag::err_invalid_conversion_between_vectors : 5402 diag::err_invalid_conversion_between_vector_and_integer) 5403 << VectorTy << Ty << R; 5404 } else 5405 return Diag(R.getBegin(), 5406 diag::err_invalid_conversion_between_vector_and_scalar) 5407 << VectorTy << Ty << R; 5408 5409 Kind = CK_BitCast; 5410 return false; 5411 } 5412 5413 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5414 Expr *CastExpr, CastKind &Kind) { 5415 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5416 5417 QualType SrcTy = CastExpr->getType(); 5418 5419 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5420 // an ExtVectorType. 5421 // In OpenCL, casts between vectors of different types are not allowed. 5422 // (See OpenCL 6.2). 5423 if (SrcTy->isVectorType()) { 5424 if (!VectorTypesMatch(*this, SrcTy, DestTy) 5425 || (getLangOpts().OpenCL && 5426 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5427 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5428 << DestTy << SrcTy << R; 5429 return ExprError(); 5430 } 5431 Kind = CK_BitCast; 5432 return CastExpr; 5433 } 5434 5435 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5436 // conversion will take place first from scalar to elt type, and then 5437 // splat from elt type to vector. 5438 if (SrcTy->isPointerType()) 5439 return Diag(R.getBegin(), 5440 diag::err_invalid_conversion_between_vector_and_scalar) 5441 << DestTy << SrcTy << R; 5442 5443 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5444 ExprResult CastExprRes = CastExpr; 5445 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5446 if (CastExprRes.isInvalid()) 5447 return ExprError(); 5448 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5449 5450 Kind = CK_VectorSplat; 5451 return CastExpr; 5452 } 5453 5454 ExprResult 5455 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5456 Declarator &D, ParsedType &Ty, 5457 SourceLocation RParenLoc, Expr *CastExpr) { 5458 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5459 "ActOnCastExpr(): missing type or expr"); 5460 5461 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5462 if (D.isInvalidType()) 5463 return ExprError(); 5464 5465 if (getLangOpts().CPlusPlus) { 5466 // Check that there are no default arguments (C++ only). 5467 CheckExtraCXXDefaultArguments(D); 5468 } else { 5469 // Make sure any TypoExprs have been dealt with. 5470 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5471 if (!Res.isUsable()) 5472 return ExprError(); 5473 CastExpr = Res.get(); 5474 } 5475 5476 checkUnusedDeclAttributes(D); 5477 5478 QualType castType = castTInfo->getType(); 5479 Ty = CreateParsedType(castType, castTInfo); 5480 5481 bool isVectorLiteral = false; 5482 5483 // Check for an altivec or OpenCL literal, 5484 // i.e. all the elements are integer constants. 5485 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5486 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5487 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5488 && castType->isVectorType() && (PE || PLE)) { 5489 if (PLE && PLE->getNumExprs() == 0) { 5490 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5491 return ExprError(); 5492 } 5493 if (PE || PLE->getNumExprs() == 1) { 5494 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5495 if (!E->getType()->isVectorType()) 5496 isVectorLiteral = true; 5497 } 5498 else 5499 isVectorLiteral = true; 5500 } 5501 5502 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5503 // then handle it as such. 5504 if (isVectorLiteral) 5505 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5506 5507 // If the Expr being casted is a ParenListExpr, handle it specially. 5508 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5509 // sequence of BinOp comma operators. 5510 if (isa<ParenListExpr>(CastExpr)) { 5511 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5512 if (Result.isInvalid()) return ExprError(); 5513 CastExpr = Result.get(); 5514 } 5515 5516 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5517 !getSourceManager().isInSystemMacro(LParenLoc)) 5518 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5519 5520 CheckTollFreeBridgeCast(castType, CastExpr); 5521 5522 CheckObjCBridgeRelatedCast(castType, CastExpr); 5523 5524 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5525 } 5526 5527 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5528 SourceLocation RParenLoc, Expr *E, 5529 TypeSourceInfo *TInfo) { 5530 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5531 "Expected paren or paren list expression"); 5532 5533 Expr **exprs; 5534 unsigned numExprs; 5535 Expr *subExpr; 5536 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5537 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5538 LiteralLParenLoc = PE->getLParenLoc(); 5539 LiteralRParenLoc = PE->getRParenLoc(); 5540 exprs = PE->getExprs(); 5541 numExprs = PE->getNumExprs(); 5542 } else { // isa<ParenExpr> by assertion at function entrance 5543 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5544 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5545 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5546 exprs = &subExpr; 5547 numExprs = 1; 5548 } 5549 5550 QualType Ty = TInfo->getType(); 5551 assert(Ty->isVectorType() && "Expected vector type"); 5552 5553 SmallVector<Expr *, 8> initExprs; 5554 const VectorType *VTy = Ty->getAs<VectorType>(); 5555 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5556 5557 // '(...)' form of vector initialization in AltiVec: the number of 5558 // initializers must be one or must match the size of the vector. 5559 // If a single value is specified in the initializer then it will be 5560 // replicated to all the components of the vector 5561 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5562 // The number of initializers must be one or must match the size of the 5563 // vector. If a single value is specified in the initializer then it will 5564 // be replicated to all the components of the vector 5565 if (numExprs == 1) { 5566 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5567 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5568 if (Literal.isInvalid()) 5569 return ExprError(); 5570 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5571 PrepareScalarCast(Literal, ElemTy)); 5572 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5573 } 5574 else if (numExprs < numElems) { 5575 Diag(E->getExprLoc(), 5576 diag::err_incorrect_number_of_vector_initializers); 5577 return ExprError(); 5578 } 5579 else 5580 initExprs.append(exprs, exprs + numExprs); 5581 } 5582 else { 5583 // For OpenCL, when the number of initializers is a single value, 5584 // it will be replicated to all components of the vector. 5585 if (getLangOpts().OpenCL && 5586 VTy->getVectorKind() == VectorType::GenericVector && 5587 numExprs == 1) { 5588 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5589 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5590 if (Literal.isInvalid()) 5591 return ExprError(); 5592 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5593 PrepareScalarCast(Literal, ElemTy)); 5594 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5595 } 5596 5597 initExprs.append(exprs, exprs + numExprs); 5598 } 5599 // FIXME: This means that pretty-printing the final AST will produce curly 5600 // braces instead of the original commas. 5601 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5602 initExprs, LiteralRParenLoc); 5603 initE->setType(Ty); 5604 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5605 } 5606 5607 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5608 /// the ParenListExpr into a sequence of comma binary operators. 5609 ExprResult 5610 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5611 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5612 if (!E) 5613 return OrigExpr; 5614 5615 ExprResult Result(E->getExpr(0)); 5616 5617 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5618 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5619 E->getExpr(i)); 5620 5621 if (Result.isInvalid()) return ExprError(); 5622 5623 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5624 } 5625 5626 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5627 SourceLocation R, 5628 MultiExprArg Val) { 5629 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5630 return expr; 5631 } 5632 5633 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5634 /// constant and the other is not a pointer. Returns true if a diagnostic is 5635 /// emitted. 5636 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5637 SourceLocation QuestionLoc) { 5638 Expr *NullExpr = LHSExpr; 5639 Expr *NonPointerExpr = RHSExpr; 5640 Expr::NullPointerConstantKind NullKind = 5641 NullExpr->isNullPointerConstant(Context, 5642 Expr::NPC_ValueDependentIsNotNull); 5643 5644 if (NullKind == Expr::NPCK_NotNull) { 5645 NullExpr = RHSExpr; 5646 NonPointerExpr = LHSExpr; 5647 NullKind = 5648 NullExpr->isNullPointerConstant(Context, 5649 Expr::NPC_ValueDependentIsNotNull); 5650 } 5651 5652 if (NullKind == Expr::NPCK_NotNull) 5653 return false; 5654 5655 if (NullKind == Expr::NPCK_ZeroExpression) 5656 return false; 5657 5658 if (NullKind == Expr::NPCK_ZeroLiteral) { 5659 // In this case, check to make sure that we got here from a "NULL" 5660 // string in the source code. 5661 NullExpr = NullExpr->IgnoreParenImpCasts(); 5662 SourceLocation loc = NullExpr->getExprLoc(); 5663 if (!findMacroSpelling(loc, "NULL")) 5664 return false; 5665 } 5666 5667 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5668 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5669 << NonPointerExpr->getType() << DiagType 5670 << NonPointerExpr->getSourceRange(); 5671 return true; 5672 } 5673 5674 /// \brief Return false if the condition expression is valid, true otherwise. 5675 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 5676 QualType CondTy = Cond->getType(); 5677 5678 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 5679 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 5680 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 5681 << CondTy << Cond->getSourceRange(); 5682 return true; 5683 } 5684 5685 // C99 6.5.15p2 5686 if (CondTy->isScalarType()) return false; 5687 5688 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 5689 << CondTy << Cond->getSourceRange(); 5690 return true; 5691 } 5692 5693 /// \brief Handle when one or both operands are void type. 5694 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5695 ExprResult &RHS) { 5696 Expr *LHSExpr = LHS.get(); 5697 Expr *RHSExpr = RHS.get(); 5698 5699 if (!LHSExpr->getType()->isVoidType()) 5700 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5701 << RHSExpr->getSourceRange(); 5702 if (!RHSExpr->getType()->isVoidType()) 5703 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5704 << LHSExpr->getSourceRange(); 5705 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5706 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5707 return S.Context.VoidTy; 5708 } 5709 5710 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5711 /// true otherwise. 5712 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5713 QualType PointerTy) { 5714 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5715 !NullExpr.get()->isNullPointerConstant(S.Context, 5716 Expr::NPC_ValueDependentIsNull)) 5717 return true; 5718 5719 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5720 return false; 5721 } 5722 5723 /// \brief Checks compatibility between two pointers and return the resulting 5724 /// type. 5725 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5726 ExprResult &RHS, 5727 SourceLocation Loc) { 5728 QualType LHSTy = LHS.get()->getType(); 5729 QualType RHSTy = RHS.get()->getType(); 5730 5731 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5732 // Two identical pointers types are always compatible. 5733 return LHSTy; 5734 } 5735 5736 QualType lhptee, rhptee; 5737 5738 // Get the pointee types. 5739 bool IsBlockPointer = false; 5740 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5741 lhptee = LHSBTy->getPointeeType(); 5742 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5743 IsBlockPointer = true; 5744 } else { 5745 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5746 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5747 } 5748 5749 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5750 // differently qualified versions of compatible types, the result type is 5751 // a pointer to an appropriately qualified version of the composite 5752 // type. 5753 5754 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5755 // clause doesn't make sense for our extensions. E.g. address space 2 should 5756 // be incompatible with address space 3: they may live on different devices or 5757 // anything. 5758 Qualifiers lhQual = lhptee.getQualifiers(); 5759 Qualifiers rhQual = rhptee.getQualifiers(); 5760 5761 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5762 lhQual.removeCVRQualifiers(); 5763 rhQual.removeCVRQualifiers(); 5764 5765 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5766 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5767 5768 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5769 5770 if (CompositeTy.isNull()) { 5771 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 5772 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5773 << RHS.get()->getSourceRange(); 5774 // In this situation, we assume void* type. No especially good 5775 // reason, but this is what gcc does, and we do have to pick 5776 // to get a consistent AST. 5777 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5778 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5779 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5780 return incompatTy; 5781 } 5782 5783 // The pointer types are compatible. 5784 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5785 if (IsBlockPointer) 5786 ResultTy = S.Context.getBlockPointerType(ResultTy); 5787 else 5788 ResultTy = S.Context.getPointerType(ResultTy); 5789 5790 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5791 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5792 return ResultTy; 5793 } 5794 5795 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or 5796 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally 5797 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else). 5798 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) { 5799 if (QT->isObjCIdType()) 5800 return true; 5801 5802 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>(); 5803 if (!OPT) 5804 return false; 5805 5806 if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl()) 5807 if (ID->getIdentifier() != &C.Idents.get("NSObject")) 5808 return false; 5809 5810 ObjCProtocolDecl* PNSCopying = 5811 S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation()); 5812 ObjCProtocolDecl* PNSObject = 5813 S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation()); 5814 5815 for (auto *Proto : OPT->quals()) { 5816 if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) || 5817 (PNSObject && declaresSameEntity(Proto, PNSObject))) 5818 ; 5819 else 5820 return false; 5821 } 5822 return true; 5823 } 5824 5825 /// \brief Return the resulting type when the operands are both block pointers. 5826 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5827 ExprResult &LHS, 5828 ExprResult &RHS, 5829 SourceLocation Loc) { 5830 QualType LHSTy = LHS.get()->getType(); 5831 QualType RHSTy = RHS.get()->getType(); 5832 5833 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5834 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5835 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5836 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5837 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5838 return destType; 5839 } 5840 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5841 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5842 << RHS.get()->getSourceRange(); 5843 return QualType(); 5844 } 5845 5846 // We have 2 block pointer types. 5847 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5848 } 5849 5850 /// \brief Return the resulting type when the operands are both pointers. 5851 static QualType 5852 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5853 ExprResult &RHS, 5854 SourceLocation Loc) { 5855 // get the pointer types 5856 QualType LHSTy = LHS.get()->getType(); 5857 QualType RHSTy = RHS.get()->getType(); 5858 5859 // get the "pointed to" types 5860 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5861 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5862 5863 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5864 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5865 // Figure out necessary qualifiers (C99 6.5.15p6) 5866 QualType destPointee 5867 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5868 QualType destType = S.Context.getPointerType(destPointee); 5869 // Add qualifiers if necessary. 5870 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 5871 // Promote to void*. 5872 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5873 return destType; 5874 } 5875 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5876 QualType destPointee 5877 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5878 QualType destType = S.Context.getPointerType(destPointee); 5879 // Add qualifiers if necessary. 5880 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 5881 // Promote to void*. 5882 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5883 return destType; 5884 } 5885 5886 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5887 } 5888 5889 /// \brief Return false if the first expression is not an integer and the second 5890 /// expression is not a pointer, true otherwise. 5891 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5892 Expr* PointerExpr, SourceLocation Loc, 5893 bool IsIntFirstExpr) { 5894 if (!PointerExpr->getType()->isPointerType() || 5895 !Int.get()->getType()->isIntegerType()) 5896 return false; 5897 5898 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5899 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5900 5901 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 5902 << Expr1->getType() << Expr2->getType() 5903 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5904 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 5905 CK_IntegralToPointer); 5906 return true; 5907 } 5908 5909 /// \brief Simple conversion between integer and floating point types. 5910 /// 5911 /// Used when handling the OpenCL conditional operator where the 5912 /// condition is a vector while the other operands are scalar. 5913 /// 5914 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 5915 /// types are either integer or floating type. Between the two 5916 /// operands, the type with the higher rank is defined as the "result 5917 /// type". The other operand needs to be promoted to the same type. No 5918 /// other type promotion is allowed. We cannot use 5919 /// UsualArithmeticConversions() for this purpose, since it always 5920 /// promotes promotable types. 5921 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 5922 ExprResult &RHS, 5923 SourceLocation QuestionLoc) { 5924 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 5925 if (LHS.isInvalid()) 5926 return QualType(); 5927 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 5928 if (RHS.isInvalid()) 5929 return QualType(); 5930 5931 // For conversion purposes, we ignore any qualifiers. 5932 // For example, "const float" and "float" are equivalent. 5933 QualType LHSType = 5934 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 5935 QualType RHSType = 5936 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 5937 5938 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 5939 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 5940 << LHSType << LHS.get()->getSourceRange(); 5941 return QualType(); 5942 } 5943 5944 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 5945 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 5946 << RHSType << RHS.get()->getSourceRange(); 5947 return QualType(); 5948 } 5949 5950 // If both types are identical, no conversion is needed. 5951 if (LHSType == RHSType) 5952 return LHSType; 5953 5954 // Now handle "real" floating types (i.e. float, double, long double). 5955 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 5956 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 5957 /*IsCompAssign = */ false); 5958 5959 // Finally, we have two differing integer types. 5960 return handleIntegerConversion<doIntegralCast, doIntegralCast> 5961 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 5962 } 5963 5964 /// \brief Convert scalar operands to a vector that matches the 5965 /// condition in length. 5966 /// 5967 /// Used when handling the OpenCL conditional operator where the 5968 /// condition is a vector while the other operands are scalar. 5969 /// 5970 /// We first compute the "result type" for the scalar operands 5971 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 5972 /// into a vector of that type where the length matches the condition 5973 /// vector type. s6.11.6 requires that the element types of the result 5974 /// and the condition must have the same number of bits. 5975 static QualType 5976 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 5977 QualType CondTy, SourceLocation QuestionLoc) { 5978 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 5979 if (ResTy.isNull()) return QualType(); 5980 5981 const VectorType *CV = CondTy->getAs<VectorType>(); 5982 assert(CV); 5983 5984 // Determine the vector result type 5985 unsigned NumElements = CV->getNumElements(); 5986 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 5987 5988 // Ensure that all types have the same number of bits 5989 if (S.Context.getTypeSize(CV->getElementType()) 5990 != S.Context.getTypeSize(ResTy)) { 5991 // Since VectorTy is created internally, it does not pretty print 5992 // with an OpenCL name. Instead, we just print a description. 5993 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 5994 SmallString<64> Str; 5995 llvm::raw_svector_ostream OS(Str); 5996 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 5997 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 5998 << CondTy << OS.str(); 5999 return QualType(); 6000 } 6001 6002 // Convert operands to the vector result type 6003 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6004 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6005 6006 return VectorTy; 6007 } 6008 6009 /// \brief Return false if this is a valid OpenCL condition vector 6010 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6011 SourceLocation QuestionLoc) { 6012 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6013 // integral type. 6014 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6015 assert(CondTy); 6016 QualType EleTy = CondTy->getElementType(); 6017 if (EleTy->isIntegerType()) return false; 6018 6019 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6020 << Cond->getType() << Cond->getSourceRange(); 6021 return true; 6022 } 6023 6024 /// \brief Return false if the vector condition type and the vector 6025 /// result type are compatible. 6026 /// 6027 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6028 /// number of elements, and their element types have the same number 6029 /// of bits. 6030 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6031 SourceLocation QuestionLoc) { 6032 const VectorType *CV = CondTy->getAs<VectorType>(); 6033 const VectorType *RV = VecResTy->getAs<VectorType>(); 6034 assert(CV && RV); 6035 6036 if (CV->getNumElements() != RV->getNumElements()) { 6037 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6038 << CondTy << VecResTy; 6039 return true; 6040 } 6041 6042 QualType CVE = CV->getElementType(); 6043 QualType RVE = RV->getElementType(); 6044 6045 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6046 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6047 << CondTy << VecResTy; 6048 return true; 6049 } 6050 6051 return false; 6052 } 6053 6054 /// \brief Return the resulting type for the conditional operator in 6055 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6056 /// s6.3.i) when the condition is a vector type. 6057 static QualType 6058 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6059 ExprResult &LHS, ExprResult &RHS, 6060 SourceLocation QuestionLoc) { 6061 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6062 if (Cond.isInvalid()) 6063 return QualType(); 6064 QualType CondTy = Cond.get()->getType(); 6065 6066 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6067 return QualType(); 6068 6069 // If either operand is a vector then find the vector type of the 6070 // result as specified in OpenCL v1.1 s6.3.i. 6071 if (LHS.get()->getType()->isVectorType() || 6072 RHS.get()->getType()->isVectorType()) { 6073 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6074 /*isCompAssign*/false); 6075 if (VecResTy.isNull()) return QualType(); 6076 // The result type must match the condition type as specified in 6077 // OpenCL v1.1 s6.11.6. 6078 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6079 return QualType(); 6080 return VecResTy; 6081 } 6082 6083 // Both operands are scalar. 6084 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6085 } 6086 6087 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6088 /// In that case, LHS = cond. 6089 /// C99 6.5.15 6090 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6091 ExprResult &RHS, ExprValueKind &VK, 6092 ExprObjectKind &OK, 6093 SourceLocation QuestionLoc) { 6094 6095 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6096 if (!LHSResult.isUsable()) return QualType(); 6097 LHS = LHSResult; 6098 6099 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6100 if (!RHSResult.isUsable()) return QualType(); 6101 RHS = RHSResult; 6102 6103 // C++ is sufficiently different to merit its own checker. 6104 if (getLangOpts().CPlusPlus) 6105 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6106 6107 VK = VK_RValue; 6108 OK = OK_Ordinary; 6109 6110 // The OpenCL operator with a vector condition is sufficiently 6111 // different to merit its own checker. 6112 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6113 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6114 6115 // First, check the condition. 6116 Cond = UsualUnaryConversions(Cond.get()); 6117 if (Cond.isInvalid()) 6118 return QualType(); 6119 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6120 return QualType(); 6121 6122 // Now check the two expressions. 6123 if (LHS.get()->getType()->isVectorType() || 6124 RHS.get()->getType()->isVectorType()) 6125 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 6126 6127 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6128 if (LHS.isInvalid() || RHS.isInvalid()) 6129 return QualType(); 6130 6131 QualType LHSTy = LHS.get()->getType(); 6132 QualType RHSTy = RHS.get()->getType(); 6133 6134 // If both operands have arithmetic type, do the usual arithmetic conversions 6135 // to find a common type: C99 6.5.15p3,5. 6136 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6137 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6138 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6139 6140 return ResTy; 6141 } 6142 6143 // If both operands are the same structure or union type, the result is that 6144 // type. 6145 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6146 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6147 if (LHSRT->getDecl() == RHSRT->getDecl()) 6148 // "If both the operands have structure or union type, the result has 6149 // that type." This implies that CV qualifiers are dropped. 6150 return LHSTy.getUnqualifiedType(); 6151 // FIXME: Type of conditional expression must be complete in C mode. 6152 } 6153 6154 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6155 // The following || allows only one side to be void (a GCC-ism). 6156 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6157 return checkConditionalVoidType(*this, LHS, RHS); 6158 } 6159 6160 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6161 // the type of the other operand." 6162 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6163 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6164 6165 // All objective-c pointer type analysis is done here. 6166 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6167 QuestionLoc); 6168 if (LHS.isInvalid() || RHS.isInvalid()) 6169 return QualType(); 6170 if (!compositeType.isNull()) 6171 return compositeType; 6172 6173 6174 // Handle block pointer types. 6175 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6176 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6177 QuestionLoc); 6178 6179 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6180 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6181 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6182 QuestionLoc); 6183 6184 // GCC compatibility: soften pointer/integer mismatch. Note that 6185 // null pointers have been filtered out by this point. 6186 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6187 /*isIntFirstExpr=*/true)) 6188 return RHSTy; 6189 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6190 /*isIntFirstExpr=*/false)) 6191 return LHSTy; 6192 6193 // Emit a better diagnostic if one of the expressions is a null pointer 6194 // constant and the other is not a pointer type. In this case, the user most 6195 // likely forgot to take the address of the other expression. 6196 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6197 return QualType(); 6198 6199 // Otherwise, the operands are not compatible. 6200 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6201 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6202 << RHS.get()->getSourceRange(); 6203 return QualType(); 6204 } 6205 6206 /// FindCompositeObjCPointerType - Helper method to find composite type of 6207 /// two objective-c pointer types of the two input expressions. 6208 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6209 SourceLocation QuestionLoc) { 6210 QualType LHSTy = LHS.get()->getType(); 6211 QualType RHSTy = RHS.get()->getType(); 6212 6213 // Handle things like Class and struct objc_class*. Here we case the result 6214 // to the pseudo-builtin, because that will be implicitly cast back to the 6215 // redefinition type if an attempt is made to access its fields. 6216 if (LHSTy->isObjCClassType() && 6217 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6218 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6219 return LHSTy; 6220 } 6221 if (RHSTy->isObjCClassType() && 6222 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6223 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6224 return RHSTy; 6225 } 6226 // And the same for struct objc_object* / id 6227 if (LHSTy->isObjCIdType() && 6228 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6229 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6230 return LHSTy; 6231 } 6232 if (RHSTy->isObjCIdType() && 6233 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6234 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6235 return RHSTy; 6236 } 6237 // And the same for struct objc_selector* / SEL 6238 if (Context.isObjCSelType(LHSTy) && 6239 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6240 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6241 return LHSTy; 6242 } 6243 if (Context.isObjCSelType(RHSTy) && 6244 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6245 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6246 return RHSTy; 6247 } 6248 // Check constraints for Objective-C object pointers types. 6249 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6250 6251 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6252 // Two identical object pointer types are always compatible. 6253 return LHSTy; 6254 } 6255 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6256 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6257 QualType compositeType = LHSTy; 6258 6259 // If both operands are interfaces and either operand can be 6260 // assigned to the other, use that type as the composite 6261 // type. This allows 6262 // xxx ? (A*) a : (B*) b 6263 // where B is a subclass of A. 6264 // 6265 // Additionally, as for assignment, if either type is 'id' 6266 // allow silent coercion. Finally, if the types are 6267 // incompatible then make sure to use 'id' as the composite 6268 // type so the result is acceptable for sending messages to. 6269 6270 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6271 // It could return the composite type. 6272 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6273 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6274 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6275 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6276 } else if ((LHSTy->isObjCQualifiedIdType() || 6277 RHSTy->isObjCQualifiedIdType()) && 6278 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6279 // Need to handle "id<xx>" explicitly. 6280 // GCC allows qualified id and any Objective-C type to devolve to 6281 // id. Currently localizing to here until clear this should be 6282 // part of ObjCQualifiedIdTypesAreCompatible. 6283 compositeType = Context.getObjCIdType(); 6284 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6285 compositeType = Context.getObjCIdType(); 6286 } else if (!(compositeType = 6287 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 6288 ; 6289 else { 6290 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6291 << LHSTy << RHSTy 6292 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6293 QualType incompatTy = Context.getObjCIdType(); 6294 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6295 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6296 return incompatTy; 6297 } 6298 // The object pointer types are compatible. 6299 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6300 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6301 return compositeType; 6302 } 6303 // Check Objective-C object pointer types and 'void *' 6304 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6305 if (getLangOpts().ObjCAutoRefCount) { 6306 // ARC forbids the implicit conversion of object pointers to 'void *', 6307 // so these types are not compatible. 6308 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6309 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6310 LHS = RHS = true; 6311 return QualType(); 6312 } 6313 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6314 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6315 QualType destPointee 6316 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6317 QualType destType = Context.getPointerType(destPointee); 6318 // Add qualifiers if necessary. 6319 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6320 // Promote to void*. 6321 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6322 return destType; 6323 } 6324 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6325 if (getLangOpts().ObjCAutoRefCount) { 6326 // ARC forbids the implicit conversion of object pointers to 'void *', 6327 // so these types are not compatible. 6328 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6329 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6330 LHS = RHS = true; 6331 return QualType(); 6332 } 6333 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6334 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6335 QualType destPointee 6336 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6337 QualType destType = Context.getPointerType(destPointee); 6338 // Add qualifiers if necessary. 6339 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6340 // Promote to void*. 6341 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6342 return destType; 6343 } 6344 return QualType(); 6345 } 6346 6347 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6348 /// ParenRange in parentheses. 6349 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6350 const PartialDiagnostic &Note, 6351 SourceRange ParenRange) { 6352 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 6353 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6354 EndLoc.isValid()) { 6355 Self.Diag(Loc, Note) 6356 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6357 << FixItHint::CreateInsertion(EndLoc, ")"); 6358 } else { 6359 // We can't display the parentheses, so just show the bare note. 6360 Self.Diag(Loc, Note) << ParenRange; 6361 } 6362 } 6363 6364 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6365 return Opc >= BO_Mul && Opc <= BO_Shr; 6366 } 6367 6368 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6369 /// expression, either using a built-in or overloaded operator, 6370 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6371 /// expression. 6372 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6373 Expr **RHSExprs) { 6374 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6375 E = E->IgnoreImpCasts(); 6376 E = E->IgnoreConversionOperator(); 6377 E = E->IgnoreImpCasts(); 6378 6379 // Built-in binary operator. 6380 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6381 if (IsArithmeticOp(OP->getOpcode())) { 6382 *Opcode = OP->getOpcode(); 6383 *RHSExprs = OP->getRHS(); 6384 return true; 6385 } 6386 } 6387 6388 // Overloaded operator. 6389 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6390 if (Call->getNumArgs() != 2) 6391 return false; 6392 6393 // Make sure this is really a binary operator that is safe to pass into 6394 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6395 OverloadedOperatorKind OO = Call->getOperator(); 6396 if (OO < OO_Plus || OO > OO_Arrow || 6397 OO == OO_PlusPlus || OO == OO_MinusMinus) 6398 return false; 6399 6400 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6401 if (IsArithmeticOp(OpKind)) { 6402 *Opcode = OpKind; 6403 *RHSExprs = Call->getArg(1); 6404 return true; 6405 } 6406 } 6407 6408 return false; 6409 } 6410 6411 static bool IsLogicOp(BinaryOperatorKind Opc) { 6412 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 6413 } 6414 6415 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6416 /// or is a logical expression such as (x==y) which has int type, but is 6417 /// commonly interpreted as boolean. 6418 static bool ExprLooksBoolean(Expr *E) { 6419 E = E->IgnoreParenImpCasts(); 6420 6421 if (E->getType()->isBooleanType()) 6422 return true; 6423 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6424 return IsLogicOp(OP->getOpcode()); 6425 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6426 return OP->getOpcode() == UO_LNot; 6427 if (E->getType()->isPointerType()) 6428 return true; 6429 6430 return false; 6431 } 6432 6433 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6434 /// and binary operator are mixed in a way that suggests the programmer assumed 6435 /// the conditional operator has higher precedence, for example: 6436 /// "int x = a + someBinaryCondition ? 1 : 2". 6437 static void DiagnoseConditionalPrecedence(Sema &Self, 6438 SourceLocation OpLoc, 6439 Expr *Condition, 6440 Expr *LHSExpr, 6441 Expr *RHSExpr) { 6442 BinaryOperatorKind CondOpcode; 6443 Expr *CondRHS; 6444 6445 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6446 return; 6447 if (!ExprLooksBoolean(CondRHS)) 6448 return; 6449 6450 // The condition is an arithmetic binary expression, with a right- 6451 // hand side that looks boolean, so warn. 6452 6453 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6454 << Condition->getSourceRange() 6455 << BinaryOperator::getOpcodeStr(CondOpcode); 6456 6457 SuggestParentheses(Self, OpLoc, 6458 Self.PDiag(diag::note_precedence_silence) 6459 << BinaryOperator::getOpcodeStr(CondOpcode), 6460 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6461 6462 SuggestParentheses(Self, OpLoc, 6463 Self.PDiag(diag::note_precedence_conditional_first), 6464 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6465 } 6466 6467 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6468 /// in the case of a the GNU conditional expr extension. 6469 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6470 SourceLocation ColonLoc, 6471 Expr *CondExpr, Expr *LHSExpr, 6472 Expr *RHSExpr) { 6473 if (!getLangOpts().CPlusPlus) { 6474 // C cannot handle TypoExpr nodes in the condition because it 6475 // doesn't handle dependent types properly, so make sure any TypoExprs have 6476 // been dealt with before checking the operands. 6477 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6478 if (!CondResult.isUsable()) return ExprError(); 6479 CondExpr = CondResult.get(); 6480 } 6481 6482 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6483 // was the condition. 6484 OpaqueValueExpr *opaqueValue = nullptr; 6485 Expr *commonExpr = nullptr; 6486 if (!LHSExpr) { 6487 commonExpr = CondExpr; 6488 // Lower out placeholder types first. This is important so that we don't 6489 // try to capture a placeholder. This happens in few cases in C++; such 6490 // as Objective-C++'s dictionary subscripting syntax. 6491 if (commonExpr->hasPlaceholderType()) { 6492 ExprResult result = CheckPlaceholderExpr(commonExpr); 6493 if (!result.isUsable()) return ExprError(); 6494 commonExpr = result.get(); 6495 } 6496 // We usually want to apply unary conversions *before* saving, except 6497 // in the special case of a C++ l-value conditional. 6498 if (!(getLangOpts().CPlusPlus 6499 && !commonExpr->isTypeDependent() 6500 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6501 && commonExpr->isGLValue() 6502 && commonExpr->isOrdinaryOrBitFieldObject() 6503 && RHSExpr->isOrdinaryOrBitFieldObject() 6504 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6505 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6506 if (commonRes.isInvalid()) 6507 return ExprError(); 6508 commonExpr = commonRes.get(); 6509 } 6510 6511 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6512 commonExpr->getType(), 6513 commonExpr->getValueKind(), 6514 commonExpr->getObjectKind(), 6515 commonExpr); 6516 LHSExpr = CondExpr = opaqueValue; 6517 } 6518 6519 ExprValueKind VK = VK_RValue; 6520 ExprObjectKind OK = OK_Ordinary; 6521 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6522 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6523 VK, OK, QuestionLoc); 6524 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6525 RHS.isInvalid()) 6526 return ExprError(); 6527 6528 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6529 RHS.get()); 6530 6531 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6532 6533 if (!commonExpr) 6534 return new (Context) 6535 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6536 RHS.get(), result, VK, OK); 6537 6538 return new (Context) BinaryConditionalOperator( 6539 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6540 ColonLoc, result, VK, OK); 6541 } 6542 6543 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6544 // being closely modeled after the C99 spec:-). The odd characteristic of this 6545 // routine is it effectively iqnores the qualifiers on the top level pointee. 6546 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6547 // FIXME: add a couple examples in this comment. 6548 static Sema::AssignConvertType 6549 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6550 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6551 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6552 6553 // get the "pointed to" type (ignoring qualifiers at the top level) 6554 const Type *lhptee, *rhptee; 6555 Qualifiers lhq, rhq; 6556 std::tie(lhptee, lhq) = 6557 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6558 std::tie(rhptee, rhq) = 6559 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6560 6561 Sema::AssignConvertType ConvTy = Sema::Compatible; 6562 6563 // C99 6.5.16.1p1: This following citation is common to constraints 6564 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6565 // qualifiers of the type *pointed to* by the right; 6566 6567 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6568 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6569 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6570 // Ignore lifetime for further calculation. 6571 lhq.removeObjCLifetime(); 6572 rhq.removeObjCLifetime(); 6573 } 6574 6575 if (!lhq.compatiblyIncludes(rhq)) { 6576 // Treat address-space mismatches as fatal. TODO: address subspaces 6577 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6578 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6579 6580 // It's okay to add or remove GC or lifetime qualifiers when converting to 6581 // and from void*. 6582 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6583 .compatiblyIncludes( 6584 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6585 && (lhptee->isVoidType() || rhptee->isVoidType())) 6586 ; // keep old 6587 6588 // Treat lifetime mismatches as fatal. 6589 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6590 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6591 6592 // For GCC compatibility, other qualifier mismatches are treated 6593 // as still compatible in C. 6594 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6595 } 6596 6597 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6598 // incomplete type and the other is a pointer to a qualified or unqualified 6599 // version of void... 6600 if (lhptee->isVoidType()) { 6601 if (rhptee->isIncompleteOrObjectType()) 6602 return ConvTy; 6603 6604 // As an extension, we allow cast to/from void* to function pointer. 6605 assert(rhptee->isFunctionType()); 6606 return Sema::FunctionVoidPointer; 6607 } 6608 6609 if (rhptee->isVoidType()) { 6610 if (lhptee->isIncompleteOrObjectType()) 6611 return ConvTy; 6612 6613 // As an extension, we allow cast to/from void* to function pointer. 6614 assert(lhptee->isFunctionType()); 6615 return Sema::FunctionVoidPointer; 6616 } 6617 6618 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6619 // unqualified versions of compatible types, ... 6620 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6621 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6622 // Check if the pointee types are compatible ignoring the sign. 6623 // We explicitly check for char so that we catch "char" vs 6624 // "unsigned char" on systems where "char" is unsigned. 6625 if (lhptee->isCharType()) 6626 ltrans = S.Context.UnsignedCharTy; 6627 else if (lhptee->hasSignedIntegerRepresentation()) 6628 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6629 6630 if (rhptee->isCharType()) 6631 rtrans = S.Context.UnsignedCharTy; 6632 else if (rhptee->hasSignedIntegerRepresentation()) 6633 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6634 6635 if (ltrans == rtrans) { 6636 // Types are compatible ignoring the sign. Qualifier incompatibility 6637 // takes priority over sign incompatibility because the sign 6638 // warning can be disabled. 6639 if (ConvTy != Sema::Compatible) 6640 return ConvTy; 6641 6642 return Sema::IncompatiblePointerSign; 6643 } 6644 6645 // If we are a multi-level pointer, it's possible that our issue is simply 6646 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6647 // the eventual target type is the same and the pointers have the same 6648 // level of indirection, this must be the issue. 6649 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6650 do { 6651 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6652 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6653 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6654 6655 if (lhptee == rhptee) 6656 return Sema::IncompatibleNestedPointerQualifiers; 6657 } 6658 6659 // General pointer incompatibility takes priority over qualifiers. 6660 return Sema::IncompatiblePointer; 6661 } 6662 if (!S.getLangOpts().CPlusPlus && 6663 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6664 return Sema::IncompatiblePointer; 6665 return ConvTy; 6666 } 6667 6668 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6669 /// block pointer types are compatible or whether a block and normal pointer 6670 /// are compatible. It is more restrict than comparing two function pointer 6671 // types. 6672 static Sema::AssignConvertType 6673 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6674 QualType RHSType) { 6675 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6676 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6677 6678 QualType lhptee, rhptee; 6679 6680 // get the "pointed to" type (ignoring qualifiers at the top level) 6681 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6682 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6683 6684 // In C++, the types have to match exactly. 6685 if (S.getLangOpts().CPlusPlus) 6686 return Sema::IncompatibleBlockPointer; 6687 6688 Sema::AssignConvertType ConvTy = Sema::Compatible; 6689 6690 // For blocks we enforce that qualifiers are identical. 6691 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6692 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6693 6694 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6695 return Sema::IncompatibleBlockPointer; 6696 6697 return ConvTy; 6698 } 6699 6700 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6701 /// for assignment compatibility. 6702 static Sema::AssignConvertType 6703 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6704 QualType RHSType) { 6705 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6706 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6707 6708 if (LHSType->isObjCBuiltinType()) { 6709 // Class is not compatible with ObjC object pointers. 6710 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6711 !RHSType->isObjCQualifiedClassType()) 6712 return Sema::IncompatiblePointer; 6713 return Sema::Compatible; 6714 } 6715 if (RHSType->isObjCBuiltinType()) { 6716 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6717 !LHSType->isObjCQualifiedClassType()) 6718 return Sema::IncompatiblePointer; 6719 return Sema::Compatible; 6720 } 6721 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6722 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6723 6724 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6725 // make an exception for id<P> 6726 !LHSType->isObjCQualifiedIdType()) 6727 return Sema::CompatiblePointerDiscardsQualifiers; 6728 6729 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6730 return Sema::Compatible; 6731 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6732 return Sema::IncompatibleObjCQualifiedId; 6733 return Sema::IncompatiblePointer; 6734 } 6735 6736 Sema::AssignConvertType 6737 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6738 QualType LHSType, QualType RHSType) { 6739 // Fake up an opaque expression. We don't actually care about what 6740 // cast operations are required, so if CheckAssignmentConstraints 6741 // adds casts to this they'll be wasted, but fortunately that doesn't 6742 // usually happen on valid code. 6743 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6744 ExprResult RHSPtr = &RHSExpr; 6745 CastKind K = CK_Invalid; 6746 6747 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6748 } 6749 6750 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6751 /// has code to accommodate several GCC extensions when type checking 6752 /// pointers. Here are some objectionable examples that GCC considers warnings: 6753 /// 6754 /// int a, *pint; 6755 /// short *pshort; 6756 /// struct foo *pfoo; 6757 /// 6758 /// pint = pshort; // warning: assignment from incompatible pointer type 6759 /// a = pint; // warning: assignment makes integer from pointer without a cast 6760 /// pint = a; // warning: assignment makes pointer from integer without a cast 6761 /// pint = pfoo; // warning: assignment from incompatible pointer type 6762 /// 6763 /// As a result, the code for dealing with pointers is more complex than the 6764 /// C99 spec dictates. 6765 /// 6766 /// Sets 'Kind' for any result kind except Incompatible. 6767 Sema::AssignConvertType 6768 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6769 CastKind &Kind) { 6770 QualType RHSType = RHS.get()->getType(); 6771 QualType OrigLHSType = LHSType; 6772 6773 // Get canonical types. We're not formatting these types, just comparing 6774 // them. 6775 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6776 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6777 6778 // Common case: no conversion required. 6779 if (LHSType == RHSType) { 6780 Kind = CK_NoOp; 6781 return Compatible; 6782 } 6783 6784 // If we have an atomic type, try a non-atomic assignment, then just add an 6785 // atomic qualification step. 6786 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6787 Sema::AssignConvertType result = 6788 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6789 if (result != Compatible) 6790 return result; 6791 if (Kind != CK_NoOp) 6792 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 6793 Kind = CK_NonAtomicToAtomic; 6794 return Compatible; 6795 } 6796 6797 // If the left-hand side is a reference type, then we are in a 6798 // (rare!) case where we've allowed the use of references in C, 6799 // e.g., as a parameter type in a built-in function. In this case, 6800 // just make sure that the type referenced is compatible with the 6801 // right-hand side type. The caller is responsible for adjusting 6802 // LHSType so that the resulting expression does not have reference 6803 // type. 6804 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6805 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6806 Kind = CK_LValueBitCast; 6807 return Compatible; 6808 } 6809 return Incompatible; 6810 } 6811 6812 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6813 // to the same ExtVector type. 6814 if (LHSType->isExtVectorType()) { 6815 if (RHSType->isExtVectorType()) 6816 return Incompatible; 6817 if (RHSType->isArithmeticType()) { 6818 // CK_VectorSplat does T -> vector T, so first cast to the 6819 // element type. 6820 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6821 if (elType != RHSType) { 6822 Kind = PrepareScalarCast(RHS, elType); 6823 RHS = ImpCastExprToType(RHS.get(), elType, Kind); 6824 } 6825 Kind = CK_VectorSplat; 6826 return Compatible; 6827 } 6828 } 6829 6830 // Conversions to or from vector type. 6831 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6832 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6833 // Allow assignments of an AltiVec vector type to an equivalent GCC 6834 // vector type and vice versa 6835 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6836 Kind = CK_BitCast; 6837 return Compatible; 6838 } 6839 6840 // If we are allowing lax vector conversions, and LHS and RHS are both 6841 // vectors, the total size only needs to be the same. This is a bitcast; 6842 // no bits are changed but the result type is different. 6843 if (isLaxVectorConversion(RHSType, LHSType)) { 6844 Kind = CK_BitCast; 6845 return IncompatibleVectors; 6846 } 6847 } 6848 return Incompatible; 6849 } 6850 6851 // Arithmetic conversions. 6852 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6853 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6854 Kind = PrepareScalarCast(RHS, LHSType); 6855 return Compatible; 6856 } 6857 6858 // Conversions to normal pointers. 6859 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6860 // U* -> T* 6861 if (isa<PointerType>(RHSType)) { 6862 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 6863 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 6864 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 6865 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6866 } 6867 6868 // int -> T* 6869 if (RHSType->isIntegerType()) { 6870 Kind = CK_IntegralToPointer; // FIXME: null? 6871 return IntToPointer; 6872 } 6873 6874 // C pointers are not compatible with ObjC object pointers, 6875 // with two exceptions: 6876 if (isa<ObjCObjectPointerType>(RHSType)) { 6877 // - conversions to void* 6878 if (LHSPointer->getPointeeType()->isVoidType()) { 6879 Kind = CK_BitCast; 6880 return Compatible; 6881 } 6882 6883 // - conversions from 'Class' to the redefinition type 6884 if (RHSType->isObjCClassType() && 6885 Context.hasSameType(LHSType, 6886 Context.getObjCClassRedefinitionType())) { 6887 Kind = CK_BitCast; 6888 return Compatible; 6889 } 6890 6891 Kind = CK_BitCast; 6892 return IncompatiblePointer; 6893 } 6894 6895 // U^ -> void* 6896 if (RHSType->getAs<BlockPointerType>()) { 6897 if (LHSPointer->getPointeeType()->isVoidType()) { 6898 Kind = CK_BitCast; 6899 return Compatible; 6900 } 6901 } 6902 6903 return Incompatible; 6904 } 6905 6906 // Conversions to block pointers. 6907 if (isa<BlockPointerType>(LHSType)) { 6908 // U^ -> T^ 6909 if (RHSType->isBlockPointerType()) { 6910 Kind = CK_BitCast; 6911 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6912 } 6913 6914 // int or null -> T^ 6915 if (RHSType->isIntegerType()) { 6916 Kind = CK_IntegralToPointer; // FIXME: null 6917 return IntToBlockPointer; 6918 } 6919 6920 // id -> T^ 6921 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6922 Kind = CK_AnyPointerToBlockPointerCast; 6923 return Compatible; 6924 } 6925 6926 // void* -> T^ 6927 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6928 if (RHSPT->getPointeeType()->isVoidType()) { 6929 Kind = CK_AnyPointerToBlockPointerCast; 6930 return Compatible; 6931 } 6932 6933 return Incompatible; 6934 } 6935 6936 // Conversions to Objective-C pointers. 6937 if (isa<ObjCObjectPointerType>(LHSType)) { 6938 // A* -> B* 6939 if (RHSType->isObjCObjectPointerType()) { 6940 Kind = CK_BitCast; 6941 Sema::AssignConvertType result = 6942 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6943 if (getLangOpts().ObjCAutoRefCount && 6944 result == Compatible && 6945 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6946 result = IncompatibleObjCWeakRef; 6947 return result; 6948 } 6949 6950 // int or null -> A* 6951 if (RHSType->isIntegerType()) { 6952 Kind = CK_IntegralToPointer; // FIXME: null 6953 return IntToPointer; 6954 } 6955 6956 // In general, C pointers are not compatible with ObjC object pointers, 6957 // with two exceptions: 6958 if (isa<PointerType>(RHSType)) { 6959 Kind = CK_CPointerToObjCPointerCast; 6960 6961 // - conversions from 'void*' 6962 if (RHSType->isVoidPointerType()) { 6963 return Compatible; 6964 } 6965 6966 // - conversions to 'Class' from its redefinition type 6967 if (LHSType->isObjCClassType() && 6968 Context.hasSameType(RHSType, 6969 Context.getObjCClassRedefinitionType())) { 6970 return Compatible; 6971 } 6972 6973 return IncompatiblePointer; 6974 } 6975 6976 // Only under strict condition T^ is compatible with an Objective-C pointer. 6977 if (RHSType->isBlockPointerType() && 6978 isObjCPtrBlockCompatible(*this, Context, LHSType)) { 6979 maybeExtendBlockObject(*this, RHS); 6980 Kind = CK_BlockPointerToObjCPointerCast; 6981 return Compatible; 6982 } 6983 6984 return Incompatible; 6985 } 6986 6987 // Conversions from pointers that are not covered by the above. 6988 if (isa<PointerType>(RHSType)) { 6989 // T* -> _Bool 6990 if (LHSType == Context.BoolTy) { 6991 Kind = CK_PointerToBoolean; 6992 return Compatible; 6993 } 6994 6995 // T* -> int 6996 if (LHSType->isIntegerType()) { 6997 Kind = CK_PointerToIntegral; 6998 return PointerToInt; 6999 } 7000 7001 return Incompatible; 7002 } 7003 7004 // Conversions from Objective-C pointers that are not covered by the above. 7005 if (isa<ObjCObjectPointerType>(RHSType)) { 7006 // T* -> _Bool 7007 if (LHSType == Context.BoolTy) { 7008 Kind = CK_PointerToBoolean; 7009 return Compatible; 7010 } 7011 7012 // T* -> int 7013 if (LHSType->isIntegerType()) { 7014 Kind = CK_PointerToIntegral; 7015 return PointerToInt; 7016 } 7017 7018 return Incompatible; 7019 } 7020 7021 // struct A -> struct B 7022 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7023 if (Context.typesAreCompatible(LHSType, RHSType)) { 7024 Kind = CK_NoOp; 7025 return Compatible; 7026 } 7027 } 7028 7029 return Incompatible; 7030 } 7031 7032 /// \brief Constructs a transparent union from an expression that is 7033 /// used to initialize the transparent union. 7034 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7035 ExprResult &EResult, QualType UnionType, 7036 FieldDecl *Field) { 7037 // Build an initializer list that designates the appropriate member 7038 // of the transparent union. 7039 Expr *E = EResult.get(); 7040 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7041 E, SourceLocation()); 7042 Initializer->setType(UnionType); 7043 Initializer->setInitializedFieldInUnion(Field); 7044 7045 // Build a compound literal constructing a value of the transparent 7046 // union type from this initializer list. 7047 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7048 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7049 VK_RValue, Initializer, false); 7050 } 7051 7052 Sema::AssignConvertType 7053 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7054 ExprResult &RHS) { 7055 QualType RHSType = RHS.get()->getType(); 7056 7057 // If the ArgType is a Union type, we want to handle a potential 7058 // transparent_union GCC extension. 7059 const RecordType *UT = ArgType->getAsUnionType(); 7060 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7061 return Incompatible; 7062 7063 // The field to initialize within the transparent union. 7064 RecordDecl *UD = UT->getDecl(); 7065 FieldDecl *InitField = nullptr; 7066 // It's compatible if the expression matches any of the fields. 7067 for (auto *it : UD->fields()) { 7068 if (it->getType()->isPointerType()) { 7069 // If the transparent union contains a pointer type, we allow: 7070 // 1) void pointer 7071 // 2) null pointer constant 7072 if (RHSType->isPointerType()) 7073 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7074 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7075 InitField = it; 7076 break; 7077 } 7078 7079 if (RHS.get()->isNullPointerConstant(Context, 7080 Expr::NPC_ValueDependentIsNull)) { 7081 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7082 CK_NullToPointer); 7083 InitField = it; 7084 break; 7085 } 7086 } 7087 7088 CastKind Kind = CK_Invalid; 7089 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7090 == Compatible) { 7091 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7092 InitField = it; 7093 break; 7094 } 7095 } 7096 7097 if (!InitField) 7098 return Incompatible; 7099 7100 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7101 return Compatible; 7102 } 7103 7104 Sema::AssignConvertType 7105 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7106 bool Diagnose, 7107 bool DiagnoseCFAudited) { 7108 if (getLangOpts().CPlusPlus) { 7109 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7110 // C++ 5.17p3: If the left operand is not of class type, the 7111 // expression is implicitly converted (C++ 4) to the 7112 // cv-unqualified type of the left operand. 7113 ExprResult Res; 7114 if (Diagnose) { 7115 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7116 AA_Assigning); 7117 } else { 7118 ImplicitConversionSequence ICS = 7119 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7120 /*SuppressUserConversions=*/false, 7121 /*AllowExplicit=*/false, 7122 /*InOverloadResolution=*/false, 7123 /*CStyle=*/false, 7124 /*AllowObjCWritebackConversion=*/false); 7125 if (ICS.isFailure()) 7126 return Incompatible; 7127 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7128 ICS, AA_Assigning); 7129 } 7130 if (Res.isInvalid()) 7131 return Incompatible; 7132 Sema::AssignConvertType result = Compatible; 7133 if (getLangOpts().ObjCAutoRefCount && 7134 !CheckObjCARCUnavailableWeakConversion(LHSType, 7135 RHS.get()->getType())) 7136 result = IncompatibleObjCWeakRef; 7137 RHS = Res; 7138 return result; 7139 } 7140 7141 // FIXME: Currently, we fall through and treat C++ classes like C 7142 // structures. 7143 // FIXME: We also fall through for atomics; not sure what should 7144 // happen there, though. 7145 } 7146 7147 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7148 // a null pointer constant. 7149 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7150 LHSType->isBlockPointerType()) && 7151 RHS.get()->isNullPointerConstant(Context, 7152 Expr::NPC_ValueDependentIsNull)) { 7153 CastKind Kind; 7154 CXXCastPath Path; 7155 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 7156 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7157 return Compatible; 7158 } 7159 7160 // This check seems unnatural, however it is necessary to ensure the proper 7161 // conversion of functions/arrays. If the conversion were done for all 7162 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7163 // expressions that suppress this implicit conversion (&, sizeof). 7164 // 7165 // Suppress this for references: C++ 8.5.3p5. 7166 if (!LHSType->isReferenceType()) { 7167 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7168 if (RHS.isInvalid()) 7169 return Incompatible; 7170 } 7171 7172 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7173 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) { 7174 ObjCProtocolDecl *PDecl = OPE->getProtocol(); 7175 if (PDecl && !PDecl->hasDefinition()) { 7176 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7177 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7178 } 7179 } 7180 7181 CastKind Kind = CK_Invalid; 7182 Sema::AssignConvertType result = 7183 CheckAssignmentConstraints(LHSType, RHS, Kind); 7184 7185 // C99 6.5.16.1p2: The value of the right operand is converted to the 7186 // type of the assignment expression. 7187 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7188 // so that we can use references in built-in functions even in C. 7189 // The getNonReferenceType() call makes sure that the resulting expression 7190 // does not have reference type. 7191 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7192 QualType Ty = LHSType.getNonLValueExprType(Context); 7193 Expr *E = RHS.get(); 7194 if (getLangOpts().ObjCAutoRefCount) 7195 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7196 DiagnoseCFAudited); 7197 if (getLangOpts().ObjC1 && 7198 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 7199 LHSType, E->getType(), E) || 7200 ConversionToObjCStringLiteralCheck(LHSType, E))) { 7201 RHS = E; 7202 return Compatible; 7203 } 7204 7205 RHS = ImpCastExprToType(E, Ty, Kind); 7206 } 7207 return result; 7208 } 7209 7210 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7211 ExprResult &RHS) { 7212 Diag(Loc, diag::err_typecheck_invalid_operands) 7213 << LHS.get()->getType() << RHS.get()->getType() 7214 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7215 return QualType(); 7216 } 7217 7218 /// Try to convert a value of non-vector type to a vector type by converting 7219 /// the type to the element type of the vector and then performing a splat. 7220 /// If the language is OpenCL, we only use conversions that promote scalar 7221 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7222 /// for float->int. 7223 /// 7224 /// \param scalar - if non-null, actually perform the conversions 7225 /// \return true if the operation fails (but without diagnosing the failure) 7226 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7227 QualType scalarTy, 7228 QualType vectorEltTy, 7229 QualType vectorTy) { 7230 // The conversion to apply to the scalar before splatting it, 7231 // if necessary. 7232 CastKind scalarCast = CK_Invalid; 7233 7234 if (vectorEltTy->isIntegralType(S.Context)) { 7235 if (!scalarTy->isIntegralType(S.Context)) 7236 return true; 7237 if (S.getLangOpts().OpenCL && 7238 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7239 return true; 7240 scalarCast = CK_IntegralCast; 7241 } else if (vectorEltTy->isRealFloatingType()) { 7242 if (scalarTy->isRealFloatingType()) { 7243 if (S.getLangOpts().OpenCL && 7244 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7245 return true; 7246 scalarCast = CK_FloatingCast; 7247 } 7248 else if (scalarTy->isIntegralType(S.Context)) 7249 scalarCast = CK_IntegralToFloating; 7250 else 7251 return true; 7252 } else { 7253 return true; 7254 } 7255 7256 // Adjust scalar if desired. 7257 if (scalar) { 7258 if (scalarCast != CK_Invalid) 7259 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7260 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7261 } 7262 return false; 7263 } 7264 7265 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7266 SourceLocation Loc, bool IsCompAssign) { 7267 if (!IsCompAssign) { 7268 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7269 if (LHS.isInvalid()) 7270 return QualType(); 7271 } 7272 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7273 if (RHS.isInvalid()) 7274 return QualType(); 7275 7276 // For conversion purposes, we ignore any qualifiers. 7277 // For example, "const float" and "float" are equivalent. 7278 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7279 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7280 7281 // If the vector types are identical, return. 7282 if (Context.hasSameType(LHSType, RHSType)) 7283 return LHSType; 7284 7285 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7286 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7287 assert(LHSVecType || RHSVecType); 7288 7289 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7290 if (LHSVecType && RHSVecType && 7291 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7292 if (isa<ExtVectorType>(LHSVecType)) { 7293 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7294 return LHSType; 7295 } 7296 7297 if (!IsCompAssign) 7298 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7299 return RHSType; 7300 } 7301 7302 // If there's an ext-vector type and a scalar, try to convert the scalar to 7303 // the vector element type and splat. 7304 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7305 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7306 LHSVecType->getElementType(), LHSType)) 7307 return LHSType; 7308 } 7309 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7310 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7311 LHSType, RHSVecType->getElementType(), 7312 RHSType)) 7313 return RHSType; 7314 } 7315 7316 // If we're allowing lax vector conversions, only the total (data) size 7317 // needs to be the same. 7318 // FIXME: Should we really be allowing this? 7319 // FIXME: We really just pick the LHS type arbitrarily? 7320 if (isLaxVectorConversion(RHSType, LHSType)) { 7321 QualType resultType = LHSType; 7322 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7323 return resultType; 7324 } 7325 7326 // Okay, the expression is invalid. 7327 7328 // If there's a non-vector, non-real operand, diagnose that. 7329 if ((!RHSVecType && !RHSType->isRealType()) || 7330 (!LHSVecType && !LHSType->isRealType())) { 7331 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7332 << LHSType << RHSType 7333 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7334 return QualType(); 7335 } 7336 7337 // Otherwise, use the generic diagnostic. 7338 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7339 << LHSType << RHSType 7340 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7341 return QualType(); 7342 } 7343 7344 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7345 // expression. These are mainly cases where the null pointer is used as an 7346 // integer instead of a pointer. 7347 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7348 SourceLocation Loc, bool IsCompare) { 7349 // The canonical way to check for a GNU null is with isNullPointerConstant, 7350 // but we use a bit of a hack here for speed; this is a relatively 7351 // hot path, and isNullPointerConstant is slow. 7352 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7353 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7354 7355 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7356 7357 // Avoid analyzing cases where the result will either be invalid (and 7358 // diagnosed as such) or entirely valid and not something to warn about. 7359 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7360 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7361 return; 7362 7363 // Comparison operations would not make sense with a null pointer no matter 7364 // what the other expression is. 7365 if (!IsCompare) { 7366 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7367 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7368 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7369 return; 7370 } 7371 7372 // The rest of the operations only make sense with a null pointer 7373 // if the other expression is a pointer. 7374 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7375 NonNullType->canDecayToPointerType()) 7376 return; 7377 7378 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7379 << LHSNull /* LHS is NULL */ << NonNullType 7380 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7381 } 7382 7383 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7384 SourceLocation Loc, 7385 bool IsCompAssign, bool IsDiv) { 7386 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7387 7388 if (LHS.get()->getType()->isVectorType() || 7389 RHS.get()->getType()->isVectorType()) 7390 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7391 7392 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7393 if (LHS.isInvalid() || RHS.isInvalid()) 7394 return QualType(); 7395 7396 7397 if (compType.isNull() || !compType->isArithmeticType()) 7398 return InvalidOperands(Loc, LHS, RHS); 7399 7400 // Check for division by zero. 7401 llvm::APSInt RHSValue; 7402 if (IsDiv && !RHS.get()->isValueDependent() && 7403 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 7404 DiagRuntimeBehavior(Loc, RHS.get(), 7405 PDiag(diag::warn_division_by_zero) 7406 << RHS.get()->getSourceRange()); 7407 7408 return compType; 7409 } 7410 7411 QualType Sema::CheckRemainderOperands( 7412 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7413 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7414 7415 if (LHS.get()->getType()->isVectorType() || 7416 RHS.get()->getType()->isVectorType()) { 7417 if (LHS.get()->getType()->hasIntegerRepresentation() && 7418 RHS.get()->getType()->hasIntegerRepresentation()) 7419 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7420 return InvalidOperands(Loc, LHS, RHS); 7421 } 7422 7423 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7424 if (LHS.isInvalid() || RHS.isInvalid()) 7425 return QualType(); 7426 7427 if (compType.isNull() || !compType->isIntegerType()) 7428 return InvalidOperands(Loc, LHS, RHS); 7429 7430 // Check for remainder by zero. 7431 llvm::APSInt RHSValue; 7432 if (!RHS.get()->isValueDependent() && 7433 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 7434 DiagRuntimeBehavior(Loc, RHS.get(), 7435 PDiag(diag::warn_remainder_by_zero) 7436 << RHS.get()->getSourceRange()); 7437 7438 return compType; 7439 } 7440 7441 /// \brief Diagnose invalid arithmetic on two void pointers. 7442 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7443 Expr *LHSExpr, Expr *RHSExpr) { 7444 S.Diag(Loc, S.getLangOpts().CPlusPlus 7445 ? diag::err_typecheck_pointer_arith_void_type 7446 : diag::ext_gnu_void_ptr) 7447 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7448 << RHSExpr->getSourceRange(); 7449 } 7450 7451 /// \brief Diagnose invalid arithmetic on a void pointer. 7452 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7453 Expr *Pointer) { 7454 S.Diag(Loc, S.getLangOpts().CPlusPlus 7455 ? diag::err_typecheck_pointer_arith_void_type 7456 : diag::ext_gnu_void_ptr) 7457 << 0 /* one pointer */ << Pointer->getSourceRange(); 7458 } 7459 7460 /// \brief Diagnose invalid arithmetic on two function pointers. 7461 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7462 Expr *LHS, Expr *RHS) { 7463 assert(LHS->getType()->isAnyPointerType()); 7464 assert(RHS->getType()->isAnyPointerType()); 7465 S.Diag(Loc, S.getLangOpts().CPlusPlus 7466 ? diag::err_typecheck_pointer_arith_function_type 7467 : diag::ext_gnu_ptr_func_arith) 7468 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7469 // We only show the second type if it differs from the first. 7470 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7471 RHS->getType()) 7472 << RHS->getType()->getPointeeType() 7473 << LHS->getSourceRange() << RHS->getSourceRange(); 7474 } 7475 7476 /// \brief Diagnose invalid arithmetic on a function pointer. 7477 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7478 Expr *Pointer) { 7479 assert(Pointer->getType()->isAnyPointerType()); 7480 S.Diag(Loc, S.getLangOpts().CPlusPlus 7481 ? diag::err_typecheck_pointer_arith_function_type 7482 : diag::ext_gnu_ptr_func_arith) 7483 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7484 << 0 /* one pointer, so only one type */ 7485 << Pointer->getSourceRange(); 7486 } 7487 7488 /// \brief Emit error if Operand is incomplete pointer type 7489 /// 7490 /// \returns True if pointer has incomplete type 7491 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7492 Expr *Operand) { 7493 QualType ResType = Operand->getType(); 7494 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7495 ResType = ResAtomicType->getValueType(); 7496 7497 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7498 QualType PointeeTy = ResType->getPointeeType(); 7499 return S.RequireCompleteType(Loc, PointeeTy, 7500 diag::err_typecheck_arithmetic_incomplete_type, 7501 PointeeTy, Operand->getSourceRange()); 7502 } 7503 7504 /// \brief Check the validity of an arithmetic pointer operand. 7505 /// 7506 /// If the operand has pointer type, this code will check for pointer types 7507 /// which are invalid in arithmetic operations. These will be diagnosed 7508 /// appropriately, including whether or not the use is supported as an 7509 /// extension. 7510 /// 7511 /// \returns True when the operand is valid to use (even if as an extension). 7512 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7513 Expr *Operand) { 7514 QualType ResType = Operand->getType(); 7515 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7516 ResType = ResAtomicType->getValueType(); 7517 7518 if (!ResType->isAnyPointerType()) return true; 7519 7520 QualType PointeeTy = ResType->getPointeeType(); 7521 if (PointeeTy->isVoidType()) { 7522 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7523 return !S.getLangOpts().CPlusPlus; 7524 } 7525 if (PointeeTy->isFunctionType()) { 7526 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7527 return !S.getLangOpts().CPlusPlus; 7528 } 7529 7530 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7531 7532 return true; 7533 } 7534 7535 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7536 /// operands. 7537 /// 7538 /// This routine will diagnose any invalid arithmetic on pointer operands much 7539 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7540 /// for emitting a single diagnostic even for operations where both LHS and RHS 7541 /// are (potentially problematic) pointers. 7542 /// 7543 /// \returns True when the operand is valid to use (even if as an extension). 7544 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7545 Expr *LHSExpr, Expr *RHSExpr) { 7546 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7547 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7548 if (!isLHSPointer && !isRHSPointer) return true; 7549 7550 QualType LHSPointeeTy, RHSPointeeTy; 7551 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7552 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7553 7554 // if both are pointers check if operation is valid wrt address spaces 7555 if (isLHSPointer && isRHSPointer) { 7556 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 7557 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 7558 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 7559 S.Diag(Loc, 7560 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7561 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 7562 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7563 return false; 7564 } 7565 } 7566 7567 // Check for arithmetic on pointers to incomplete types. 7568 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7569 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7570 if (isLHSVoidPtr || isRHSVoidPtr) { 7571 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7572 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7573 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7574 7575 return !S.getLangOpts().CPlusPlus; 7576 } 7577 7578 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7579 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7580 if (isLHSFuncPtr || isRHSFuncPtr) { 7581 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7582 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7583 RHSExpr); 7584 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7585 7586 return !S.getLangOpts().CPlusPlus; 7587 } 7588 7589 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7590 return false; 7591 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7592 return false; 7593 7594 return true; 7595 } 7596 7597 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7598 /// literal. 7599 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7600 Expr *LHSExpr, Expr *RHSExpr) { 7601 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7602 Expr* IndexExpr = RHSExpr; 7603 if (!StrExpr) { 7604 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7605 IndexExpr = LHSExpr; 7606 } 7607 7608 bool IsStringPlusInt = StrExpr && 7609 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7610 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 7611 return; 7612 7613 llvm::APSInt index; 7614 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7615 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7616 if (index.isNonNegative() && 7617 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7618 index.isUnsigned())) 7619 return; 7620 } 7621 7622 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7623 Self.Diag(OpLoc, diag::warn_string_plus_int) 7624 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7625 7626 // Only print a fixit for "str" + int, not for int + "str". 7627 if (IndexExpr == RHSExpr) { 7628 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7629 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7630 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7631 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7632 << FixItHint::CreateInsertion(EndLoc, "]"); 7633 } else 7634 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7635 } 7636 7637 /// \brief Emit a warning when adding a char literal to a string. 7638 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7639 Expr *LHSExpr, Expr *RHSExpr) { 7640 const Expr *StringRefExpr = LHSExpr; 7641 const CharacterLiteral *CharExpr = 7642 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7643 7644 if (!CharExpr) { 7645 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7646 StringRefExpr = RHSExpr; 7647 } 7648 7649 if (!CharExpr || !StringRefExpr) 7650 return; 7651 7652 const QualType StringType = StringRefExpr->getType(); 7653 7654 // Return if not a PointerType. 7655 if (!StringType->isAnyPointerType()) 7656 return; 7657 7658 // Return if not a CharacterType. 7659 if (!StringType->getPointeeType()->isAnyCharacterType()) 7660 return; 7661 7662 ASTContext &Ctx = Self.getASTContext(); 7663 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7664 7665 const QualType CharType = CharExpr->getType(); 7666 if (!CharType->isAnyCharacterType() && 7667 CharType->isIntegerType() && 7668 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7669 Self.Diag(OpLoc, diag::warn_string_plus_char) 7670 << DiagRange << Ctx.CharTy; 7671 } else { 7672 Self.Diag(OpLoc, diag::warn_string_plus_char) 7673 << DiagRange << CharExpr->getType(); 7674 } 7675 7676 // Only print a fixit for str + char, not for char + str. 7677 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7678 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7679 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7680 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7681 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7682 << FixItHint::CreateInsertion(EndLoc, "]"); 7683 } else { 7684 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7685 } 7686 } 7687 7688 /// \brief Emit error when two pointers are incompatible. 7689 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7690 Expr *LHSExpr, Expr *RHSExpr) { 7691 assert(LHSExpr->getType()->isAnyPointerType()); 7692 assert(RHSExpr->getType()->isAnyPointerType()); 7693 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7694 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7695 << RHSExpr->getSourceRange(); 7696 } 7697 7698 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7699 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7700 QualType* CompLHSTy) { 7701 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7702 7703 if (LHS.get()->getType()->isVectorType() || 7704 RHS.get()->getType()->isVectorType()) { 7705 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7706 if (CompLHSTy) *CompLHSTy = compType; 7707 return compType; 7708 } 7709 7710 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7711 if (LHS.isInvalid() || RHS.isInvalid()) 7712 return QualType(); 7713 7714 // Diagnose "string literal" '+' int and string '+' "char literal". 7715 if (Opc == BO_Add) { 7716 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7717 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7718 } 7719 7720 // handle the common case first (both operands are arithmetic). 7721 if (!compType.isNull() && compType->isArithmeticType()) { 7722 if (CompLHSTy) *CompLHSTy = compType; 7723 return compType; 7724 } 7725 7726 // Type-checking. Ultimately the pointer's going to be in PExp; 7727 // note that we bias towards the LHS being the pointer. 7728 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7729 7730 bool isObjCPointer; 7731 if (PExp->getType()->isPointerType()) { 7732 isObjCPointer = false; 7733 } else if (PExp->getType()->isObjCObjectPointerType()) { 7734 isObjCPointer = true; 7735 } else { 7736 std::swap(PExp, IExp); 7737 if (PExp->getType()->isPointerType()) { 7738 isObjCPointer = false; 7739 } else if (PExp->getType()->isObjCObjectPointerType()) { 7740 isObjCPointer = true; 7741 } else { 7742 return InvalidOperands(Loc, LHS, RHS); 7743 } 7744 } 7745 assert(PExp->getType()->isAnyPointerType()); 7746 7747 if (!IExp->getType()->isIntegerType()) 7748 return InvalidOperands(Loc, LHS, RHS); 7749 7750 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7751 return QualType(); 7752 7753 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7754 return QualType(); 7755 7756 // Check array bounds for pointer arithemtic 7757 CheckArrayAccess(PExp, IExp); 7758 7759 if (CompLHSTy) { 7760 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7761 if (LHSTy.isNull()) { 7762 LHSTy = LHS.get()->getType(); 7763 if (LHSTy->isPromotableIntegerType()) 7764 LHSTy = Context.getPromotedIntegerType(LHSTy); 7765 } 7766 *CompLHSTy = LHSTy; 7767 } 7768 7769 return PExp->getType(); 7770 } 7771 7772 // C99 6.5.6 7773 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7774 SourceLocation Loc, 7775 QualType* CompLHSTy) { 7776 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7777 7778 if (LHS.get()->getType()->isVectorType() || 7779 RHS.get()->getType()->isVectorType()) { 7780 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7781 if (CompLHSTy) *CompLHSTy = compType; 7782 return compType; 7783 } 7784 7785 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7786 if (LHS.isInvalid() || RHS.isInvalid()) 7787 return QualType(); 7788 7789 // Enforce type constraints: C99 6.5.6p3. 7790 7791 // Handle the common case first (both operands are arithmetic). 7792 if (!compType.isNull() && compType->isArithmeticType()) { 7793 if (CompLHSTy) *CompLHSTy = compType; 7794 return compType; 7795 } 7796 7797 // Either ptr - int or ptr - ptr. 7798 if (LHS.get()->getType()->isAnyPointerType()) { 7799 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7800 7801 // Diagnose bad cases where we step over interface counts. 7802 if (LHS.get()->getType()->isObjCObjectPointerType() && 7803 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7804 return QualType(); 7805 7806 // The result type of a pointer-int computation is the pointer type. 7807 if (RHS.get()->getType()->isIntegerType()) { 7808 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7809 return QualType(); 7810 7811 // Check array bounds for pointer arithemtic 7812 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 7813 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7814 7815 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7816 return LHS.get()->getType(); 7817 } 7818 7819 // Handle pointer-pointer subtractions. 7820 if (const PointerType *RHSPTy 7821 = RHS.get()->getType()->getAs<PointerType>()) { 7822 QualType rpointee = RHSPTy->getPointeeType(); 7823 7824 if (getLangOpts().CPlusPlus) { 7825 // Pointee types must be the same: C++ [expr.add] 7826 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7827 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7828 } 7829 } else { 7830 // Pointee types must be compatible C99 6.5.6p3 7831 if (!Context.typesAreCompatible( 7832 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7833 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7834 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7835 return QualType(); 7836 } 7837 } 7838 7839 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7840 LHS.get(), RHS.get())) 7841 return QualType(); 7842 7843 // The pointee type may have zero size. As an extension, a structure or 7844 // union may have zero size or an array may have zero length. In this 7845 // case subtraction does not make sense. 7846 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7847 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7848 if (ElementSize.isZero()) { 7849 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7850 << rpointee.getUnqualifiedType() 7851 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7852 } 7853 } 7854 7855 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7856 return Context.getPointerDiffType(); 7857 } 7858 } 7859 7860 return InvalidOperands(Loc, LHS, RHS); 7861 } 7862 7863 static bool isScopedEnumerationType(QualType T) { 7864 if (const EnumType *ET = T->getAs<EnumType>()) 7865 return ET->getDecl()->isScoped(); 7866 return false; 7867 } 7868 7869 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7870 SourceLocation Loc, unsigned Opc, 7871 QualType LHSType) { 7872 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7873 // so skip remaining warnings as we don't want to modify values within Sema. 7874 if (S.getLangOpts().OpenCL) 7875 return; 7876 7877 llvm::APSInt Right; 7878 // Check right/shifter operand 7879 if (RHS.get()->isValueDependent() || 7880 !RHS.get()->EvaluateAsInt(Right, S.Context)) 7881 return; 7882 7883 if (Right.isNegative()) { 7884 S.DiagRuntimeBehavior(Loc, RHS.get(), 7885 S.PDiag(diag::warn_shift_negative) 7886 << RHS.get()->getSourceRange()); 7887 return; 7888 } 7889 llvm::APInt LeftBits(Right.getBitWidth(), 7890 S.Context.getTypeSize(LHS.get()->getType())); 7891 if (Right.uge(LeftBits)) { 7892 S.DiagRuntimeBehavior(Loc, RHS.get(), 7893 S.PDiag(diag::warn_shift_gt_typewidth) 7894 << RHS.get()->getSourceRange()); 7895 return; 7896 } 7897 if (Opc != BO_Shl) 7898 return; 7899 7900 // When left shifting an ICE which is signed, we can check for overflow which 7901 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7902 // integers have defined behavior modulo one more than the maximum value 7903 // representable in the result type, so never warn for those. 7904 llvm::APSInt Left; 7905 if (LHS.get()->isValueDependent() || 7906 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7907 LHSType->hasUnsignedIntegerRepresentation()) 7908 return; 7909 llvm::APInt ResultBits = 7910 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7911 if (LeftBits.uge(ResultBits)) 7912 return; 7913 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7914 Result = Result.shl(Right); 7915 7916 // Print the bit representation of the signed integer as an unsigned 7917 // hexadecimal number. 7918 SmallString<40> HexResult; 7919 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7920 7921 // If we are only missing a sign bit, this is less likely to result in actual 7922 // bugs -- if the result is cast back to an unsigned type, it will have the 7923 // expected value. Thus we place this behind a different warning that can be 7924 // turned off separately if needed. 7925 if (LeftBits == ResultBits - 1) { 7926 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7927 << HexResult << LHSType 7928 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7929 return; 7930 } 7931 7932 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7933 << HexResult.str() << Result.getMinSignedBits() << LHSType 7934 << Left.getBitWidth() << LHS.get()->getSourceRange() 7935 << RHS.get()->getSourceRange(); 7936 } 7937 7938 /// \brief Return the resulting type when an OpenCL vector is shifted 7939 /// by a scalar or vector shift amount. 7940 static QualType checkOpenCLVectorShift(Sema &S, 7941 ExprResult &LHS, ExprResult &RHS, 7942 SourceLocation Loc, bool IsCompAssign) { 7943 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 7944 if (!LHS.get()->getType()->isVectorType()) { 7945 S.Diag(Loc, diag::err_shift_rhs_only_vector) 7946 << RHS.get()->getType() << LHS.get()->getType() 7947 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7948 return QualType(); 7949 } 7950 7951 if (!IsCompAssign) { 7952 LHS = S.UsualUnaryConversions(LHS.get()); 7953 if (LHS.isInvalid()) return QualType(); 7954 } 7955 7956 RHS = S.UsualUnaryConversions(RHS.get()); 7957 if (RHS.isInvalid()) return QualType(); 7958 7959 QualType LHSType = LHS.get()->getType(); 7960 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 7961 QualType LHSEleType = LHSVecTy->getElementType(); 7962 7963 // Note that RHS might not be a vector. 7964 QualType RHSType = RHS.get()->getType(); 7965 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 7966 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 7967 7968 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 7969 if (!LHSEleType->isIntegerType()) { 7970 S.Diag(Loc, diag::err_typecheck_expect_int) 7971 << LHS.get()->getType() << LHS.get()->getSourceRange(); 7972 return QualType(); 7973 } 7974 7975 if (!RHSEleType->isIntegerType()) { 7976 S.Diag(Loc, diag::err_typecheck_expect_int) 7977 << RHS.get()->getType() << RHS.get()->getSourceRange(); 7978 return QualType(); 7979 } 7980 7981 if (RHSVecTy) { 7982 // OpenCL v1.1 s6.3.j says that for vector types, the operators 7983 // are applied component-wise. So if RHS is a vector, then ensure 7984 // that the number of elements is the same as LHS... 7985 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 7986 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 7987 << LHS.get()->getType() << RHS.get()->getType() 7988 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7989 return QualType(); 7990 } 7991 } else { 7992 // ...else expand RHS to match the number of elements in LHS. 7993 QualType VecTy = 7994 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 7995 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 7996 } 7997 7998 return LHSType; 7999 } 8000 8001 // C99 6.5.7 8002 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8003 SourceLocation Loc, unsigned Opc, 8004 bool IsCompAssign) { 8005 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8006 8007 // Vector shifts promote their scalar inputs to vector type. 8008 if (LHS.get()->getType()->isVectorType() || 8009 RHS.get()->getType()->isVectorType()) { 8010 if (LangOpts.OpenCL) 8011 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8012 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8013 } 8014 8015 // Shifts don't perform usual arithmetic conversions, they just do integer 8016 // promotions on each operand. C99 6.5.7p3 8017 8018 // For the LHS, do usual unary conversions, but then reset them away 8019 // if this is a compound assignment. 8020 ExprResult OldLHS = LHS; 8021 LHS = UsualUnaryConversions(LHS.get()); 8022 if (LHS.isInvalid()) 8023 return QualType(); 8024 QualType LHSType = LHS.get()->getType(); 8025 if (IsCompAssign) LHS = OldLHS; 8026 8027 // The RHS is simpler. 8028 RHS = UsualUnaryConversions(RHS.get()); 8029 if (RHS.isInvalid()) 8030 return QualType(); 8031 QualType RHSType = RHS.get()->getType(); 8032 8033 // C99 6.5.7p2: Each of the operands shall have integer type. 8034 if (!LHSType->hasIntegerRepresentation() || 8035 !RHSType->hasIntegerRepresentation()) 8036 return InvalidOperands(Loc, LHS, RHS); 8037 8038 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8039 // hasIntegerRepresentation() above instead of this. 8040 if (isScopedEnumerationType(LHSType) || 8041 isScopedEnumerationType(RHSType)) { 8042 return InvalidOperands(Loc, LHS, RHS); 8043 } 8044 // Sanity-check shift operands 8045 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8046 8047 // "The type of the result is that of the promoted left operand." 8048 return LHSType; 8049 } 8050 8051 static bool IsWithinTemplateSpecialization(Decl *D) { 8052 if (DeclContext *DC = D->getDeclContext()) { 8053 if (isa<ClassTemplateSpecializationDecl>(DC)) 8054 return true; 8055 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8056 return FD->isFunctionTemplateSpecialization(); 8057 } 8058 return false; 8059 } 8060 8061 /// If two different enums are compared, raise a warning. 8062 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8063 Expr *RHS) { 8064 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8065 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8066 8067 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8068 if (!LHSEnumType) 8069 return; 8070 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8071 if (!RHSEnumType) 8072 return; 8073 8074 // Ignore anonymous enums. 8075 if (!LHSEnumType->getDecl()->getIdentifier()) 8076 return; 8077 if (!RHSEnumType->getDecl()->getIdentifier()) 8078 return; 8079 8080 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8081 return; 8082 8083 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8084 << LHSStrippedType << RHSStrippedType 8085 << LHS->getSourceRange() << RHS->getSourceRange(); 8086 } 8087 8088 /// \brief Diagnose bad pointer comparisons. 8089 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8090 ExprResult &LHS, ExprResult &RHS, 8091 bool IsError) { 8092 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8093 : diag::ext_typecheck_comparison_of_distinct_pointers) 8094 << LHS.get()->getType() << RHS.get()->getType() 8095 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8096 } 8097 8098 /// \brief Returns false if the pointers are converted to a composite type, 8099 /// true otherwise. 8100 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8101 ExprResult &LHS, ExprResult &RHS) { 8102 // C++ [expr.rel]p2: 8103 // [...] Pointer conversions (4.10) and qualification 8104 // conversions (4.4) are performed on pointer operands (or on 8105 // a pointer operand and a null pointer constant) to bring 8106 // them to their composite pointer type. [...] 8107 // 8108 // C++ [expr.eq]p1 uses the same notion for (in)equality 8109 // comparisons of pointers. 8110 8111 // C++ [expr.eq]p2: 8112 // In addition, pointers to members can be compared, or a pointer to 8113 // member and a null pointer constant. Pointer to member conversions 8114 // (4.11) and qualification conversions (4.4) are performed to bring 8115 // them to a common type. If one operand is a null pointer constant, 8116 // the common type is the type of the other operand. Otherwise, the 8117 // common type is a pointer to member type similar (4.4) to the type 8118 // of one of the operands, with a cv-qualification signature (4.4) 8119 // that is the union of the cv-qualification signatures of the operand 8120 // types. 8121 8122 QualType LHSType = LHS.get()->getType(); 8123 QualType RHSType = RHS.get()->getType(); 8124 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8125 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8126 8127 bool NonStandardCompositeType = false; 8128 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8129 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8130 if (T.isNull()) { 8131 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8132 return true; 8133 } 8134 8135 if (NonStandardCompositeType) 8136 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8137 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8138 << RHS.get()->getSourceRange(); 8139 8140 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8141 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8142 return false; 8143 } 8144 8145 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8146 ExprResult &LHS, 8147 ExprResult &RHS, 8148 bool IsError) { 8149 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8150 : diag::ext_typecheck_comparison_of_fptr_to_void) 8151 << LHS.get()->getType() << RHS.get()->getType() 8152 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8153 } 8154 8155 static bool isObjCObjectLiteral(ExprResult &E) { 8156 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8157 case Stmt::ObjCArrayLiteralClass: 8158 case Stmt::ObjCDictionaryLiteralClass: 8159 case Stmt::ObjCStringLiteralClass: 8160 case Stmt::ObjCBoxedExprClass: 8161 return true; 8162 default: 8163 // Note that ObjCBoolLiteral is NOT an object literal! 8164 return false; 8165 } 8166 } 8167 8168 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8169 const ObjCObjectPointerType *Type = 8170 LHS->getType()->getAs<ObjCObjectPointerType>(); 8171 8172 // If this is not actually an Objective-C object, bail out. 8173 if (!Type) 8174 return false; 8175 8176 // Get the LHS object's interface type. 8177 QualType InterfaceType = Type->getPointeeType(); 8178 if (const ObjCObjectType *iQFaceTy = 8179 InterfaceType->getAsObjCQualifiedInterfaceType()) 8180 InterfaceType = iQFaceTy->getBaseType(); 8181 8182 // If the RHS isn't an Objective-C object, bail out. 8183 if (!RHS->getType()->isObjCObjectPointerType()) 8184 return false; 8185 8186 // Try to find the -isEqual: method. 8187 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8188 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8189 InterfaceType, 8190 /*instance=*/true); 8191 if (!Method) { 8192 if (Type->isObjCIdType()) { 8193 // For 'id', just check the global pool. 8194 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8195 /*receiverId=*/true); 8196 } else { 8197 // Check protocols. 8198 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8199 /*instance=*/true); 8200 } 8201 } 8202 8203 if (!Method) 8204 return false; 8205 8206 QualType T = Method->parameters()[0]->getType(); 8207 if (!T->isObjCObjectPointerType()) 8208 return false; 8209 8210 QualType R = Method->getReturnType(); 8211 if (!R->isScalarType()) 8212 return false; 8213 8214 return true; 8215 } 8216 8217 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8218 FromE = FromE->IgnoreParenImpCasts(); 8219 switch (FromE->getStmtClass()) { 8220 default: 8221 break; 8222 case Stmt::ObjCStringLiteralClass: 8223 // "string literal" 8224 return LK_String; 8225 case Stmt::ObjCArrayLiteralClass: 8226 // "array literal" 8227 return LK_Array; 8228 case Stmt::ObjCDictionaryLiteralClass: 8229 // "dictionary literal" 8230 return LK_Dictionary; 8231 case Stmt::BlockExprClass: 8232 return LK_Block; 8233 case Stmt::ObjCBoxedExprClass: { 8234 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8235 switch (Inner->getStmtClass()) { 8236 case Stmt::IntegerLiteralClass: 8237 case Stmt::FloatingLiteralClass: 8238 case Stmt::CharacterLiteralClass: 8239 case Stmt::ObjCBoolLiteralExprClass: 8240 case Stmt::CXXBoolLiteralExprClass: 8241 // "numeric literal" 8242 return LK_Numeric; 8243 case Stmt::ImplicitCastExprClass: { 8244 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8245 // Boolean literals can be represented by implicit casts. 8246 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8247 return LK_Numeric; 8248 break; 8249 } 8250 default: 8251 break; 8252 } 8253 return LK_Boxed; 8254 } 8255 } 8256 return LK_None; 8257 } 8258 8259 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8260 ExprResult &LHS, ExprResult &RHS, 8261 BinaryOperator::Opcode Opc){ 8262 Expr *Literal; 8263 Expr *Other; 8264 if (isObjCObjectLiteral(LHS)) { 8265 Literal = LHS.get(); 8266 Other = RHS.get(); 8267 } else { 8268 Literal = RHS.get(); 8269 Other = LHS.get(); 8270 } 8271 8272 // Don't warn on comparisons against nil. 8273 Other = Other->IgnoreParenCasts(); 8274 if (Other->isNullPointerConstant(S.getASTContext(), 8275 Expr::NPC_ValueDependentIsNotNull)) 8276 return; 8277 8278 // This should be kept in sync with warn_objc_literal_comparison. 8279 // LK_String should always be after the other literals, since it has its own 8280 // warning flag. 8281 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8282 assert(LiteralKind != Sema::LK_Block); 8283 if (LiteralKind == Sema::LK_None) { 8284 llvm_unreachable("Unknown Objective-C object literal kind"); 8285 } 8286 8287 if (LiteralKind == Sema::LK_String) 8288 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8289 << Literal->getSourceRange(); 8290 else 8291 S.Diag(Loc, diag::warn_objc_literal_comparison) 8292 << LiteralKind << Literal->getSourceRange(); 8293 8294 if (BinaryOperator::isEqualityOp(Opc) && 8295 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8296 SourceLocation Start = LHS.get()->getLocStart(); 8297 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 8298 CharSourceRange OpRange = 8299 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 8300 8301 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8302 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8303 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8304 << FixItHint::CreateInsertion(End, "]"); 8305 } 8306 } 8307 8308 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8309 ExprResult &RHS, 8310 SourceLocation Loc, 8311 unsigned OpaqueOpc) { 8312 // This checking requires bools. 8313 if (!S.getLangOpts().Bool) return; 8314 8315 // Check that left hand side is !something. 8316 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8317 if (!UO || UO->getOpcode() != UO_LNot) return; 8318 8319 // Only check if the right hand side is non-bool arithmetic type. 8320 if (RHS.get()->getType()->isBooleanType()) return; 8321 8322 // Make sure that the something in !something is not bool. 8323 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8324 if (SubExpr->getType()->isBooleanType()) return; 8325 8326 // Emit warning. 8327 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8328 << Loc; 8329 8330 // First note suggest !(x < y) 8331 SourceLocation FirstOpen = SubExpr->getLocStart(); 8332 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8333 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 8334 if (FirstClose.isInvalid()) 8335 FirstOpen = SourceLocation(); 8336 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8337 << FixItHint::CreateInsertion(FirstOpen, "(") 8338 << FixItHint::CreateInsertion(FirstClose, ")"); 8339 8340 // Second note suggests (!x) < y 8341 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8342 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8343 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 8344 if (SecondClose.isInvalid()) 8345 SecondOpen = SourceLocation(); 8346 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8347 << FixItHint::CreateInsertion(SecondOpen, "(") 8348 << FixItHint::CreateInsertion(SecondClose, ")"); 8349 } 8350 8351 // Get the decl for a simple expression: a reference to a variable, 8352 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8353 static ValueDecl *getCompareDecl(Expr *E) { 8354 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8355 return DR->getDecl(); 8356 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8357 if (Ivar->isFreeIvar()) 8358 return Ivar->getDecl(); 8359 } 8360 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8361 if (Mem->isImplicitAccess()) 8362 return Mem->getMemberDecl(); 8363 } 8364 return nullptr; 8365 } 8366 8367 // C99 6.5.8, C++ [expr.rel] 8368 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8369 SourceLocation Loc, unsigned OpaqueOpc, 8370 bool IsRelational) { 8371 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8372 8373 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 8374 8375 // Handle vector comparisons separately. 8376 if (LHS.get()->getType()->isVectorType() || 8377 RHS.get()->getType()->isVectorType()) 8378 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8379 8380 QualType LHSType = LHS.get()->getType(); 8381 QualType RHSType = RHS.get()->getType(); 8382 8383 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8384 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8385 8386 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8387 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 8388 8389 if (!LHSType->hasFloatingRepresentation() && 8390 !(LHSType->isBlockPointerType() && IsRelational) && 8391 !LHS.get()->getLocStart().isMacroID() && 8392 !RHS.get()->getLocStart().isMacroID() && 8393 ActiveTemplateInstantiations.empty()) { 8394 // For non-floating point types, check for self-comparisons of the form 8395 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8396 // often indicate logic errors in the program. 8397 // 8398 // NOTE: Don't warn about comparison expressions resulting from macro 8399 // expansion. Also don't warn about comparisons which are only self 8400 // comparisons within a template specialization. The warnings should catch 8401 // obvious cases in the definition of the template anyways. The idea is to 8402 // warn when the typed comparison operator will always evaluate to the same 8403 // result. 8404 ValueDecl *DL = getCompareDecl(LHSStripped); 8405 ValueDecl *DR = getCompareDecl(RHSStripped); 8406 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8407 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8408 << 0 // self- 8409 << (Opc == BO_EQ 8410 || Opc == BO_LE 8411 || Opc == BO_GE)); 8412 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8413 !DL->getType()->isReferenceType() && 8414 !DR->getType()->isReferenceType()) { 8415 // what is it always going to eval to? 8416 char always_evals_to; 8417 switch(Opc) { 8418 case BO_EQ: // e.g. array1 == array2 8419 always_evals_to = 0; // false 8420 break; 8421 case BO_NE: // e.g. array1 != array2 8422 always_evals_to = 1; // true 8423 break; 8424 default: 8425 // best we can say is 'a constant' 8426 always_evals_to = 2; // e.g. array1 <= array2 8427 break; 8428 } 8429 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8430 << 1 // array 8431 << always_evals_to); 8432 } 8433 8434 if (isa<CastExpr>(LHSStripped)) 8435 LHSStripped = LHSStripped->IgnoreParenCasts(); 8436 if (isa<CastExpr>(RHSStripped)) 8437 RHSStripped = RHSStripped->IgnoreParenCasts(); 8438 8439 // Warn about comparisons against a string constant (unless the other 8440 // operand is null), the user probably wants strcmp. 8441 Expr *literalString = nullptr; 8442 Expr *literalStringStripped = nullptr; 8443 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8444 !RHSStripped->isNullPointerConstant(Context, 8445 Expr::NPC_ValueDependentIsNull)) { 8446 literalString = LHS.get(); 8447 literalStringStripped = LHSStripped; 8448 } else if ((isa<StringLiteral>(RHSStripped) || 8449 isa<ObjCEncodeExpr>(RHSStripped)) && 8450 !LHSStripped->isNullPointerConstant(Context, 8451 Expr::NPC_ValueDependentIsNull)) { 8452 literalString = RHS.get(); 8453 literalStringStripped = RHSStripped; 8454 } 8455 8456 if (literalString) { 8457 DiagRuntimeBehavior(Loc, nullptr, 8458 PDiag(diag::warn_stringcompare) 8459 << isa<ObjCEncodeExpr>(literalStringStripped) 8460 << literalString->getSourceRange()); 8461 } 8462 } 8463 8464 // C99 6.5.8p3 / C99 6.5.9p4 8465 UsualArithmeticConversions(LHS, RHS); 8466 if (LHS.isInvalid() || RHS.isInvalid()) 8467 return QualType(); 8468 8469 LHSType = LHS.get()->getType(); 8470 RHSType = RHS.get()->getType(); 8471 8472 // The result of comparisons is 'bool' in C++, 'int' in C. 8473 QualType ResultTy = Context.getLogicalOperationType(); 8474 8475 if (IsRelational) { 8476 if (LHSType->isRealType() && RHSType->isRealType()) 8477 return ResultTy; 8478 } else { 8479 // Check for comparisons of floating point operands using != and ==. 8480 if (LHSType->hasFloatingRepresentation()) 8481 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8482 8483 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8484 return ResultTy; 8485 } 8486 8487 const Expr::NullPointerConstantKind LHSNullKind = 8488 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8489 const Expr::NullPointerConstantKind RHSNullKind = 8490 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8491 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8492 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8493 8494 if (!IsRelational && LHSIsNull != RHSIsNull) { 8495 bool IsEquality = Opc == BO_EQ; 8496 if (RHSIsNull) 8497 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 8498 RHS.get()->getSourceRange()); 8499 else 8500 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 8501 LHS.get()->getSourceRange()); 8502 } 8503 8504 // All of the following pointer-related warnings are GCC extensions, except 8505 // when handling null pointer constants. 8506 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 8507 QualType LCanPointeeTy = 8508 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8509 QualType RCanPointeeTy = 8510 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8511 8512 if (getLangOpts().CPlusPlus) { 8513 if (LCanPointeeTy == RCanPointeeTy) 8514 return ResultTy; 8515 if (!IsRelational && 8516 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8517 // Valid unless comparison between non-null pointer and function pointer 8518 // This is a gcc extension compatibility comparison. 8519 // In a SFINAE context, we treat this as a hard error to maintain 8520 // conformance with the C++ standard. 8521 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8522 && !LHSIsNull && !RHSIsNull) { 8523 diagnoseFunctionPointerToVoidComparison( 8524 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8525 8526 if (isSFINAEContext()) 8527 return QualType(); 8528 8529 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8530 return ResultTy; 8531 } 8532 } 8533 8534 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8535 return QualType(); 8536 else 8537 return ResultTy; 8538 } 8539 // C99 6.5.9p2 and C99 6.5.8p2 8540 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8541 RCanPointeeTy.getUnqualifiedType())) { 8542 // Valid unless a relational comparison of function pointers 8543 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8544 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8545 << LHSType << RHSType << LHS.get()->getSourceRange() 8546 << RHS.get()->getSourceRange(); 8547 } 8548 } else if (!IsRelational && 8549 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8550 // Valid unless comparison between non-null pointer and function pointer 8551 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8552 && !LHSIsNull && !RHSIsNull) 8553 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8554 /*isError*/false); 8555 } else { 8556 // Invalid 8557 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8558 } 8559 if (LCanPointeeTy != RCanPointeeTy) { 8560 const PointerType *lhsPtr = LHSType->getAs<PointerType>(); 8561 if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 8562 Diag(Loc, 8563 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8564 << LHSType << RHSType << 0 /* comparison */ 8565 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8566 } 8567 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 8568 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 8569 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 8570 : CK_BitCast; 8571 if (LHSIsNull && !RHSIsNull) 8572 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 8573 else 8574 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 8575 } 8576 return ResultTy; 8577 } 8578 8579 if (getLangOpts().CPlusPlus) { 8580 // Comparison of nullptr_t with itself. 8581 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 8582 return ResultTy; 8583 8584 // Comparison of pointers with null pointer constants and equality 8585 // comparisons of member pointers to null pointer constants. 8586 if (RHSIsNull && 8587 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 8588 (!IsRelational && 8589 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 8590 RHS = ImpCastExprToType(RHS.get(), LHSType, 8591 LHSType->isMemberPointerType() 8592 ? CK_NullToMemberPointer 8593 : CK_NullToPointer); 8594 return ResultTy; 8595 } 8596 if (LHSIsNull && 8597 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 8598 (!IsRelational && 8599 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 8600 LHS = ImpCastExprToType(LHS.get(), RHSType, 8601 RHSType->isMemberPointerType() 8602 ? CK_NullToMemberPointer 8603 : CK_NullToPointer); 8604 return ResultTy; 8605 } 8606 8607 // Comparison of member pointers. 8608 if (!IsRelational && 8609 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 8610 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8611 return QualType(); 8612 else 8613 return ResultTy; 8614 } 8615 8616 // Handle scoped enumeration types specifically, since they don't promote 8617 // to integers. 8618 if (LHS.get()->getType()->isEnumeralType() && 8619 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8620 RHS.get()->getType())) 8621 return ResultTy; 8622 } 8623 8624 // Handle block pointer types. 8625 if (!IsRelational && LHSType->isBlockPointerType() && 8626 RHSType->isBlockPointerType()) { 8627 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8628 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8629 8630 if (!LHSIsNull && !RHSIsNull && 8631 !Context.typesAreCompatible(lpointee, rpointee)) { 8632 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8633 << LHSType << RHSType << LHS.get()->getSourceRange() 8634 << RHS.get()->getSourceRange(); 8635 } 8636 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8637 return ResultTy; 8638 } 8639 8640 // Allow block pointers to be compared with null pointer constants. 8641 if (!IsRelational 8642 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8643 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8644 if (!LHSIsNull && !RHSIsNull) { 8645 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8646 ->getPointeeType()->isVoidType()) 8647 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8648 ->getPointeeType()->isVoidType()))) 8649 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8650 << LHSType << RHSType << LHS.get()->getSourceRange() 8651 << RHS.get()->getSourceRange(); 8652 } 8653 if (LHSIsNull && !RHSIsNull) 8654 LHS = ImpCastExprToType(LHS.get(), RHSType, 8655 RHSType->isPointerType() ? CK_BitCast 8656 : CK_AnyPointerToBlockPointerCast); 8657 else 8658 RHS = ImpCastExprToType(RHS.get(), LHSType, 8659 LHSType->isPointerType() ? CK_BitCast 8660 : CK_AnyPointerToBlockPointerCast); 8661 return ResultTy; 8662 } 8663 8664 if (LHSType->isObjCObjectPointerType() || 8665 RHSType->isObjCObjectPointerType()) { 8666 const PointerType *LPT = LHSType->getAs<PointerType>(); 8667 const PointerType *RPT = RHSType->getAs<PointerType>(); 8668 if (LPT || RPT) { 8669 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8670 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8671 8672 if (!LPtrToVoid && !RPtrToVoid && 8673 !Context.typesAreCompatible(LHSType, RHSType)) { 8674 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8675 /*isError*/false); 8676 } 8677 if (LHSIsNull && !RHSIsNull) { 8678 Expr *E = LHS.get(); 8679 if (getLangOpts().ObjCAutoRefCount) 8680 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8681 LHS = ImpCastExprToType(E, RHSType, 8682 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8683 } 8684 else { 8685 Expr *E = RHS.get(); 8686 if (getLangOpts().ObjCAutoRefCount) 8687 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false, 8688 Opc); 8689 RHS = ImpCastExprToType(E, LHSType, 8690 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8691 } 8692 return ResultTy; 8693 } 8694 if (LHSType->isObjCObjectPointerType() && 8695 RHSType->isObjCObjectPointerType()) { 8696 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8697 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8698 /*isError*/false); 8699 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8700 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8701 8702 if (LHSIsNull && !RHSIsNull) 8703 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8704 else 8705 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8706 return ResultTy; 8707 } 8708 } 8709 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8710 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8711 unsigned DiagID = 0; 8712 bool isError = false; 8713 if (LangOpts.DebuggerSupport) { 8714 // Under a debugger, allow the comparison of pointers to integers, 8715 // since users tend to want to compare addresses. 8716 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8717 (RHSIsNull && RHSType->isIntegerType())) { 8718 if (IsRelational && !getLangOpts().CPlusPlus) 8719 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8720 } else if (IsRelational && !getLangOpts().CPlusPlus) 8721 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8722 else if (getLangOpts().CPlusPlus) { 8723 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8724 isError = true; 8725 } else 8726 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8727 8728 if (DiagID) { 8729 Diag(Loc, DiagID) 8730 << LHSType << RHSType << LHS.get()->getSourceRange() 8731 << RHS.get()->getSourceRange(); 8732 if (isError) 8733 return QualType(); 8734 } 8735 8736 if (LHSType->isIntegerType()) 8737 LHS = ImpCastExprToType(LHS.get(), RHSType, 8738 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8739 else 8740 RHS = ImpCastExprToType(RHS.get(), LHSType, 8741 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8742 return ResultTy; 8743 } 8744 8745 // Handle block pointers. 8746 if (!IsRelational && RHSIsNull 8747 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8748 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8749 return ResultTy; 8750 } 8751 if (!IsRelational && LHSIsNull 8752 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8753 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 8754 return ResultTy; 8755 } 8756 8757 return InvalidOperands(Loc, LHS, RHS); 8758 } 8759 8760 8761 // Return a signed type that is of identical size and number of elements. 8762 // For floating point vectors, return an integer type of identical size 8763 // and number of elements. 8764 QualType Sema::GetSignedVectorType(QualType V) { 8765 const VectorType *VTy = V->getAs<VectorType>(); 8766 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8767 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8768 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8769 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8770 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8771 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8772 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8773 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8774 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8775 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8776 "Unhandled vector element size in vector compare"); 8777 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8778 } 8779 8780 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 8781 /// operates on extended vector types. Instead of producing an IntTy result, 8782 /// like a scalar comparison, a vector comparison produces a vector of integer 8783 /// types. 8784 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8785 SourceLocation Loc, 8786 bool IsRelational) { 8787 // Check to make sure we're operating on vectors of the same type and width, 8788 // Allowing one side to be a scalar of element type. 8789 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8790 if (vType.isNull()) 8791 return vType; 8792 8793 QualType LHSType = LHS.get()->getType(); 8794 8795 // If AltiVec, the comparison results in a numeric type, i.e. 8796 // bool for C++, int for C 8797 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8798 return Context.getLogicalOperationType(); 8799 8800 // For non-floating point types, check for self-comparisons of the form 8801 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8802 // often indicate logic errors in the program. 8803 if (!LHSType->hasFloatingRepresentation() && 8804 ActiveTemplateInstantiations.empty()) { 8805 if (DeclRefExpr* DRL 8806 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8807 if (DeclRefExpr* DRR 8808 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8809 if (DRL->getDecl() == DRR->getDecl()) 8810 DiagRuntimeBehavior(Loc, nullptr, 8811 PDiag(diag::warn_comparison_always) 8812 << 0 // self- 8813 << 2 // "a constant" 8814 ); 8815 } 8816 8817 // Check for comparisons of floating point operands using != and ==. 8818 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8819 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8820 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8821 } 8822 8823 // Return a signed type for the vector. 8824 return GetSignedVectorType(LHSType); 8825 } 8826 8827 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8828 SourceLocation Loc) { 8829 // Ensure that either both operands are of the same vector type, or 8830 // one operand is of a vector type and the other is of its element type. 8831 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8832 if (vType.isNull()) 8833 return InvalidOperands(Loc, LHS, RHS); 8834 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8835 vType->hasFloatingRepresentation()) 8836 return InvalidOperands(Loc, LHS, RHS); 8837 8838 return GetSignedVectorType(LHS.get()->getType()); 8839 } 8840 8841 inline QualType Sema::CheckBitwiseOperands( 8842 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8843 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8844 8845 if (LHS.get()->getType()->isVectorType() || 8846 RHS.get()->getType()->isVectorType()) { 8847 if (LHS.get()->getType()->hasIntegerRepresentation() && 8848 RHS.get()->getType()->hasIntegerRepresentation()) 8849 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8850 8851 return InvalidOperands(Loc, LHS, RHS); 8852 } 8853 8854 ExprResult LHSResult = LHS, RHSResult = RHS; 8855 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8856 IsCompAssign); 8857 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8858 return QualType(); 8859 LHS = LHSResult.get(); 8860 RHS = RHSResult.get(); 8861 8862 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8863 return compType; 8864 return InvalidOperands(Loc, LHS, RHS); 8865 } 8866 8867 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8868 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8869 8870 // Check vector operands differently. 8871 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8872 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8873 8874 // Diagnose cases where the user write a logical and/or but probably meant a 8875 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8876 // is a constant. 8877 if (LHS.get()->getType()->isIntegerType() && 8878 !LHS.get()->getType()->isBooleanType() && 8879 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8880 // Don't warn in macros or template instantiations. 8881 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8882 // If the RHS can be constant folded, and if it constant folds to something 8883 // that isn't 0 or 1 (which indicate a potential logical operation that 8884 // happened to fold to true/false) then warn. 8885 // Parens on the RHS are ignored. 8886 llvm::APSInt Result; 8887 if (RHS.get()->EvaluateAsInt(Result, Context)) 8888 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 8889 !RHS.get()->getExprLoc().isMacroID()) || 8890 (Result != 0 && Result != 1)) { 8891 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8892 << RHS.get()->getSourceRange() 8893 << (Opc == BO_LAnd ? "&&" : "||"); 8894 // Suggest replacing the logical operator with the bitwise version 8895 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8896 << (Opc == BO_LAnd ? "&" : "|") 8897 << FixItHint::CreateReplacement(SourceRange( 8898 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8899 getLangOpts())), 8900 Opc == BO_LAnd ? "&" : "|"); 8901 if (Opc == BO_LAnd) 8902 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8903 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8904 << FixItHint::CreateRemoval( 8905 SourceRange( 8906 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8907 0, getSourceManager(), 8908 getLangOpts()), 8909 RHS.get()->getLocEnd())); 8910 } 8911 } 8912 8913 if (!Context.getLangOpts().CPlusPlus) { 8914 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8915 // not operate on the built-in scalar and vector float types. 8916 if (Context.getLangOpts().OpenCL && 8917 Context.getLangOpts().OpenCLVersion < 120) { 8918 if (LHS.get()->getType()->isFloatingType() || 8919 RHS.get()->getType()->isFloatingType()) 8920 return InvalidOperands(Loc, LHS, RHS); 8921 } 8922 8923 LHS = UsualUnaryConversions(LHS.get()); 8924 if (LHS.isInvalid()) 8925 return QualType(); 8926 8927 RHS = UsualUnaryConversions(RHS.get()); 8928 if (RHS.isInvalid()) 8929 return QualType(); 8930 8931 if (!LHS.get()->getType()->isScalarType() || 8932 !RHS.get()->getType()->isScalarType()) 8933 return InvalidOperands(Loc, LHS, RHS); 8934 8935 return Context.IntTy; 8936 } 8937 8938 // The following is safe because we only use this method for 8939 // non-overloadable operands. 8940 8941 // C++ [expr.log.and]p1 8942 // C++ [expr.log.or]p1 8943 // The operands are both contextually converted to type bool. 8944 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8945 if (LHSRes.isInvalid()) 8946 return InvalidOperands(Loc, LHS, RHS); 8947 LHS = LHSRes; 8948 8949 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8950 if (RHSRes.isInvalid()) 8951 return InvalidOperands(Loc, LHS, RHS); 8952 RHS = RHSRes; 8953 8954 // C++ [expr.log.and]p2 8955 // C++ [expr.log.or]p2 8956 // The result is a bool. 8957 return Context.BoolTy; 8958 } 8959 8960 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8961 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8962 if (!ME) return false; 8963 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8964 ObjCMessageExpr *Base = 8965 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8966 if (!Base) return false; 8967 return Base->getMethodDecl() != nullptr; 8968 } 8969 8970 /// Is the given expression (which must be 'const') a reference to a 8971 /// variable which was originally non-const, but which has become 8972 /// 'const' due to being captured within a block? 8973 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8974 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8975 assert(E->isLValue() && E->getType().isConstQualified()); 8976 E = E->IgnoreParens(); 8977 8978 // Must be a reference to a declaration from an enclosing scope. 8979 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8980 if (!DRE) return NCCK_None; 8981 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 8982 8983 // The declaration must be a variable which is not declared 'const'. 8984 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8985 if (!var) return NCCK_None; 8986 if (var->getType().isConstQualified()) return NCCK_None; 8987 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8988 8989 // Decide whether the first capture was for a block or a lambda. 8990 DeclContext *DC = S.CurContext, *Prev = nullptr; 8991 while (DC != var->getDeclContext()) { 8992 Prev = DC; 8993 DC = DC->getParent(); 8994 } 8995 // Unless we have an init-capture, we've gone one step too far. 8996 if (!var->isInitCapture()) 8997 DC = Prev; 8998 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8999 } 9000 9001 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9002 Ty = Ty.getNonReferenceType(); 9003 if (IsDereference && Ty->isPointerType()) 9004 Ty = Ty->getPointeeType(); 9005 return !Ty.isConstQualified(); 9006 } 9007 9008 /// Emit the "read-only variable not assignable" error and print notes to give 9009 /// more information about why the variable is not assignable, such as pointing 9010 /// to the declaration of a const variable, showing that a method is const, or 9011 /// that the function is returning a const reference. 9012 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9013 SourceLocation Loc) { 9014 // Update err_typecheck_assign_const and note_typecheck_assign_const 9015 // when this enum is changed. 9016 enum { 9017 ConstFunction, 9018 ConstVariable, 9019 ConstMember, 9020 ConstMethod, 9021 ConstUnknown, // Keep as last element 9022 }; 9023 9024 SourceRange ExprRange = E->getSourceRange(); 9025 9026 // Only emit one error on the first const found. All other consts will emit 9027 // a note to the error. 9028 bool DiagnosticEmitted = false; 9029 9030 // Track if the current expression is the result of a derefence, and if the 9031 // next checked expression is the result of a derefence. 9032 bool IsDereference = false; 9033 bool NextIsDereference = false; 9034 9035 // Loop to process MemberExpr chains. 9036 while (true) { 9037 IsDereference = NextIsDereference; 9038 NextIsDereference = false; 9039 9040 E = E->IgnoreParenImpCasts(); 9041 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9042 NextIsDereference = ME->isArrow(); 9043 const ValueDecl *VD = ME->getMemberDecl(); 9044 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9045 // Mutable fields can be modified even if the class is const. 9046 if (Field->isMutable()) { 9047 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9048 break; 9049 } 9050 9051 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9052 if (!DiagnosticEmitted) { 9053 S.Diag(Loc, diag::err_typecheck_assign_const) 9054 << ExprRange << ConstMember << false /*static*/ << Field 9055 << Field->getType(); 9056 DiagnosticEmitted = true; 9057 } 9058 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9059 << ConstMember << false /*static*/ << Field << Field->getType() 9060 << Field->getSourceRange(); 9061 } 9062 E = ME->getBase(); 9063 continue; 9064 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9065 if (VDecl->getType().isConstQualified()) { 9066 if (!DiagnosticEmitted) { 9067 S.Diag(Loc, diag::err_typecheck_assign_const) 9068 << ExprRange << ConstMember << true /*static*/ << VDecl 9069 << VDecl->getType(); 9070 DiagnosticEmitted = true; 9071 } 9072 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9073 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9074 << VDecl->getSourceRange(); 9075 } 9076 // Static fields do not inherit constness from parents. 9077 break; 9078 } 9079 break; 9080 } // End MemberExpr 9081 break; 9082 } 9083 9084 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9085 // Function calls 9086 const FunctionDecl *FD = CE->getDirectCallee(); 9087 if (!IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9088 if (!DiagnosticEmitted) { 9089 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9090 << ConstFunction << FD; 9091 DiagnosticEmitted = true; 9092 } 9093 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9094 diag::note_typecheck_assign_const) 9095 << ConstFunction << FD << FD->getReturnType() 9096 << FD->getReturnTypeSourceRange(); 9097 } 9098 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9099 // Point to variable declaration. 9100 if (const ValueDecl *VD = DRE->getDecl()) { 9101 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9102 if (!DiagnosticEmitted) { 9103 S.Diag(Loc, diag::err_typecheck_assign_const) 9104 << ExprRange << ConstVariable << VD << VD->getType(); 9105 DiagnosticEmitted = true; 9106 } 9107 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9108 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9109 } 9110 } 9111 } else if (isa<CXXThisExpr>(E)) { 9112 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9113 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9114 if (MD->isConst()) { 9115 if (!DiagnosticEmitted) { 9116 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9117 << ConstMethod << MD; 9118 DiagnosticEmitted = true; 9119 } 9120 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9121 << ConstMethod << MD << MD->getSourceRange(); 9122 } 9123 } 9124 } 9125 } 9126 9127 if (DiagnosticEmitted) 9128 return; 9129 9130 // Can't determine a more specific message, so display the generic error. 9131 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9132 } 9133 9134 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9135 /// emit an error and return true. If so, return false. 9136 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9137 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9138 SourceLocation OrigLoc = Loc; 9139 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9140 &Loc); 9141 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9142 IsLV = Expr::MLV_InvalidMessageExpression; 9143 if (IsLV == Expr::MLV_Valid) 9144 return false; 9145 9146 unsigned DiagID = 0; 9147 bool NeedType = false; 9148 switch (IsLV) { // C99 6.5.16p2 9149 case Expr::MLV_ConstQualified: 9150 // Use a specialized diagnostic when we're assigning to an object 9151 // from an enclosing function or block. 9152 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9153 if (NCCK == NCCK_Block) 9154 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9155 else 9156 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9157 break; 9158 } 9159 9160 // In ARC, use some specialized diagnostics for occasions where we 9161 // infer 'const'. These are always pseudo-strong variables. 9162 if (S.getLangOpts().ObjCAutoRefCount) { 9163 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9164 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9165 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9166 9167 // Use the normal diagnostic if it's pseudo-__strong but the 9168 // user actually wrote 'const'. 9169 if (var->isARCPseudoStrong() && 9170 (!var->getTypeSourceInfo() || 9171 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9172 // There are two pseudo-strong cases: 9173 // - self 9174 ObjCMethodDecl *method = S.getCurMethodDecl(); 9175 if (method && var == method->getSelfDecl()) 9176 DiagID = method->isClassMethod() 9177 ? diag::err_typecheck_arc_assign_self_class_method 9178 : diag::err_typecheck_arc_assign_self; 9179 9180 // - fast enumeration variables 9181 else 9182 DiagID = diag::err_typecheck_arr_assign_enumeration; 9183 9184 SourceRange Assign; 9185 if (Loc != OrigLoc) 9186 Assign = SourceRange(OrigLoc, OrigLoc); 9187 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9188 // We need to preserve the AST regardless, so migration tool 9189 // can do its job. 9190 return false; 9191 } 9192 } 9193 } 9194 9195 // If none of the special cases above are triggered, then this is a 9196 // simple const assignment. 9197 if (DiagID == 0) { 9198 DiagnoseConstAssignment(S, E, Loc); 9199 return true; 9200 } 9201 9202 break; 9203 case Expr::MLV_ConstAddrSpace: 9204 DiagnoseConstAssignment(S, E, Loc); 9205 return true; 9206 case Expr::MLV_ArrayType: 9207 case Expr::MLV_ArrayTemporary: 9208 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9209 NeedType = true; 9210 break; 9211 case Expr::MLV_NotObjectType: 9212 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9213 NeedType = true; 9214 break; 9215 case Expr::MLV_LValueCast: 9216 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9217 break; 9218 case Expr::MLV_Valid: 9219 llvm_unreachable("did not take early return for MLV_Valid"); 9220 case Expr::MLV_InvalidExpression: 9221 case Expr::MLV_MemberFunction: 9222 case Expr::MLV_ClassTemporary: 9223 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9224 break; 9225 case Expr::MLV_IncompleteType: 9226 case Expr::MLV_IncompleteVoidType: 9227 return S.RequireCompleteType(Loc, E->getType(), 9228 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9229 case Expr::MLV_DuplicateVectorComponents: 9230 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9231 break; 9232 case Expr::MLV_NoSetterProperty: 9233 llvm_unreachable("readonly properties should be processed differently"); 9234 case Expr::MLV_InvalidMessageExpression: 9235 DiagID = diag::error_readonly_message_assignment; 9236 break; 9237 case Expr::MLV_SubObjCPropertySetting: 9238 DiagID = diag::error_no_subobject_property_setting; 9239 break; 9240 } 9241 9242 SourceRange Assign; 9243 if (Loc != OrigLoc) 9244 Assign = SourceRange(OrigLoc, OrigLoc); 9245 if (NeedType) 9246 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9247 else 9248 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9249 return true; 9250 } 9251 9252 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9253 SourceLocation Loc, 9254 Sema &Sema) { 9255 // C / C++ fields 9256 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9257 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9258 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9259 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9260 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9261 } 9262 9263 // Objective-C instance variables 9264 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9265 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9266 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9267 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9268 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9269 if (RL && RR && RL->getDecl() == RR->getDecl()) 9270 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9271 } 9272 } 9273 9274 // C99 6.5.16.1 9275 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9276 SourceLocation Loc, 9277 QualType CompoundType) { 9278 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9279 9280 // Verify that LHS is a modifiable lvalue, and emit error if not. 9281 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9282 return QualType(); 9283 9284 QualType LHSType = LHSExpr->getType(); 9285 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9286 CompoundType; 9287 AssignConvertType ConvTy; 9288 if (CompoundType.isNull()) { 9289 Expr *RHSCheck = RHS.get(); 9290 9291 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9292 9293 QualType LHSTy(LHSType); 9294 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9295 if (RHS.isInvalid()) 9296 return QualType(); 9297 // Special case of NSObject attributes on c-style pointer types. 9298 if (ConvTy == IncompatiblePointer && 9299 ((Context.isObjCNSObjectType(LHSType) && 9300 RHSType->isObjCObjectPointerType()) || 9301 (Context.isObjCNSObjectType(RHSType) && 9302 LHSType->isObjCObjectPointerType()))) 9303 ConvTy = Compatible; 9304 9305 if (ConvTy == Compatible && 9306 LHSType->isObjCObjectType()) 9307 Diag(Loc, diag::err_objc_object_assignment) 9308 << LHSType; 9309 9310 // If the RHS is a unary plus or minus, check to see if they = and + are 9311 // right next to each other. If so, the user may have typo'd "x =+ 4" 9312 // instead of "x += 4". 9313 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9314 RHSCheck = ICE->getSubExpr(); 9315 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9316 if ((UO->getOpcode() == UO_Plus || 9317 UO->getOpcode() == UO_Minus) && 9318 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9319 // Only if the two operators are exactly adjacent. 9320 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9321 // And there is a space or other character before the subexpr of the 9322 // unary +/-. We don't want to warn on "x=-1". 9323 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9324 UO->getSubExpr()->getLocStart().isFileID()) { 9325 Diag(Loc, diag::warn_not_compound_assign) 9326 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9327 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9328 } 9329 } 9330 9331 if (ConvTy == Compatible) { 9332 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9333 // Warn about retain cycles where a block captures the LHS, but 9334 // not if the LHS is a simple variable into which the block is 9335 // being stored...unless that variable can be captured by reference! 9336 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9337 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9338 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9339 checkRetainCycles(LHSExpr, RHS.get()); 9340 9341 // It is safe to assign a weak reference into a strong variable. 9342 // Although this code can still have problems: 9343 // id x = self.weakProp; 9344 // id y = self.weakProp; 9345 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9346 // paths through the function. This should be revisited if 9347 // -Wrepeated-use-of-weak is made flow-sensitive. 9348 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9349 RHS.get()->getLocStart())) 9350 getCurFunction()->markSafeWeakUse(RHS.get()); 9351 9352 } else if (getLangOpts().ObjCAutoRefCount) { 9353 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9354 } 9355 } 9356 } else { 9357 // Compound assignment "x += y" 9358 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9359 } 9360 9361 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9362 RHS.get(), AA_Assigning)) 9363 return QualType(); 9364 9365 CheckForNullPointerDereference(*this, LHSExpr); 9366 9367 // C99 6.5.16p3: The type of an assignment expression is the type of the 9368 // left operand unless the left operand has qualified type, in which case 9369 // it is the unqualified version of the type of the left operand. 9370 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9371 // is converted to the type of the assignment expression (above). 9372 // C++ 5.17p1: the type of the assignment expression is that of its left 9373 // operand. 9374 return (getLangOpts().CPlusPlus 9375 ? LHSType : LHSType.getUnqualifiedType()); 9376 } 9377 9378 // C99 6.5.17 9379 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9380 SourceLocation Loc) { 9381 LHS = S.CheckPlaceholderExpr(LHS.get()); 9382 RHS = S.CheckPlaceholderExpr(RHS.get()); 9383 if (LHS.isInvalid() || RHS.isInvalid()) 9384 return QualType(); 9385 9386 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9387 // operands, but not unary promotions. 9388 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9389 9390 // So we treat the LHS as a ignored value, and in C++ we allow the 9391 // containing site to determine what should be done with the RHS. 9392 LHS = S.IgnoredValueConversions(LHS.get()); 9393 if (LHS.isInvalid()) 9394 return QualType(); 9395 9396 S.DiagnoseUnusedExprResult(LHS.get()); 9397 9398 if (!S.getLangOpts().CPlusPlus) { 9399 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9400 if (RHS.isInvalid()) 9401 return QualType(); 9402 if (!RHS.get()->getType()->isVoidType()) 9403 S.RequireCompleteType(Loc, RHS.get()->getType(), 9404 diag::err_incomplete_type); 9405 } 9406 9407 return RHS.get()->getType(); 9408 } 9409 9410 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9411 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9412 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9413 ExprValueKind &VK, 9414 ExprObjectKind &OK, 9415 SourceLocation OpLoc, 9416 bool IsInc, bool IsPrefix) { 9417 if (Op->isTypeDependent()) 9418 return S.Context.DependentTy; 9419 9420 QualType ResType = Op->getType(); 9421 // Atomic types can be used for increment / decrement where the non-atomic 9422 // versions can, so ignore the _Atomic() specifier for the purpose of 9423 // checking. 9424 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9425 ResType = ResAtomicType->getValueType(); 9426 9427 assert(!ResType.isNull() && "no type for increment/decrement expression"); 9428 9429 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 9430 // Decrement of bool is not allowed. 9431 if (!IsInc) { 9432 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 9433 return QualType(); 9434 } 9435 // Increment of bool sets it to true, but is deprecated. 9436 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 9437 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 9438 // Error on enum increments and decrements in C++ mode 9439 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 9440 return QualType(); 9441 } else if (ResType->isRealType()) { 9442 // OK! 9443 } else if (ResType->isPointerType()) { 9444 // C99 6.5.2.4p2, 6.5.6p2 9445 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 9446 return QualType(); 9447 } else if (ResType->isObjCObjectPointerType()) { 9448 // On modern runtimes, ObjC pointer arithmetic is forbidden. 9449 // Otherwise, we just need a complete type. 9450 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 9451 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 9452 return QualType(); 9453 } else if (ResType->isAnyComplexType()) { 9454 // C99 does not support ++/-- on complex types, we allow as an extension. 9455 S.Diag(OpLoc, diag::ext_integer_increment_complex) 9456 << ResType << Op->getSourceRange(); 9457 } else if (ResType->isPlaceholderType()) { 9458 ExprResult PR = S.CheckPlaceholderExpr(Op); 9459 if (PR.isInvalid()) return QualType(); 9460 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 9461 IsInc, IsPrefix); 9462 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 9463 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 9464 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 9465 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 9466 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 9467 } else { 9468 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 9469 << ResType << int(IsInc) << Op->getSourceRange(); 9470 return QualType(); 9471 } 9472 // At this point, we know we have a real, complex or pointer type. 9473 // Now make sure the operand is a modifiable lvalue. 9474 if (CheckForModifiableLvalue(Op, OpLoc, S)) 9475 return QualType(); 9476 // In C++, a prefix increment is the same type as the operand. Otherwise 9477 // (in C or with postfix), the increment is the unqualified type of the 9478 // operand. 9479 if (IsPrefix && S.getLangOpts().CPlusPlus) { 9480 VK = VK_LValue; 9481 OK = Op->getObjectKind(); 9482 return ResType; 9483 } else { 9484 VK = VK_RValue; 9485 return ResType.getUnqualifiedType(); 9486 } 9487 } 9488 9489 9490 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 9491 /// This routine allows us to typecheck complex/recursive expressions 9492 /// where the declaration is needed for type checking. We only need to 9493 /// handle cases when the expression references a function designator 9494 /// or is an lvalue. Here are some examples: 9495 /// - &(x) => x 9496 /// - &*****f => f for f a function designator. 9497 /// - &s.xx => s 9498 /// - &s.zz[1].yy -> s, if zz is an array 9499 /// - *(x + 1) -> x, if x is an array 9500 /// - &"123"[2] -> 0 9501 /// - & __real__ x -> x 9502 static ValueDecl *getPrimaryDecl(Expr *E) { 9503 switch (E->getStmtClass()) { 9504 case Stmt::DeclRefExprClass: 9505 return cast<DeclRefExpr>(E)->getDecl(); 9506 case Stmt::MemberExprClass: 9507 // If this is an arrow operator, the address is an offset from 9508 // the base's value, so the object the base refers to is 9509 // irrelevant. 9510 if (cast<MemberExpr>(E)->isArrow()) 9511 return nullptr; 9512 // Otherwise, the expression refers to a part of the base 9513 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 9514 case Stmt::ArraySubscriptExprClass: { 9515 // FIXME: This code shouldn't be necessary! We should catch the implicit 9516 // promotion of register arrays earlier. 9517 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 9518 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 9519 if (ICE->getSubExpr()->getType()->isArrayType()) 9520 return getPrimaryDecl(ICE->getSubExpr()); 9521 } 9522 return nullptr; 9523 } 9524 case Stmt::UnaryOperatorClass: { 9525 UnaryOperator *UO = cast<UnaryOperator>(E); 9526 9527 switch(UO->getOpcode()) { 9528 case UO_Real: 9529 case UO_Imag: 9530 case UO_Extension: 9531 return getPrimaryDecl(UO->getSubExpr()); 9532 default: 9533 return nullptr; 9534 } 9535 } 9536 case Stmt::ParenExprClass: 9537 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 9538 case Stmt::ImplicitCastExprClass: 9539 // If the result of an implicit cast is an l-value, we care about 9540 // the sub-expression; otherwise, the result here doesn't matter. 9541 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 9542 default: 9543 return nullptr; 9544 } 9545 } 9546 9547 namespace { 9548 enum { 9549 AO_Bit_Field = 0, 9550 AO_Vector_Element = 1, 9551 AO_Property_Expansion = 2, 9552 AO_Register_Variable = 3, 9553 AO_No_Error = 4 9554 }; 9555 } 9556 /// \brief Diagnose invalid operand for address of operations. 9557 /// 9558 /// \param Type The type of operand which cannot have its address taken. 9559 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 9560 Expr *E, unsigned Type) { 9561 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 9562 } 9563 9564 /// CheckAddressOfOperand - The operand of & must be either a function 9565 /// designator or an lvalue designating an object. If it is an lvalue, the 9566 /// object cannot be declared with storage class register or be a bit field. 9567 /// Note: The usual conversions are *not* applied to the operand of the & 9568 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 9569 /// In C++, the operand might be an overloaded function name, in which case 9570 /// we allow the '&' but retain the overloaded-function type. 9571 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 9572 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 9573 if (PTy->getKind() == BuiltinType::Overload) { 9574 Expr *E = OrigOp.get()->IgnoreParens(); 9575 if (!isa<OverloadExpr>(E)) { 9576 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 9577 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 9578 << OrigOp.get()->getSourceRange(); 9579 return QualType(); 9580 } 9581 9582 OverloadExpr *Ovl = cast<OverloadExpr>(E); 9583 if (isa<UnresolvedMemberExpr>(Ovl)) 9584 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 9585 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9586 << OrigOp.get()->getSourceRange(); 9587 return QualType(); 9588 } 9589 9590 return Context.OverloadTy; 9591 } 9592 9593 if (PTy->getKind() == BuiltinType::UnknownAny) 9594 return Context.UnknownAnyTy; 9595 9596 if (PTy->getKind() == BuiltinType::BoundMember) { 9597 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9598 << OrigOp.get()->getSourceRange(); 9599 return QualType(); 9600 } 9601 9602 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 9603 if (OrigOp.isInvalid()) return QualType(); 9604 } 9605 9606 if (OrigOp.get()->isTypeDependent()) 9607 return Context.DependentTy; 9608 9609 assert(!OrigOp.get()->getType()->isPlaceholderType()); 9610 9611 // Make sure to ignore parentheses in subsequent checks 9612 Expr *op = OrigOp.get()->IgnoreParens(); 9613 9614 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 9615 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 9616 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 9617 return QualType(); 9618 } 9619 9620 if (getLangOpts().C99) { 9621 // Implement C99-only parts of addressof rules. 9622 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 9623 if (uOp->getOpcode() == UO_Deref) 9624 // Per C99 6.5.3.2, the address of a deref always returns a valid result 9625 // (assuming the deref expression is valid). 9626 return uOp->getSubExpr()->getType(); 9627 } 9628 // Technically, there should be a check for array subscript 9629 // expressions here, but the result of one is always an lvalue anyway. 9630 } 9631 ValueDecl *dcl = getPrimaryDecl(op); 9632 Expr::LValueClassification lval = op->ClassifyLValue(Context); 9633 unsigned AddressOfError = AO_No_Error; 9634 9635 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 9636 bool sfinae = (bool)isSFINAEContext(); 9637 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 9638 : diag::ext_typecheck_addrof_temporary) 9639 << op->getType() << op->getSourceRange(); 9640 if (sfinae) 9641 return QualType(); 9642 // Materialize the temporary as an lvalue so that we can take its address. 9643 OrigOp = op = new (Context) 9644 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 9645 } else if (isa<ObjCSelectorExpr>(op)) { 9646 return Context.getPointerType(op->getType()); 9647 } else if (lval == Expr::LV_MemberFunction) { 9648 // If it's an instance method, make a member pointer. 9649 // The expression must have exactly the form &A::foo. 9650 9651 // If the underlying expression isn't a decl ref, give up. 9652 if (!isa<DeclRefExpr>(op)) { 9653 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9654 << OrigOp.get()->getSourceRange(); 9655 return QualType(); 9656 } 9657 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 9658 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 9659 9660 // The id-expression was parenthesized. 9661 if (OrigOp.get() != DRE) { 9662 Diag(OpLoc, diag::err_parens_pointer_member_function) 9663 << OrigOp.get()->getSourceRange(); 9664 9665 // The method was named without a qualifier. 9666 } else if (!DRE->getQualifier()) { 9667 if (MD->getParent()->getName().empty()) 9668 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9669 << op->getSourceRange(); 9670 else { 9671 SmallString<32> Str; 9672 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 9673 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9674 << op->getSourceRange() 9675 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 9676 } 9677 } 9678 9679 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 9680 if (isa<CXXDestructorDecl>(MD)) 9681 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 9682 9683 QualType MPTy = Context.getMemberPointerType( 9684 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 9685 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9686 RequireCompleteType(OpLoc, MPTy, 0); 9687 return MPTy; 9688 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 9689 // C99 6.5.3.2p1 9690 // The operand must be either an l-value or a function designator 9691 if (!op->getType()->isFunctionType()) { 9692 // Use a special diagnostic for loads from property references. 9693 if (isa<PseudoObjectExpr>(op)) { 9694 AddressOfError = AO_Property_Expansion; 9695 } else { 9696 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 9697 << op->getType() << op->getSourceRange(); 9698 return QualType(); 9699 } 9700 } 9701 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 9702 // The operand cannot be a bit-field 9703 AddressOfError = AO_Bit_Field; 9704 } else if (op->getObjectKind() == OK_VectorComponent) { 9705 // The operand cannot be an element of a vector 9706 AddressOfError = AO_Vector_Element; 9707 } else if (dcl) { // C99 6.5.3.2p1 9708 // We have an lvalue with a decl. Make sure the decl is not declared 9709 // with the register storage-class specifier. 9710 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 9711 // in C++ it is not error to take address of a register 9712 // variable (c++03 7.1.1P3) 9713 if (vd->getStorageClass() == SC_Register && 9714 !getLangOpts().CPlusPlus) { 9715 AddressOfError = AO_Register_Variable; 9716 } 9717 } else if (isa<MSPropertyDecl>(dcl)) { 9718 AddressOfError = AO_Property_Expansion; 9719 } else if (isa<FunctionTemplateDecl>(dcl)) { 9720 return Context.OverloadTy; 9721 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 9722 // Okay: we can take the address of a field. 9723 // Could be a pointer to member, though, if there is an explicit 9724 // scope qualifier for the class. 9725 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 9726 DeclContext *Ctx = dcl->getDeclContext(); 9727 if (Ctx && Ctx->isRecord()) { 9728 if (dcl->getType()->isReferenceType()) { 9729 Diag(OpLoc, 9730 diag::err_cannot_form_pointer_to_member_of_reference_type) 9731 << dcl->getDeclName() << dcl->getType(); 9732 return QualType(); 9733 } 9734 9735 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 9736 Ctx = Ctx->getParent(); 9737 9738 QualType MPTy = Context.getMemberPointerType( 9739 op->getType(), 9740 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 9741 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9742 RequireCompleteType(OpLoc, MPTy, 0); 9743 return MPTy; 9744 } 9745 } 9746 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 9747 llvm_unreachable("Unknown/unexpected decl type"); 9748 } 9749 9750 if (AddressOfError != AO_No_Error) { 9751 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 9752 return QualType(); 9753 } 9754 9755 if (lval == Expr::LV_IncompleteVoidType) { 9756 // Taking the address of a void variable is technically illegal, but we 9757 // allow it in cases which are otherwise valid. 9758 // Example: "extern void x; void* y = &x;". 9759 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 9760 } 9761 9762 // If the operand has type "type", the result has type "pointer to type". 9763 if (op->getType()->isObjCObjectType()) 9764 return Context.getObjCObjectPointerType(op->getType()); 9765 return Context.getPointerType(op->getType()); 9766 } 9767 9768 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 9769 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 9770 if (!DRE) 9771 return; 9772 const Decl *D = DRE->getDecl(); 9773 if (!D) 9774 return; 9775 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 9776 if (!Param) 9777 return; 9778 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 9779 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 9780 return; 9781 if (FunctionScopeInfo *FD = S.getCurFunction()) 9782 if (!FD->ModifiedNonNullParams.count(Param)) 9783 FD->ModifiedNonNullParams.insert(Param); 9784 } 9785 9786 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 9787 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 9788 SourceLocation OpLoc) { 9789 if (Op->isTypeDependent()) 9790 return S.Context.DependentTy; 9791 9792 ExprResult ConvResult = S.UsualUnaryConversions(Op); 9793 if (ConvResult.isInvalid()) 9794 return QualType(); 9795 Op = ConvResult.get(); 9796 QualType OpTy = Op->getType(); 9797 QualType Result; 9798 9799 if (isa<CXXReinterpretCastExpr>(Op)) { 9800 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 9801 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 9802 Op->getSourceRange()); 9803 } 9804 9805 if (const PointerType *PT = OpTy->getAs<PointerType>()) 9806 Result = PT->getPointeeType(); 9807 else if (const ObjCObjectPointerType *OPT = 9808 OpTy->getAs<ObjCObjectPointerType>()) 9809 Result = OPT->getPointeeType(); 9810 else { 9811 ExprResult PR = S.CheckPlaceholderExpr(Op); 9812 if (PR.isInvalid()) return QualType(); 9813 if (PR.get() != Op) 9814 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 9815 } 9816 9817 if (Result.isNull()) { 9818 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 9819 << OpTy << Op->getSourceRange(); 9820 return QualType(); 9821 } 9822 9823 // Note that per both C89 and C99, indirection is always legal, even if Result 9824 // is an incomplete type or void. It would be possible to warn about 9825 // dereferencing a void pointer, but it's completely well-defined, and such a 9826 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 9827 // for pointers to 'void' but is fine for any other pointer type: 9828 // 9829 // C++ [expr.unary.op]p1: 9830 // [...] the expression to which [the unary * operator] is applied shall 9831 // be a pointer to an object type, or a pointer to a function type 9832 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 9833 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 9834 << OpTy << Op->getSourceRange(); 9835 9836 // Dereferences are usually l-values... 9837 VK = VK_LValue; 9838 9839 // ...except that certain expressions are never l-values in C. 9840 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 9841 VK = VK_RValue; 9842 9843 return Result; 9844 } 9845 9846 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 9847 BinaryOperatorKind Opc; 9848 switch (Kind) { 9849 default: llvm_unreachable("Unknown binop!"); 9850 case tok::periodstar: Opc = BO_PtrMemD; break; 9851 case tok::arrowstar: Opc = BO_PtrMemI; break; 9852 case tok::star: Opc = BO_Mul; break; 9853 case tok::slash: Opc = BO_Div; break; 9854 case tok::percent: Opc = BO_Rem; break; 9855 case tok::plus: Opc = BO_Add; break; 9856 case tok::minus: Opc = BO_Sub; break; 9857 case tok::lessless: Opc = BO_Shl; break; 9858 case tok::greatergreater: Opc = BO_Shr; break; 9859 case tok::lessequal: Opc = BO_LE; break; 9860 case tok::less: Opc = BO_LT; break; 9861 case tok::greaterequal: Opc = BO_GE; break; 9862 case tok::greater: Opc = BO_GT; break; 9863 case tok::exclaimequal: Opc = BO_NE; break; 9864 case tok::equalequal: Opc = BO_EQ; break; 9865 case tok::amp: Opc = BO_And; break; 9866 case tok::caret: Opc = BO_Xor; break; 9867 case tok::pipe: Opc = BO_Or; break; 9868 case tok::ampamp: Opc = BO_LAnd; break; 9869 case tok::pipepipe: Opc = BO_LOr; break; 9870 case tok::equal: Opc = BO_Assign; break; 9871 case tok::starequal: Opc = BO_MulAssign; break; 9872 case tok::slashequal: Opc = BO_DivAssign; break; 9873 case tok::percentequal: Opc = BO_RemAssign; break; 9874 case tok::plusequal: Opc = BO_AddAssign; break; 9875 case tok::minusequal: Opc = BO_SubAssign; break; 9876 case tok::lesslessequal: Opc = BO_ShlAssign; break; 9877 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 9878 case tok::ampequal: Opc = BO_AndAssign; break; 9879 case tok::caretequal: Opc = BO_XorAssign; break; 9880 case tok::pipeequal: Opc = BO_OrAssign; break; 9881 case tok::comma: Opc = BO_Comma; break; 9882 } 9883 return Opc; 9884 } 9885 9886 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 9887 tok::TokenKind Kind) { 9888 UnaryOperatorKind Opc; 9889 switch (Kind) { 9890 default: llvm_unreachable("Unknown unary op!"); 9891 case tok::plusplus: Opc = UO_PreInc; break; 9892 case tok::minusminus: Opc = UO_PreDec; break; 9893 case tok::amp: Opc = UO_AddrOf; break; 9894 case tok::star: Opc = UO_Deref; break; 9895 case tok::plus: Opc = UO_Plus; break; 9896 case tok::minus: Opc = UO_Minus; break; 9897 case tok::tilde: Opc = UO_Not; break; 9898 case tok::exclaim: Opc = UO_LNot; break; 9899 case tok::kw___real: Opc = UO_Real; break; 9900 case tok::kw___imag: Opc = UO_Imag; break; 9901 case tok::kw___extension__: Opc = UO_Extension; break; 9902 } 9903 return Opc; 9904 } 9905 9906 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 9907 /// This warning is only emitted for builtin assignment operations. It is also 9908 /// suppressed in the event of macro expansions. 9909 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 9910 SourceLocation OpLoc) { 9911 if (!S.ActiveTemplateInstantiations.empty()) 9912 return; 9913 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 9914 return; 9915 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 9916 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 9917 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 9918 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 9919 if (!LHSDeclRef || !RHSDeclRef || 9920 LHSDeclRef->getLocation().isMacroID() || 9921 RHSDeclRef->getLocation().isMacroID()) 9922 return; 9923 const ValueDecl *LHSDecl = 9924 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 9925 const ValueDecl *RHSDecl = 9926 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 9927 if (LHSDecl != RHSDecl) 9928 return; 9929 if (LHSDecl->getType().isVolatileQualified()) 9930 return; 9931 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9932 if (RefTy->getPointeeType().isVolatileQualified()) 9933 return; 9934 9935 S.Diag(OpLoc, diag::warn_self_assignment) 9936 << LHSDeclRef->getType() 9937 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9938 } 9939 9940 /// Check if a bitwise-& is performed on an Objective-C pointer. This 9941 /// is usually indicative of introspection within the Objective-C pointer. 9942 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9943 SourceLocation OpLoc) { 9944 if (!S.getLangOpts().ObjC1) 9945 return; 9946 9947 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 9948 const Expr *LHS = L.get(); 9949 const Expr *RHS = R.get(); 9950 9951 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9952 ObjCPointerExpr = LHS; 9953 OtherExpr = RHS; 9954 } 9955 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9956 ObjCPointerExpr = RHS; 9957 OtherExpr = LHS; 9958 } 9959 9960 // This warning is deliberately made very specific to reduce false 9961 // positives with logic that uses '&' for hashing. This logic mainly 9962 // looks for code trying to introspect into tagged pointers, which 9963 // code should generally never do. 9964 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9965 unsigned Diag = diag::warn_objc_pointer_masking; 9966 // Determine if we are introspecting the result of performSelectorXXX. 9967 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9968 // Special case messages to -performSelector and friends, which 9969 // can return non-pointer values boxed in a pointer value. 9970 // Some clients may wish to silence warnings in this subcase. 9971 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9972 Selector S = ME->getSelector(); 9973 StringRef SelArg0 = S.getNameForSlot(0); 9974 if (SelArg0.startswith("performSelector")) 9975 Diag = diag::warn_objc_pointer_masking_performSelector; 9976 } 9977 9978 S.Diag(OpLoc, Diag) 9979 << ObjCPointerExpr->getSourceRange(); 9980 } 9981 } 9982 9983 static NamedDecl *getDeclFromExpr(Expr *E) { 9984 if (!E) 9985 return nullptr; 9986 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 9987 return DRE->getDecl(); 9988 if (auto *ME = dyn_cast<MemberExpr>(E)) 9989 return ME->getMemberDecl(); 9990 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 9991 return IRE->getDecl(); 9992 return nullptr; 9993 } 9994 9995 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 9996 /// operator @p Opc at location @c TokLoc. This routine only supports 9997 /// built-in operations; ActOnBinOp handles overloaded operators. 9998 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9999 BinaryOperatorKind Opc, 10000 Expr *LHSExpr, Expr *RHSExpr) { 10001 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10002 // The syntax only allows initializer lists on the RHS of assignment, 10003 // so we don't need to worry about accepting invalid code for 10004 // non-assignment operators. 10005 // C++11 5.17p9: 10006 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10007 // of x = {} is x = T(). 10008 InitializationKind Kind = 10009 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10010 InitializedEntity Entity = 10011 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10012 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10013 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10014 if (Init.isInvalid()) 10015 return Init; 10016 RHSExpr = Init.get(); 10017 } 10018 10019 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10020 QualType ResultTy; // Result type of the binary operator. 10021 // The following two variables are used for compound assignment operators 10022 QualType CompLHSTy; // Type of LHS after promotions for computation 10023 QualType CompResultTy; // Type of computation result 10024 ExprValueKind VK = VK_RValue; 10025 ExprObjectKind OK = OK_Ordinary; 10026 10027 if (!getLangOpts().CPlusPlus) { 10028 // C cannot handle TypoExpr nodes on either side of a binop because it 10029 // doesn't handle dependent types properly, so make sure any TypoExprs have 10030 // been dealt with before checking the operands. 10031 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10032 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10033 if (Opc != BO_Assign) 10034 return ExprResult(E); 10035 // Avoid correcting the RHS to the same Expr as the LHS. 10036 Decl *D = getDeclFromExpr(E); 10037 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10038 }); 10039 if (!LHS.isUsable() || !RHS.isUsable()) 10040 return ExprError(); 10041 } 10042 10043 switch (Opc) { 10044 case BO_Assign: 10045 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10046 if (getLangOpts().CPlusPlus && 10047 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10048 VK = LHS.get()->getValueKind(); 10049 OK = LHS.get()->getObjectKind(); 10050 } 10051 if (!ResultTy.isNull()) { 10052 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10053 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10054 } 10055 RecordModifiableNonNullParam(*this, LHS.get()); 10056 break; 10057 case BO_PtrMemD: 10058 case BO_PtrMemI: 10059 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10060 Opc == BO_PtrMemI); 10061 break; 10062 case BO_Mul: 10063 case BO_Div: 10064 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10065 Opc == BO_Div); 10066 break; 10067 case BO_Rem: 10068 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10069 break; 10070 case BO_Add: 10071 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10072 break; 10073 case BO_Sub: 10074 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10075 break; 10076 case BO_Shl: 10077 case BO_Shr: 10078 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10079 break; 10080 case BO_LE: 10081 case BO_LT: 10082 case BO_GE: 10083 case BO_GT: 10084 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10085 break; 10086 case BO_EQ: 10087 case BO_NE: 10088 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10089 break; 10090 case BO_And: 10091 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10092 case BO_Xor: 10093 case BO_Or: 10094 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10095 break; 10096 case BO_LAnd: 10097 case BO_LOr: 10098 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10099 break; 10100 case BO_MulAssign: 10101 case BO_DivAssign: 10102 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10103 Opc == BO_DivAssign); 10104 CompLHSTy = CompResultTy; 10105 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10106 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10107 break; 10108 case BO_RemAssign: 10109 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10110 CompLHSTy = CompResultTy; 10111 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10112 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10113 break; 10114 case BO_AddAssign: 10115 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10116 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10117 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10118 break; 10119 case BO_SubAssign: 10120 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10121 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10122 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10123 break; 10124 case BO_ShlAssign: 10125 case BO_ShrAssign: 10126 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10127 CompLHSTy = CompResultTy; 10128 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10129 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10130 break; 10131 case BO_AndAssign: 10132 case BO_OrAssign: // fallthrough 10133 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10134 case BO_XorAssign: 10135 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10136 CompLHSTy = CompResultTy; 10137 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10138 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10139 break; 10140 case BO_Comma: 10141 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10142 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10143 VK = RHS.get()->getValueKind(); 10144 OK = RHS.get()->getObjectKind(); 10145 } 10146 break; 10147 } 10148 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10149 return ExprError(); 10150 10151 // Check for array bounds violations for both sides of the BinaryOperator 10152 CheckArrayAccess(LHS.get()); 10153 CheckArrayAccess(RHS.get()); 10154 10155 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10156 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10157 &Context.Idents.get("object_setClass"), 10158 SourceLocation(), LookupOrdinaryName); 10159 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10160 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 10161 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10162 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10163 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10164 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10165 } 10166 else 10167 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10168 } 10169 else if (const ObjCIvarRefExpr *OIRE = 10170 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10171 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10172 10173 if (CompResultTy.isNull()) 10174 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10175 OK, OpLoc, FPFeatures.fp_contract); 10176 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10177 OK_ObjCProperty) { 10178 VK = VK_LValue; 10179 OK = LHS.get()->getObjectKind(); 10180 } 10181 return new (Context) CompoundAssignOperator( 10182 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10183 OpLoc, FPFeatures.fp_contract); 10184 } 10185 10186 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10187 /// operators are mixed in a way that suggests that the programmer forgot that 10188 /// comparison operators have higher precedence. The most typical example of 10189 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10190 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10191 SourceLocation OpLoc, Expr *LHSExpr, 10192 Expr *RHSExpr) { 10193 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10194 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10195 10196 // Check that one of the sides is a comparison operator. 10197 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10198 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10199 if (!isLeftComp && !isRightComp) 10200 return; 10201 10202 // Bitwise operations are sometimes used as eager logical ops. 10203 // Don't diagnose this. 10204 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10205 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10206 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 10207 return; 10208 10209 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10210 OpLoc) 10211 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10212 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10213 SourceRange ParensRange = isLeftComp ? 10214 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10215 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10216 10217 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10218 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10219 SuggestParentheses(Self, OpLoc, 10220 Self.PDiag(diag::note_precedence_silence) << OpStr, 10221 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10222 SuggestParentheses(Self, OpLoc, 10223 Self.PDiag(diag::note_precedence_bitwise_first) 10224 << BinaryOperator::getOpcodeStr(Opc), 10225 ParensRange); 10226 } 10227 10228 /// \brief It accepts a '&' expr that is inside a '|' one. 10229 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 10230 /// in parentheses. 10231 static void 10232 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 10233 BinaryOperator *Bop) { 10234 assert(Bop->getOpcode() == BO_And); 10235 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 10236 << Bop->getSourceRange() << OpLoc; 10237 SuggestParentheses(Self, Bop->getOperatorLoc(), 10238 Self.PDiag(diag::note_precedence_silence) 10239 << Bop->getOpcodeStr(), 10240 Bop->getSourceRange()); 10241 } 10242 10243 /// \brief It accepts a '&&' expr that is inside a '||' one. 10244 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10245 /// in parentheses. 10246 static void 10247 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10248 BinaryOperator *Bop) { 10249 assert(Bop->getOpcode() == BO_LAnd); 10250 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10251 << Bop->getSourceRange() << OpLoc; 10252 SuggestParentheses(Self, Bop->getOperatorLoc(), 10253 Self.PDiag(diag::note_precedence_silence) 10254 << Bop->getOpcodeStr(), 10255 Bop->getSourceRange()); 10256 } 10257 10258 /// \brief Returns true if the given expression can be evaluated as a constant 10259 /// 'true'. 10260 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10261 bool Res; 10262 return !E->isValueDependent() && 10263 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10264 } 10265 10266 /// \brief Returns true if the given expression can be evaluated as a constant 10267 /// 'false'. 10268 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10269 bool Res; 10270 return !E->isValueDependent() && 10271 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10272 } 10273 10274 /// \brief Look for '&&' in the left hand of a '||' expr. 10275 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10276 Expr *LHSExpr, Expr *RHSExpr) { 10277 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10278 if (Bop->getOpcode() == BO_LAnd) { 10279 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10280 if (EvaluatesAsFalse(S, RHSExpr)) 10281 return; 10282 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10283 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10284 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10285 } else if (Bop->getOpcode() == BO_LOr) { 10286 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10287 // If it's "a || b && 1 || c" we didn't warn earlier for 10288 // "a || b && 1", but warn now. 10289 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10290 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10291 } 10292 } 10293 } 10294 } 10295 10296 /// \brief Look for '&&' in the right hand of a '||' expr. 10297 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10298 Expr *LHSExpr, Expr *RHSExpr) { 10299 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10300 if (Bop->getOpcode() == BO_LAnd) { 10301 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10302 if (EvaluatesAsFalse(S, LHSExpr)) 10303 return; 10304 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10305 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10306 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10307 } 10308 } 10309 } 10310 10311 /// \brief Look for '&' in the left or right hand of a '|' expr. 10312 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 10313 Expr *OrArg) { 10314 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 10315 if (Bop->getOpcode() == BO_And) 10316 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 10317 } 10318 } 10319 10320 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10321 Expr *SubExpr, StringRef Shift) { 10322 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10323 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10324 StringRef Op = Bop->getOpcodeStr(); 10325 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10326 << Bop->getSourceRange() << OpLoc << Shift << Op; 10327 SuggestParentheses(S, Bop->getOperatorLoc(), 10328 S.PDiag(diag::note_precedence_silence) << Op, 10329 Bop->getSourceRange()); 10330 } 10331 } 10332 } 10333 10334 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10335 Expr *LHSExpr, Expr *RHSExpr) { 10336 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10337 if (!OCE) 10338 return; 10339 10340 FunctionDecl *FD = OCE->getDirectCallee(); 10341 if (!FD || !FD->isOverloadedOperator()) 10342 return; 10343 10344 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10345 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10346 return; 10347 10348 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10349 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10350 << (Kind == OO_LessLess); 10351 SuggestParentheses(S, OCE->getOperatorLoc(), 10352 S.PDiag(diag::note_precedence_silence) 10353 << (Kind == OO_LessLess ? "<<" : ">>"), 10354 OCE->getSourceRange()); 10355 SuggestParentheses(S, OpLoc, 10356 S.PDiag(diag::note_evaluate_comparison_first), 10357 SourceRange(OCE->getArg(1)->getLocStart(), 10358 RHSExpr->getLocEnd())); 10359 } 10360 10361 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10362 /// precedence. 10363 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10364 SourceLocation OpLoc, Expr *LHSExpr, 10365 Expr *RHSExpr){ 10366 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10367 if (BinaryOperator::isBitwiseOp(Opc)) 10368 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10369 10370 // Diagnose "arg1 & arg2 | arg3" 10371 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10372 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 10373 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 10374 } 10375 10376 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10377 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10378 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10379 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10380 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10381 } 10382 10383 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 10384 || Opc == BO_Shr) { 10385 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 10386 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 10387 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 10388 } 10389 10390 // Warn on overloaded shift operators and comparisons, such as: 10391 // cout << 5 == 4; 10392 if (BinaryOperator::isComparisonOp(Opc)) 10393 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 10394 } 10395 10396 // Binary Operators. 'Tok' is the token for the operator. 10397 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 10398 tok::TokenKind Kind, 10399 Expr *LHSExpr, Expr *RHSExpr) { 10400 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 10401 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 10402 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 10403 10404 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 10405 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 10406 10407 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 10408 } 10409 10410 /// Build an overloaded binary operator expression in the given scope. 10411 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 10412 BinaryOperatorKind Opc, 10413 Expr *LHS, Expr *RHS) { 10414 // Find all of the overloaded operators visible from this 10415 // point. We perform both an operator-name lookup from the local 10416 // scope and an argument-dependent lookup based on the types of 10417 // the arguments. 10418 UnresolvedSet<16> Functions; 10419 OverloadedOperatorKind OverOp 10420 = BinaryOperator::getOverloadedOperator(Opc); 10421 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 10422 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 10423 RHS->getType(), Functions); 10424 10425 // Build the (potentially-overloaded, potentially-dependent) 10426 // binary operation. 10427 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 10428 } 10429 10430 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 10431 BinaryOperatorKind Opc, 10432 Expr *LHSExpr, Expr *RHSExpr) { 10433 // We want to end up calling one of checkPseudoObjectAssignment 10434 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 10435 // both expressions are overloadable or either is type-dependent), 10436 // or CreateBuiltinBinOp (in any other case). We also want to get 10437 // any placeholder types out of the way. 10438 10439 // Handle pseudo-objects in the LHS. 10440 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 10441 // Assignments with a pseudo-object l-value need special analysis. 10442 if (pty->getKind() == BuiltinType::PseudoObject && 10443 BinaryOperator::isAssignmentOp(Opc)) 10444 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 10445 10446 // Don't resolve overloads if the other type is overloadable. 10447 if (pty->getKind() == BuiltinType::Overload) { 10448 // We can't actually test that if we still have a placeholder, 10449 // though. Fortunately, none of the exceptions we see in that 10450 // code below are valid when the LHS is an overload set. Note 10451 // that an overload set can be dependently-typed, but it never 10452 // instantiates to having an overloadable type. 10453 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10454 if (resolvedRHS.isInvalid()) return ExprError(); 10455 RHSExpr = resolvedRHS.get(); 10456 10457 if (RHSExpr->isTypeDependent() || 10458 RHSExpr->getType()->isOverloadableType()) 10459 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10460 } 10461 10462 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 10463 if (LHS.isInvalid()) return ExprError(); 10464 LHSExpr = LHS.get(); 10465 } 10466 10467 // Handle pseudo-objects in the RHS. 10468 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 10469 // An overload in the RHS can potentially be resolved by the type 10470 // being assigned to. 10471 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 10472 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10473 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10474 10475 if (LHSExpr->getType()->isOverloadableType()) 10476 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10477 10478 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10479 } 10480 10481 // Don't resolve overloads if the other type is overloadable. 10482 if (pty->getKind() == BuiltinType::Overload && 10483 LHSExpr->getType()->isOverloadableType()) 10484 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10485 10486 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10487 if (!resolvedRHS.isUsable()) return ExprError(); 10488 RHSExpr = resolvedRHS.get(); 10489 } 10490 10491 if (getLangOpts().CPlusPlus) { 10492 // If either expression is type-dependent, always build an 10493 // overloaded op. 10494 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10495 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10496 10497 // Otherwise, build an overloaded op if either expression has an 10498 // overloadable type. 10499 if (LHSExpr->getType()->isOverloadableType() || 10500 RHSExpr->getType()->isOverloadableType()) 10501 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10502 } 10503 10504 // Build a built-in binary operation. 10505 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10506 } 10507 10508 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 10509 UnaryOperatorKind Opc, 10510 Expr *InputExpr) { 10511 ExprResult Input = InputExpr; 10512 ExprValueKind VK = VK_RValue; 10513 ExprObjectKind OK = OK_Ordinary; 10514 QualType resultType; 10515 switch (Opc) { 10516 case UO_PreInc: 10517 case UO_PreDec: 10518 case UO_PostInc: 10519 case UO_PostDec: 10520 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 10521 OpLoc, 10522 Opc == UO_PreInc || 10523 Opc == UO_PostInc, 10524 Opc == UO_PreInc || 10525 Opc == UO_PreDec); 10526 break; 10527 case UO_AddrOf: 10528 resultType = CheckAddressOfOperand(Input, OpLoc); 10529 RecordModifiableNonNullParam(*this, InputExpr); 10530 break; 10531 case UO_Deref: { 10532 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10533 if (Input.isInvalid()) return ExprError(); 10534 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 10535 break; 10536 } 10537 case UO_Plus: 10538 case UO_Minus: 10539 Input = UsualUnaryConversions(Input.get()); 10540 if (Input.isInvalid()) return ExprError(); 10541 resultType = Input.get()->getType(); 10542 if (resultType->isDependentType()) 10543 break; 10544 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 10545 resultType->isVectorType()) 10546 break; 10547 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 10548 Opc == UO_Plus && 10549 resultType->isPointerType()) 10550 break; 10551 10552 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10553 << resultType << Input.get()->getSourceRange()); 10554 10555 case UO_Not: // bitwise complement 10556 Input = UsualUnaryConversions(Input.get()); 10557 if (Input.isInvalid()) 10558 return ExprError(); 10559 resultType = Input.get()->getType(); 10560 if (resultType->isDependentType()) 10561 break; 10562 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 10563 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 10564 // C99 does not support '~' for complex conjugation. 10565 Diag(OpLoc, diag::ext_integer_complement_complex) 10566 << resultType << Input.get()->getSourceRange(); 10567 else if (resultType->hasIntegerRepresentation()) 10568 break; 10569 else if (resultType->isExtVectorType()) { 10570 if (Context.getLangOpts().OpenCL) { 10571 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 10572 // on vector float types. 10573 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10574 if (!T->isIntegerType()) 10575 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10576 << resultType << Input.get()->getSourceRange()); 10577 } 10578 break; 10579 } else { 10580 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10581 << resultType << Input.get()->getSourceRange()); 10582 } 10583 break; 10584 10585 case UO_LNot: // logical negation 10586 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 10587 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10588 if (Input.isInvalid()) return ExprError(); 10589 resultType = Input.get()->getType(); 10590 10591 // Though we still have to promote half FP to float... 10592 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 10593 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 10594 resultType = Context.FloatTy; 10595 } 10596 10597 if (resultType->isDependentType()) 10598 break; 10599 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 10600 // C99 6.5.3.3p1: ok, fallthrough; 10601 if (Context.getLangOpts().CPlusPlus) { 10602 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 10603 // operand contextually converted to bool. 10604 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 10605 ScalarTypeToBooleanCastKind(resultType)); 10606 } else if (Context.getLangOpts().OpenCL && 10607 Context.getLangOpts().OpenCLVersion < 120) { 10608 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10609 // operate on scalar float types. 10610 if (!resultType->isIntegerType()) 10611 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10612 << resultType << Input.get()->getSourceRange()); 10613 } 10614 } else if (resultType->isExtVectorType()) { 10615 if (Context.getLangOpts().OpenCL && 10616 Context.getLangOpts().OpenCLVersion < 120) { 10617 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10618 // operate on vector float types. 10619 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10620 if (!T->isIntegerType()) 10621 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10622 << resultType << Input.get()->getSourceRange()); 10623 } 10624 // Vector logical not returns the signed variant of the operand type. 10625 resultType = GetSignedVectorType(resultType); 10626 break; 10627 } else { 10628 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10629 << resultType << Input.get()->getSourceRange()); 10630 } 10631 10632 // LNot always has type int. C99 6.5.3.3p5. 10633 // In C++, it's bool. C++ 5.3.1p8 10634 resultType = Context.getLogicalOperationType(); 10635 break; 10636 case UO_Real: 10637 case UO_Imag: 10638 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 10639 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 10640 // complex l-values to ordinary l-values and all other values to r-values. 10641 if (Input.isInvalid()) return ExprError(); 10642 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 10643 if (Input.get()->getValueKind() != VK_RValue && 10644 Input.get()->getObjectKind() == OK_Ordinary) 10645 VK = Input.get()->getValueKind(); 10646 } else if (!getLangOpts().CPlusPlus) { 10647 // In C, a volatile scalar is read by __imag. In C++, it is not. 10648 Input = DefaultLvalueConversion(Input.get()); 10649 } 10650 break; 10651 case UO_Extension: 10652 resultType = Input.get()->getType(); 10653 VK = Input.get()->getValueKind(); 10654 OK = Input.get()->getObjectKind(); 10655 break; 10656 } 10657 if (resultType.isNull() || Input.isInvalid()) 10658 return ExprError(); 10659 10660 // Check for array bounds violations in the operand of the UnaryOperator, 10661 // except for the '*' and '&' operators that have to be handled specially 10662 // by CheckArrayAccess (as there are special cases like &array[arraysize] 10663 // that are explicitly defined as valid by the standard). 10664 if (Opc != UO_AddrOf && Opc != UO_Deref) 10665 CheckArrayAccess(Input.get()); 10666 10667 return new (Context) 10668 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 10669 } 10670 10671 /// \brief Determine whether the given expression is a qualified member 10672 /// access expression, of a form that could be turned into a pointer to member 10673 /// with the address-of operator. 10674 static bool isQualifiedMemberAccess(Expr *E) { 10675 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10676 if (!DRE->getQualifier()) 10677 return false; 10678 10679 ValueDecl *VD = DRE->getDecl(); 10680 if (!VD->isCXXClassMember()) 10681 return false; 10682 10683 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 10684 return true; 10685 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 10686 return Method->isInstance(); 10687 10688 return false; 10689 } 10690 10691 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 10692 if (!ULE->getQualifier()) 10693 return false; 10694 10695 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 10696 DEnd = ULE->decls_end(); 10697 D != DEnd; ++D) { 10698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 10699 if (Method->isInstance()) 10700 return true; 10701 } else { 10702 // Overload set does not contain methods. 10703 break; 10704 } 10705 } 10706 10707 return false; 10708 } 10709 10710 return false; 10711 } 10712 10713 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 10714 UnaryOperatorKind Opc, Expr *Input) { 10715 // First things first: handle placeholders so that the 10716 // overloaded-operator check considers the right type. 10717 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 10718 // Increment and decrement of pseudo-object references. 10719 if (pty->getKind() == BuiltinType::PseudoObject && 10720 UnaryOperator::isIncrementDecrementOp(Opc)) 10721 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 10722 10723 // extension is always a builtin operator. 10724 if (Opc == UO_Extension) 10725 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10726 10727 // & gets special logic for several kinds of placeholder. 10728 // The builtin code knows what to do. 10729 if (Opc == UO_AddrOf && 10730 (pty->getKind() == BuiltinType::Overload || 10731 pty->getKind() == BuiltinType::UnknownAny || 10732 pty->getKind() == BuiltinType::BoundMember)) 10733 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10734 10735 // Anything else needs to be handled now. 10736 ExprResult Result = CheckPlaceholderExpr(Input); 10737 if (Result.isInvalid()) return ExprError(); 10738 Input = Result.get(); 10739 } 10740 10741 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 10742 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 10743 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 10744 // Find all of the overloaded operators visible from this 10745 // point. We perform both an operator-name lookup from the local 10746 // scope and an argument-dependent lookup based on the types of 10747 // the arguments. 10748 UnresolvedSet<16> Functions; 10749 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 10750 if (S && OverOp != OO_None) 10751 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 10752 Functions); 10753 10754 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 10755 } 10756 10757 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10758 } 10759 10760 // Unary Operators. 'Tok' is the token for the operator. 10761 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 10762 tok::TokenKind Op, Expr *Input) { 10763 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 10764 } 10765 10766 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 10767 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 10768 LabelDecl *TheDecl) { 10769 TheDecl->markUsed(Context); 10770 // Create the AST node. The address of a label always has type 'void*'. 10771 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 10772 Context.getPointerType(Context.VoidTy)); 10773 } 10774 10775 /// Given the last statement in a statement-expression, check whether 10776 /// the result is a producing expression (like a call to an 10777 /// ns_returns_retained function) and, if so, rebuild it to hoist the 10778 /// release out of the full-expression. Otherwise, return null. 10779 /// Cannot fail. 10780 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 10781 // Should always be wrapped with one of these. 10782 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 10783 if (!cleanups) return nullptr; 10784 10785 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 10786 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 10787 return nullptr; 10788 10789 // Splice out the cast. This shouldn't modify any interesting 10790 // features of the statement. 10791 Expr *producer = cast->getSubExpr(); 10792 assert(producer->getType() == cast->getType()); 10793 assert(producer->getValueKind() == cast->getValueKind()); 10794 cleanups->setSubExpr(producer); 10795 return cleanups; 10796 } 10797 10798 void Sema::ActOnStartStmtExpr() { 10799 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 10800 } 10801 10802 void Sema::ActOnStmtExprError() { 10803 // Note that function is also called by TreeTransform when leaving a 10804 // StmtExpr scope without rebuilding anything. 10805 10806 DiscardCleanupsInEvaluationContext(); 10807 PopExpressionEvaluationContext(); 10808 } 10809 10810 ExprResult 10811 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 10812 SourceLocation RPLoc) { // "({..})" 10813 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 10814 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 10815 10816 if (hasAnyUnrecoverableErrorsInThisFunction()) 10817 DiscardCleanupsInEvaluationContext(); 10818 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 10819 PopExpressionEvaluationContext(); 10820 10821 // FIXME: there are a variety of strange constraints to enforce here, for 10822 // example, it is not possible to goto into a stmt expression apparently. 10823 // More semantic analysis is needed. 10824 10825 // If there are sub-stmts in the compound stmt, take the type of the last one 10826 // as the type of the stmtexpr. 10827 QualType Ty = Context.VoidTy; 10828 bool StmtExprMayBindToTemp = false; 10829 if (!Compound->body_empty()) { 10830 Stmt *LastStmt = Compound->body_back(); 10831 LabelStmt *LastLabelStmt = nullptr; 10832 // If LastStmt is a label, skip down through into the body. 10833 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 10834 LastLabelStmt = Label; 10835 LastStmt = Label->getSubStmt(); 10836 } 10837 10838 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 10839 // Do function/array conversion on the last expression, but not 10840 // lvalue-to-rvalue. However, initialize an unqualified type. 10841 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 10842 if (LastExpr.isInvalid()) 10843 return ExprError(); 10844 Ty = LastExpr.get()->getType().getUnqualifiedType(); 10845 10846 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 10847 // In ARC, if the final expression ends in a consume, splice 10848 // the consume out and bind it later. In the alternate case 10849 // (when dealing with a retainable type), the result 10850 // initialization will create a produce. In both cases the 10851 // result will be +1, and we'll need to balance that out with 10852 // a bind. 10853 if (Expr *rebuiltLastStmt 10854 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 10855 LastExpr = rebuiltLastStmt; 10856 } else { 10857 LastExpr = PerformCopyInitialization( 10858 InitializedEntity::InitializeResult(LPLoc, 10859 Ty, 10860 false), 10861 SourceLocation(), 10862 LastExpr); 10863 } 10864 10865 if (LastExpr.isInvalid()) 10866 return ExprError(); 10867 if (LastExpr.get() != nullptr) { 10868 if (!LastLabelStmt) 10869 Compound->setLastStmt(LastExpr.get()); 10870 else 10871 LastLabelStmt->setSubStmt(LastExpr.get()); 10872 StmtExprMayBindToTemp = true; 10873 } 10874 } 10875 } 10876 } 10877 10878 // FIXME: Check that expression type is complete/non-abstract; statement 10879 // expressions are not lvalues. 10880 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 10881 if (StmtExprMayBindToTemp) 10882 return MaybeBindToTemporary(ResStmtExpr); 10883 return ResStmtExpr; 10884 } 10885 10886 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 10887 TypeSourceInfo *TInfo, 10888 OffsetOfComponent *CompPtr, 10889 unsigned NumComponents, 10890 SourceLocation RParenLoc) { 10891 QualType ArgTy = TInfo->getType(); 10892 bool Dependent = ArgTy->isDependentType(); 10893 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 10894 10895 // We must have at least one component that refers to the type, and the first 10896 // one is known to be a field designator. Verify that the ArgTy represents 10897 // a struct/union/class. 10898 if (!Dependent && !ArgTy->isRecordType()) 10899 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 10900 << ArgTy << TypeRange); 10901 10902 // Type must be complete per C99 7.17p3 because a declaring a variable 10903 // with an incomplete type would be ill-formed. 10904 if (!Dependent 10905 && RequireCompleteType(BuiltinLoc, ArgTy, 10906 diag::err_offsetof_incomplete_type, TypeRange)) 10907 return ExprError(); 10908 10909 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 10910 // GCC extension, diagnose them. 10911 // FIXME: This diagnostic isn't actually visible because the location is in 10912 // a system header! 10913 if (NumComponents != 1) 10914 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 10915 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 10916 10917 bool DidWarnAboutNonPOD = false; 10918 QualType CurrentType = ArgTy; 10919 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 10920 SmallVector<OffsetOfNode, 4> Comps; 10921 SmallVector<Expr*, 4> Exprs; 10922 for (unsigned i = 0; i != NumComponents; ++i) { 10923 const OffsetOfComponent &OC = CompPtr[i]; 10924 if (OC.isBrackets) { 10925 // Offset of an array sub-field. TODO: Should we allow vector elements? 10926 if (!CurrentType->isDependentType()) { 10927 const ArrayType *AT = Context.getAsArrayType(CurrentType); 10928 if(!AT) 10929 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 10930 << CurrentType); 10931 CurrentType = AT->getElementType(); 10932 } else 10933 CurrentType = Context.DependentTy; 10934 10935 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 10936 if (IdxRval.isInvalid()) 10937 return ExprError(); 10938 Expr *Idx = IdxRval.get(); 10939 10940 // The expression must be an integral expression. 10941 // FIXME: An integral constant expression? 10942 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 10943 !Idx->getType()->isIntegerType()) 10944 return ExprError(Diag(Idx->getLocStart(), 10945 diag::err_typecheck_subscript_not_integer) 10946 << Idx->getSourceRange()); 10947 10948 // Record this array index. 10949 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 10950 Exprs.push_back(Idx); 10951 continue; 10952 } 10953 10954 // Offset of a field. 10955 if (CurrentType->isDependentType()) { 10956 // We have the offset of a field, but we can't look into the dependent 10957 // type. Just record the identifier of the field. 10958 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10959 CurrentType = Context.DependentTy; 10960 continue; 10961 } 10962 10963 // We need to have a complete type to look into. 10964 if (RequireCompleteType(OC.LocStart, CurrentType, 10965 diag::err_offsetof_incomplete_type)) 10966 return ExprError(); 10967 10968 // Look for the designated field. 10969 const RecordType *RC = CurrentType->getAs<RecordType>(); 10970 if (!RC) 10971 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10972 << CurrentType); 10973 RecordDecl *RD = RC->getDecl(); 10974 10975 // C++ [lib.support.types]p5: 10976 // The macro offsetof accepts a restricted set of type arguments in this 10977 // International Standard. type shall be a POD structure or a POD union 10978 // (clause 9). 10979 // C++11 [support.types]p4: 10980 // If type is not a standard-layout class (Clause 9), the results are 10981 // undefined. 10982 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10983 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10984 unsigned DiagID = 10985 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 10986 : diag::ext_offsetof_non_pod_type; 10987 10988 if (!IsSafe && !DidWarnAboutNonPOD && 10989 DiagRuntimeBehavior(BuiltinLoc, nullptr, 10990 PDiag(DiagID) 10991 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10992 << CurrentType)) 10993 DidWarnAboutNonPOD = true; 10994 } 10995 10996 // Look for the field. 10997 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10998 LookupQualifiedName(R, RD); 10999 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11000 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11001 if (!MemberDecl) { 11002 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11003 MemberDecl = IndirectMemberDecl->getAnonField(); 11004 } 11005 11006 if (!MemberDecl) 11007 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11008 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11009 OC.LocEnd)); 11010 11011 // C99 7.17p3: 11012 // (If the specified member is a bit-field, the behavior is undefined.) 11013 // 11014 // We diagnose this as an error. 11015 if (MemberDecl->isBitField()) { 11016 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11017 << MemberDecl->getDeclName() 11018 << SourceRange(BuiltinLoc, RParenLoc); 11019 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11020 return ExprError(); 11021 } 11022 11023 RecordDecl *Parent = MemberDecl->getParent(); 11024 if (IndirectMemberDecl) 11025 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11026 11027 // If the member was found in a base class, introduce OffsetOfNodes for 11028 // the base class indirections. 11029 CXXBasePaths Paths; 11030 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 11031 if (Paths.getDetectedVirtual()) { 11032 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11033 << MemberDecl->getDeclName() 11034 << SourceRange(BuiltinLoc, RParenLoc); 11035 return ExprError(); 11036 } 11037 11038 CXXBasePath &Path = Paths.front(); 11039 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 11040 B != BEnd; ++B) 11041 Comps.push_back(OffsetOfNode(B->Base)); 11042 } 11043 11044 if (IndirectMemberDecl) { 11045 for (auto *FI : IndirectMemberDecl->chain()) { 11046 assert(isa<FieldDecl>(FI)); 11047 Comps.push_back(OffsetOfNode(OC.LocStart, 11048 cast<FieldDecl>(FI), OC.LocEnd)); 11049 } 11050 } else 11051 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11052 11053 CurrentType = MemberDecl->getType().getNonReferenceType(); 11054 } 11055 11056 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11057 Comps, Exprs, RParenLoc); 11058 } 11059 11060 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11061 SourceLocation BuiltinLoc, 11062 SourceLocation TypeLoc, 11063 ParsedType ParsedArgTy, 11064 OffsetOfComponent *CompPtr, 11065 unsigned NumComponents, 11066 SourceLocation RParenLoc) { 11067 11068 TypeSourceInfo *ArgTInfo; 11069 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11070 if (ArgTy.isNull()) 11071 return ExprError(); 11072 11073 if (!ArgTInfo) 11074 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11075 11076 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 11077 RParenLoc); 11078 } 11079 11080 11081 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11082 Expr *CondExpr, 11083 Expr *LHSExpr, Expr *RHSExpr, 11084 SourceLocation RPLoc) { 11085 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11086 11087 ExprValueKind VK = VK_RValue; 11088 ExprObjectKind OK = OK_Ordinary; 11089 QualType resType; 11090 bool ValueDependent = false; 11091 bool CondIsTrue = false; 11092 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11093 resType = Context.DependentTy; 11094 ValueDependent = true; 11095 } else { 11096 // The conditional expression is required to be a constant expression. 11097 llvm::APSInt condEval(32); 11098 ExprResult CondICE 11099 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11100 diag::err_typecheck_choose_expr_requires_constant, false); 11101 if (CondICE.isInvalid()) 11102 return ExprError(); 11103 CondExpr = CondICE.get(); 11104 CondIsTrue = condEval.getZExtValue(); 11105 11106 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11107 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11108 11109 resType = ActiveExpr->getType(); 11110 ValueDependent = ActiveExpr->isValueDependent(); 11111 VK = ActiveExpr->getValueKind(); 11112 OK = ActiveExpr->getObjectKind(); 11113 } 11114 11115 return new (Context) 11116 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11117 CondIsTrue, resType->isDependentType(), ValueDependent); 11118 } 11119 11120 //===----------------------------------------------------------------------===// 11121 // Clang Extensions. 11122 //===----------------------------------------------------------------------===// 11123 11124 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11125 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11126 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11127 11128 if (LangOpts.CPlusPlus) { 11129 Decl *ManglingContextDecl; 11130 if (MangleNumberingContext *MCtx = 11131 getCurrentMangleNumberContext(Block->getDeclContext(), 11132 ManglingContextDecl)) { 11133 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11134 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11135 } 11136 } 11137 11138 PushBlockScope(CurScope, Block); 11139 CurContext->addDecl(Block); 11140 if (CurScope) 11141 PushDeclContext(CurScope, Block); 11142 else 11143 CurContext = Block; 11144 11145 getCurBlock()->HasImplicitReturnType = true; 11146 11147 // Enter a new evaluation context to insulate the block from any 11148 // cleanups from the enclosing full-expression. 11149 PushExpressionEvaluationContext(PotentiallyEvaluated); 11150 } 11151 11152 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11153 Scope *CurScope) { 11154 assert(ParamInfo.getIdentifier() == nullptr && 11155 "block-id should have no identifier!"); 11156 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11157 BlockScopeInfo *CurBlock = getCurBlock(); 11158 11159 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11160 QualType T = Sig->getType(); 11161 11162 // FIXME: We should allow unexpanded parameter packs here, but that would, 11163 // in turn, make the block expression contain unexpanded parameter packs. 11164 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11165 // Drop the parameters. 11166 FunctionProtoType::ExtProtoInfo EPI; 11167 EPI.HasTrailingReturn = false; 11168 EPI.TypeQuals |= DeclSpec::TQ_const; 11169 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11170 Sig = Context.getTrivialTypeSourceInfo(T); 11171 } 11172 11173 // GetTypeForDeclarator always produces a function type for a block 11174 // literal signature. Furthermore, it is always a FunctionProtoType 11175 // unless the function was written with a typedef. 11176 assert(T->isFunctionType() && 11177 "GetTypeForDeclarator made a non-function block signature"); 11178 11179 // Look for an explicit signature in that function type. 11180 FunctionProtoTypeLoc ExplicitSignature; 11181 11182 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11183 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11184 11185 // Check whether that explicit signature was synthesized by 11186 // GetTypeForDeclarator. If so, don't save that as part of the 11187 // written signature. 11188 if (ExplicitSignature.getLocalRangeBegin() == 11189 ExplicitSignature.getLocalRangeEnd()) { 11190 // This would be much cheaper if we stored TypeLocs instead of 11191 // TypeSourceInfos. 11192 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11193 unsigned Size = Result.getFullDataSize(); 11194 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11195 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11196 11197 ExplicitSignature = FunctionProtoTypeLoc(); 11198 } 11199 } 11200 11201 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11202 CurBlock->FunctionType = T; 11203 11204 const FunctionType *Fn = T->getAs<FunctionType>(); 11205 QualType RetTy = Fn->getReturnType(); 11206 bool isVariadic = 11207 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11208 11209 CurBlock->TheDecl->setIsVariadic(isVariadic); 11210 11211 // Context.DependentTy is used as a placeholder for a missing block 11212 // return type. TODO: what should we do with declarators like: 11213 // ^ * { ... } 11214 // If the answer is "apply template argument deduction".... 11215 if (RetTy != Context.DependentTy) { 11216 CurBlock->ReturnType = RetTy; 11217 CurBlock->TheDecl->setBlockMissingReturnType(false); 11218 CurBlock->HasImplicitReturnType = false; 11219 } 11220 11221 // Push block parameters from the declarator if we had them. 11222 SmallVector<ParmVarDecl*, 8> Params; 11223 if (ExplicitSignature) { 11224 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11225 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11226 if (Param->getIdentifier() == nullptr && 11227 !Param->isImplicit() && 11228 !Param->isInvalidDecl() && 11229 !getLangOpts().CPlusPlus) 11230 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11231 Params.push_back(Param); 11232 } 11233 11234 // Fake up parameter variables if we have a typedef, like 11235 // ^ fntype { ... } 11236 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11237 for (const auto &I : Fn->param_types()) { 11238 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11239 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11240 Params.push_back(Param); 11241 } 11242 } 11243 11244 // Set the parameters on the block decl. 11245 if (!Params.empty()) { 11246 CurBlock->TheDecl->setParams(Params); 11247 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11248 CurBlock->TheDecl->param_end(), 11249 /*CheckParameterNames=*/false); 11250 } 11251 11252 // Finally we can process decl attributes. 11253 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11254 11255 // Put the parameter variables in scope. 11256 for (auto AI : CurBlock->TheDecl->params()) { 11257 AI->setOwningFunction(CurBlock->TheDecl); 11258 11259 // If this has an identifier, add it to the scope stack. 11260 if (AI->getIdentifier()) { 11261 CheckShadow(CurBlock->TheScope, AI); 11262 11263 PushOnScopeChains(AI, CurBlock->TheScope); 11264 } 11265 } 11266 } 11267 11268 /// ActOnBlockError - If there is an error parsing a block, this callback 11269 /// is invoked to pop the information about the block from the action impl. 11270 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11271 // Leave the expression-evaluation context. 11272 DiscardCleanupsInEvaluationContext(); 11273 PopExpressionEvaluationContext(); 11274 11275 // Pop off CurBlock, handle nested blocks. 11276 PopDeclContext(); 11277 PopFunctionScopeInfo(); 11278 } 11279 11280 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11281 /// literal was successfully completed. ^(int x){...} 11282 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11283 Stmt *Body, Scope *CurScope) { 11284 // If blocks are disabled, emit an error. 11285 if (!LangOpts.Blocks) 11286 Diag(CaretLoc, diag::err_blocks_disable); 11287 11288 // Leave the expression-evaluation context. 11289 if (hasAnyUnrecoverableErrorsInThisFunction()) 11290 DiscardCleanupsInEvaluationContext(); 11291 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11292 PopExpressionEvaluationContext(); 11293 11294 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11295 11296 if (BSI->HasImplicitReturnType) 11297 deduceClosureReturnType(*BSI); 11298 11299 PopDeclContext(); 11300 11301 QualType RetTy = Context.VoidTy; 11302 if (!BSI->ReturnType.isNull()) 11303 RetTy = BSI->ReturnType; 11304 11305 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11306 QualType BlockTy; 11307 11308 // Set the captured variables on the block. 11309 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11310 SmallVector<BlockDecl::Capture, 4> Captures; 11311 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 11312 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 11313 if (Cap.isThisCapture()) 11314 continue; 11315 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11316 Cap.isNested(), Cap.getInitExpr()); 11317 Captures.push_back(NewCap); 11318 } 11319 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 11320 BSI->CXXThisCaptureIndex != 0); 11321 11322 // If the user wrote a function type in some form, try to use that. 11323 if (!BSI->FunctionType.isNull()) { 11324 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11325 11326 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11327 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11328 11329 // Turn protoless block types into nullary block types. 11330 if (isa<FunctionNoProtoType>(FTy)) { 11331 FunctionProtoType::ExtProtoInfo EPI; 11332 EPI.ExtInfo = Ext; 11333 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11334 11335 // Otherwise, if we don't need to change anything about the function type, 11336 // preserve its sugar structure. 11337 } else if (FTy->getReturnType() == RetTy && 11338 (!NoReturn || FTy->getNoReturnAttr())) { 11339 BlockTy = BSI->FunctionType; 11340 11341 // Otherwise, make the minimal modifications to the function type. 11342 } else { 11343 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11344 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11345 EPI.TypeQuals = 0; // FIXME: silently? 11346 EPI.ExtInfo = Ext; 11347 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11348 } 11349 11350 // If we don't have a function type, just build one from nothing. 11351 } else { 11352 FunctionProtoType::ExtProtoInfo EPI; 11353 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11354 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11355 } 11356 11357 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11358 BSI->TheDecl->param_end()); 11359 BlockTy = Context.getBlockPointerType(BlockTy); 11360 11361 // If needed, diagnose invalid gotos and switches in the block. 11362 if (getCurFunction()->NeedsScopeChecking() && 11363 !PP.isCodeCompletionEnabled()) 11364 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11365 11366 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11367 11368 // Try to apply the named return value optimization. We have to check again 11369 // if we can do this, though, because blocks keep return statements around 11370 // to deduce an implicit return type. 11371 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11372 !BSI->TheDecl->isDependentContext()) 11373 computeNRVO(Body, BSI); 11374 11375 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11376 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11377 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11378 11379 // If the block isn't obviously global, i.e. it captures anything at 11380 // all, then we need to do a few things in the surrounding context: 11381 if (Result->getBlockDecl()->hasCaptures()) { 11382 // First, this expression has a new cleanup object. 11383 ExprCleanupObjects.push_back(Result->getBlockDecl()); 11384 ExprNeedsCleanups = true; 11385 11386 // It also gets a branch-protected scope if any of the captured 11387 // variables needs destruction. 11388 for (const auto &CI : Result->getBlockDecl()->captures()) { 11389 const VarDecl *var = CI.getVariable(); 11390 if (var->getType().isDestructedType() != QualType::DK_none) { 11391 getCurFunction()->setHasBranchProtectedScope(); 11392 break; 11393 } 11394 } 11395 } 11396 11397 return Result; 11398 } 11399 11400 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 11401 Expr *E, ParsedType Ty, 11402 SourceLocation RPLoc) { 11403 TypeSourceInfo *TInfo; 11404 GetTypeFromParser(Ty, &TInfo); 11405 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 11406 } 11407 11408 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 11409 Expr *E, TypeSourceInfo *TInfo, 11410 SourceLocation RPLoc) { 11411 Expr *OrigExpr = E; 11412 11413 // Get the va_list type 11414 QualType VaListType = Context.getBuiltinVaListType(); 11415 if (VaListType->isArrayType()) { 11416 // Deal with implicit array decay; for example, on x86-64, 11417 // va_list is an array, but it's supposed to decay to 11418 // a pointer for va_arg. 11419 VaListType = Context.getArrayDecayedType(VaListType); 11420 // Make sure the input expression also decays appropriately. 11421 ExprResult Result = UsualUnaryConversions(E); 11422 if (Result.isInvalid()) 11423 return ExprError(); 11424 E = Result.get(); 11425 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 11426 // If va_list is a record type and we are compiling in C++ mode, 11427 // check the argument using reference binding. 11428 InitializedEntity Entity 11429 = InitializedEntity::InitializeParameter(Context, 11430 Context.getLValueReferenceType(VaListType), false); 11431 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 11432 if (Init.isInvalid()) 11433 return ExprError(); 11434 E = Init.getAs<Expr>(); 11435 } else { 11436 // Otherwise, the va_list argument must be an l-value because 11437 // it is modified by va_arg. 11438 if (!E->isTypeDependent() && 11439 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11440 return ExprError(); 11441 } 11442 11443 if (!E->isTypeDependent() && 11444 !Context.hasSameType(VaListType, E->getType())) { 11445 return ExprError(Diag(E->getLocStart(), 11446 diag::err_first_argument_to_va_arg_not_of_type_va_list) 11447 << OrigExpr->getType() << E->getSourceRange()); 11448 } 11449 11450 if (!TInfo->getType()->isDependentType()) { 11451 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 11452 diag::err_second_parameter_to_va_arg_incomplete, 11453 TInfo->getTypeLoc())) 11454 return ExprError(); 11455 11456 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 11457 TInfo->getType(), 11458 diag::err_second_parameter_to_va_arg_abstract, 11459 TInfo->getTypeLoc())) 11460 return ExprError(); 11461 11462 if (!TInfo->getType().isPODType(Context)) { 11463 Diag(TInfo->getTypeLoc().getBeginLoc(), 11464 TInfo->getType()->isObjCLifetimeType() 11465 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 11466 : diag::warn_second_parameter_to_va_arg_not_pod) 11467 << TInfo->getType() 11468 << TInfo->getTypeLoc().getSourceRange(); 11469 } 11470 11471 // Check for va_arg where arguments of the given type will be promoted 11472 // (i.e. this va_arg is guaranteed to have undefined behavior). 11473 QualType PromoteType; 11474 if (TInfo->getType()->isPromotableIntegerType()) { 11475 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 11476 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 11477 PromoteType = QualType(); 11478 } 11479 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 11480 PromoteType = Context.DoubleTy; 11481 if (!PromoteType.isNull()) 11482 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 11483 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 11484 << TInfo->getType() 11485 << PromoteType 11486 << TInfo->getTypeLoc().getSourceRange()); 11487 } 11488 11489 QualType T = TInfo->getType().getNonLValueExprType(Context); 11490 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T); 11491 } 11492 11493 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 11494 // The type of __null will be int or long, depending on the size of 11495 // pointers on the target. 11496 QualType Ty; 11497 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 11498 if (pw == Context.getTargetInfo().getIntWidth()) 11499 Ty = Context.IntTy; 11500 else if (pw == Context.getTargetInfo().getLongWidth()) 11501 Ty = Context.LongTy; 11502 else if (pw == Context.getTargetInfo().getLongLongWidth()) 11503 Ty = Context.LongLongTy; 11504 else { 11505 llvm_unreachable("I don't know size of pointer!"); 11506 } 11507 11508 return new (Context) GNUNullExpr(Ty, TokenLoc); 11509 } 11510 11511 bool 11512 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 11513 if (!getLangOpts().ObjC1) 11514 return false; 11515 11516 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 11517 if (!PT) 11518 return false; 11519 11520 if (!PT->isObjCIdType()) { 11521 // Check if the destination is the 'NSString' interface. 11522 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 11523 if (!ID || !ID->getIdentifier()->isStr("NSString")) 11524 return false; 11525 } 11526 11527 // Ignore any parens, implicit casts (should only be 11528 // array-to-pointer decays), and not-so-opaque values. The last is 11529 // important for making this trigger for property assignments. 11530 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 11531 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 11532 if (OV->getSourceExpr()) 11533 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 11534 11535 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 11536 if (!SL || !SL->isAscii()) 11537 return false; 11538 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 11539 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 11540 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 11541 return true; 11542 } 11543 11544 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 11545 SourceLocation Loc, 11546 QualType DstType, QualType SrcType, 11547 Expr *SrcExpr, AssignmentAction Action, 11548 bool *Complained) { 11549 if (Complained) 11550 *Complained = false; 11551 11552 // Decode the result (notice that AST's are still created for extensions). 11553 bool CheckInferredResultType = false; 11554 bool isInvalid = false; 11555 unsigned DiagKind = 0; 11556 FixItHint Hint; 11557 ConversionFixItGenerator ConvHints; 11558 bool MayHaveConvFixit = false; 11559 bool MayHaveFunctionDiff = false; 11560 const ObjCInterfaceDecl *IFace = nullptr; 11561 const ObjCProtocolDecl *PDecl = nullptr; 11562 11563 switch (ConvTy) { 11564 case Compatible: 11565 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 11566 return false; 11567 11568 case PointerToInt: 11569 DiagKind = diag::ext_typecheck_convert_pointer_int; 11570 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11571 MayHaveConvFixit = true; 11572 break; 11573 case IntToPointer: 11574 DiagKind = diag::ext_typecheck_convert_int_pointer; 11575 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11576 MayHaveConvFixit = true; 11577 break; 11578 case IncompatiblePointer: 11579 DiagKind = 11580 (Action == AA_Passing_CFAudited ? 11581 diag::err_arc_typecheck_convert_incompatible_pointer : 11582 diag::ext_typecheck_convert_incompatible_pointer); 11583 CheckInferredResultType = DstType->isObjCObjectPointerType() && 11584 SrcType->isObjCObjectPointerType(); 11585 if (Hint.isNull() && !CheckInferredResultType) { 11586 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11587 } 11588 else if (CheckInferredResultType) { 11589 SrcType = SrcType.getUnqualifiedType(); 11590 DstType = DstType.getUnqualifiedType(); 11591 } 11592 MayHaveConvFixit = true; 11593 break; 11594 case IncompatiblePointerSign: 11595 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 11596 break; 11597 case FunctionVoidPointer: 11598 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 11599 break; 11600 case IncompatiblePointerDiscardsQualifiers: { 11601 // Perform array-to-pointer decay if necessary. 11602 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 11603 11604 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 11605 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 11606 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 11607 DiagKind = diag::err_typecheck_incompatible_address_space; 11608 break; 11609 11610 11611 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 11612 DiagKind = diag::err_typecheck_incompatible_ownership; 11613 break; 11614 } 11615 11616 llvm_unreachable("unknown error case for discarding qualifiers!"); 11617 // fallthrough 11618 } 11619 case CompatiblePointerDiscardsQualifiers: 11620 // If the qualifiers lost were because we were applying the 11621 // (deprecated) C++ conversion from a string literal to a char* 11622 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 11623 // Ideally, this check would be performed in 11624 // checkPointerTypesForAssignment. However, that would require a 11625 // bit of refactoring (so that the second argument is an 11626 // expression, rather than a type), which should be done as part 11627 // of a larger effort to fix checkPointerTypesForAssignment for 11628 // C++ semantics. 11629 if (getLangOpts().CPlusPlus && 11630 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 11631 return false; 11632 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 11633 break; 11634 case IncompatibleNestedPointerQualifiers: 11635 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 11636 break; 11637 case IntToBlockPointer: 11638 DiagKind = diag::err_int_to_block_pointer; 11639 break; 11640 case IncompatibleBlockPointer: 11641 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 11642 break; 11643 case IncompatibleObjCQualifiedId: { 11644 if (SrcType->isObjCQualifiedIdType()) { 11645 const ObjCObjectPointerType *srcOPT = 11646 SrcType->getAs<ObjCObjectPointerType>(); 11647 for (auto *srcProto : srcOPT->quals()) { 11648 PDecl = srcProto; 11649 break; 11650 } 11651 if (const ObjCInterfaceType *IFaceT = 11652 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11653 IFace = IFaceT->getDecl(); 11654 } 11655 else if (DstType->isObjCQualifiedIdType()) { 11656 const ObjCObjectPointerType *dstOPT = 11657 DstType->getAs<ObjCObjectPointerType>(); 11658 for (auto *dstProto : dstOPT->quals()) { 11659 PDecl = dstProto; 11660 break; 11661 } 11662 if (const ObjCInterfaceType *IFaceT = 11663 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11664 IFace = IFaceT->getDecl(); 11665 } 11666 DiagKind = diag::warn_incompatible_qualified_id; 11667 break; 11668 } 11669 case IncompatibleVectors: 11670 DiagKind = diag::warn_incompatible_vectors; 11671 break; 11672 case IncompatibleObjCWeakRef: 11673 DiagKind = diag::err_arc_weak_unavailable_assign; 11674 break; 11675 case Incompatible: 11676 DiagKind = diag::err_typecheck_convert_incompatible; 11677 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11678 MayHaveConvFixit = true; 11679 isInvalid = true; 11680 MayHaveFunctionDiff = true; 11681 break; 11682 } 11683 11684 QualType FirstType, SecondType; 11685 switch (Action) { 11686 case AA_Assigning: 11687 case AA_Initializing: 11688 // The destination type comes first. 11689 FirstType = DstType; 11690 SecondType = SrcType; 11691 break; 11692 11693 case AA_Returning: 11694 case AA_Passing: 11695 case AA_Passing_CFAudited: 11696 case AA_Converting: 11697 case AA_Sending: 11698 case AA_Casting: 11699 // The source type comes first. 11700 FirstType = SrcType; 11701 SecondType = DstType; 11702 break; 11703 } 11704 11705 PartialDiagnostic FDiag = PDiag(DiagKind); 11706 if (Action == AA_Passing_CFAudited) 11707 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 11708 else 11709 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 11710 11711 // If we can fix the conversion, suggest the FixIts. 11712 assert(ConvHints.isNull() || Hint.isNull()); 11713 if (!ConvHints.isNull()) { 11714 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 11715 HE = ConvHints.Hints.end(); HI != HE; ++HI) 11716 FDiag << *HI; 11717 } else { 11718 FDiag << Hint; 11719 } 11720 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 11721 11722 if (MayHaveFunctionDiff) 11723 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 11724 11725 Diag(Loc, FDiag); 11726 if (DiagKind == diag::warn_incompatible_qualified_id && 11727 PDecl && IFace && !IFace->hasDefinition()) 11728 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 11729 << IFace->getName() << PDecl->getName(); 11730 11731 if (SecondType == Context.OverloadTy) 11732 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 11733 FirstType); 11734 11735 if (CheckInferredResultType) 11736 EmitRelatedResultTypeNote(SrcExpr); 11737 11738 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 11739 EmitRelatedResultTypeNoteForReturn(DstType); 11740 11741 if (Complained) 11742 *Complained = true; 11743 return isInvalid; 11744 } 11745 11746 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 11747 llvm::APSInt *Result) { 11748 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 11749 public: 11750 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 11751 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 11752 } 11753 } Diagnoser; 11754 11755 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 11756 } 11757 11758 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 11759 llvm::APSInt *Result, 11760 unsigned DiagID, 11761 bool AllowFold) { 11762 class IDDiagnoser : public VerifyICEDiagnoser { 11763 unsigned DiagID; 11764 11765 public: 11766 IDDiagnoser(unsigned DiagID) 11767 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 11768 11769 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 11770 S.Diag(Loc, DiagID) << SR; 11771 } 11772 } Diagnoser(DiagID); 11773 11774 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 11775 } 11776 11777 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 11778 SourceRange SR) { 11779 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 11780 } 11781 11782 ExprResult 11783 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11784 VerifyICEDiagnoser &Diagnoser, 11785 bool AllowFold) { 11786 SourceLocation DiagLoc = E->getLocStart(); 11787 11788 if (getLangOpts().CPlusPlus11) { 11789 // C++11 [expr.const]p5: 11790 // If an expression of literal class type is used in a context where an 11791 // integral constant expression is required, then that class type shall 11792 // have a single non-explicit conversion function to an integral or 11793 // unscoped enumeration type 11794 ExprResult Converted; 11795 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 11796 public: 11797 CXX11ConvertDiagnoser(bool Silent) 11798 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 11799 Silent, true) {} 11800 11801 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 11802 QualType T) override { 11803 return S.Diag(Loc, diag::err_ice_not_integral) << T; 11804 } 11805 11806 SemaDiagnosticBuilder diagnoseIncomplete( 11807 Sema &S, SourceLocation Loc, QualType T) override { 11808 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 11809 } 11810 11811 SemaDiagnosticBuilder diagnoseExplicitConv( 11812 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 11813 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 11814 } 11815 11816 SemaDiagnosticBuilder noteExplicitConv( 11817 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 11818 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 11819 << ConvTy->isEnumeralType() << ConvTy; 11820 } 11821 11822 SemaDiagnosticBuilder diagnoseAmbiguous( 11823 Sema &S, SourceLocation Loc, QualType T) override { 11824 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 11825 } 11826 11827 SemaDiagnosticBuilder noteAmbiguous( 11828 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 11829 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 11830 << ConvTy->isEnumeralType() << ConvTy; 11831 } 11832 11833 SemaDiagnosticBuilder diagnoseConversion( 11834 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 11835 llvm_unreachable("conversion functions are permitted"); 11836 } 11837 } ConvertDiagnoser(Diagnoser.Suppress); 11838 11839 Converted = PerformContextualImplicitConversion(DiagLoc, E, 11840 ConvertDiagnoser); 11841 if (Converted.isInvalid()) 11842 return Converted; 11843 E = Converted.get(); 11844 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 11845 return ExprError(); 11846 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11847 // An ICE must be of integral or unscoped enumeration type. 11848 if (!Diagnoser.Suppress) 11849 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11850 return ExprError(); 11851 } 11852 11853 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 11854 // in the non-ICE case. 11855 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 11856 if (Result) 11857 *Result = E->EvaluateKnownConstInt(Context); 11858 return E; 11859 } 11860 11861 Expr::EvalResult EvalResult; 11862 SmallVector<PartialDiagnosticAt, 8> Notes; 11863 EvalResult.Diag = &Notes; 11864 11865 // Try to evaluate the expression, and produce diagnostics explaining why it's 11866 // not a constant expression as a side-effect. 11867 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 11868 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 11869 11870 // In C++11, we can rely on diagnostics being produced for any expression 11871 // which is not a constant expression. If no diagnostics were produced, then 11872 // this is a constant expression. 11873 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 11874 if (Result) 11875 *Result = EvalResult.Val.getInt(); 11876 return E; 11877 } 11878 11879 // If our only note is the usual "invalid subexpression" note, just point 11880 // the caret at its location rather than producing an essentially 11881 // redundant note. 11882 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11883 diag::note_invalid_subexpr_in_const_expr) { 11884 DiagLoc = Notes[0].first; 11885 Notes.clear(); 11886 } 11887 11888 if (!Folded || !AllowFold) { 11889 if (!Diagnoser.Suppress) { 11890 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11891 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11892 Diag(Notes[I].first, Notes[I].second); 11893 } 11894 11895 return ExprError(); 11896 } 11897 11898 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 11899 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11900 Diag(Notes[I].first, Notes[I].second); 11901 11902 if (Result) 11903 *Result = EvalResult.Val.getInt(); 11904 return E; 11905 } 11906 11907 namespace { 11908 // Handle the case where we conclude a expression which we speculatively 11909 // considered to be unevaluated is actually evaluated. 11910 class TransformToPE : public TreeTransform<TransformToPE> { 11911 typedef TreeTransform<TransformToPE> BaseTransform; 11912 11913 public: 11914 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 11915 11916 // Make sure we redo semantic analysis 11917 bool AlwaysRebuild() { return true; } 11918 11919 // Make sure we handle LabelStmts correctly. 11920 // FIXME: This does the right thing, but maybe we need a more general 11921 // fix to TreeTransform? 11922 StmtResult TransformLabelStmt(LabelStmt *S) { 11923 S->getDecl()->setStmt(nullptr); 11924 return BaseTransform::TransformLabelStmt(S); 11925 } 11926 11927 // We need to special-case DeclRefExprs referring to FieldDecls which 11928 // are not part of a member pointer formation; normal TreeTransforming 11929 // doesn't catch this case because of the way we represent them in the AST. 11930 // FIXME: This is a bit ugly; is it really the best way to handle this 11931 // case? 11932 // 11933 // Error on DeclRefExprs referring to FieldDecls. 11934 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 11935 if (isa<FieldDecl>(E->getDecl()) && 11936 !SemaRef.isUnevaluatedContext()) 11937 return SemaRef.Diag(E->getLocation(), 11938 diag::err_invalid_non_static_member_use) 11939 << E->getDecl() << E->getSourceRange(); 11940 11941 return BaseTransform::TransformDeclRefExpr(E); 11942 } 11943 11944 // Exception: filter out member pointer formation 11945 ExprResult TransformUnaryOperator(UnaryOperator *E) { 11946 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 11947 return E; 11948 11949 return BaseTransform::TransformUnaryOperator(E); 11950 } 11951 11952 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11953 // Lambdas never need to be transformed. 11954 return E; 11955 } 11956 }; 11957 } 11958 11959 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 11960 assert(isUnevaluatedContext() && 11961 "Should only transform unevaluated expressions"); 11962 ExprEvalContexts.back().Context = 11963 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 11964 if (isUnevaluatedContext()) 11965 return E; 11966 return TransformToPE(*this).TransformExpr(E); 11967 } 11968 11969 void 11970 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11971 Decl *LambdaContextDecl, 11972 bool IsDecltype) { 11973 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 11974 ExprNeedsCleanups, LambdaContextDecl, 11975 IsDecltype); 11976 ExprNeedsCleanups = false; 11977 if (!MaybeODRUseExprs.empty()) 11978 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11979 } 11980 11981 void 11982 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11983 ReuseLambdaContextDecl_t, 11984 bool IsDecltype) { 11985 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11986 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11987 } 11988 11989 void Sema::PopExpressionEvaluationContext() { 11990 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11991 unsigned NumTypos = Rec.NumTypos; 11992 11993 if (!Rec.Lambdas.empty()) { 11994 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11995 unsigned D; 11996 if (Rec.isUnevaluated()) { 11997 // C++11 [expr.prim.lambda]p2: 11998 // A lambda-expression shall not appear in an unevaluated operand 11999 // (Clause 5). 12000 D = diag::err_lambda_unevaluated_operand; 12001 } else { 12002 // C++1y [expr.const]p2: 12003 // A conditional-expression e is a core constant expression unless the 12004 // evaluation of e, following the rules of the abstract machine, would 12005 // evaluate [...] a lambda-expression. 12006 D = diag::err_lambda_in_constant_expression; 12007 } 12008 for (const auto *L : Rec.Lambdas) 12009 Diag(L->getLocStart(), D); 12010 } else { 12011 // Mark the capture expressions odr-used. This was deferred 12012 // during lambda expression creation. 12013 for (auto *Lambda : Rec.Lambdas) { 12014 for (auto *C : Lambda->capture_inits()) 12015 MarkDeclarationsReferencedInExpr(C); 12016 } 12017 } 12018 } 12019 12020 // When are coming out of an unevaluated context, clear out any 12021 // temporaries that we may have created as part of the evaluation of 12022 // the expression in that context: they aren't relevant because they 12023 // will never be constructed. 12024 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12025 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12026 ExprCleanupObjects.end()); 12027 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12028 CleanupVarDeclMarking(); 12029 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12030 // Otherwise, merge the contexts together. 12031 } else { 12032 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12033 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12034 Rec.SavedMaybeODRUseExprs.end()); 12035 } 12036 12037 // Pop the current expression evaluation context off the stack. 12038 ExprEvalContexts.pop_back(); 12039 12040 if (!ExprEvalContexts.empty()) 12041 ExprEvalContexts.back().NumTypos += NumTypos; 12042 else 12043 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12044 "last ExpressionEvaluationContextRecord"); 12045 } 12046 12047 void Sema::DiscardCleanupsInEvaluationContext() { 12048 ExprCleanupObjects.erase( 12049 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12050 ExprCleanupObjects.end()); 12051 ExprNeedsCleanups = false; 12052 MaybeODRUseExprs.clear(); 12053 } 12054 12055 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12056 if (!E->getType()->isVariablyModifiedType()) 12057 return E; 12058 return TransformToPotentiallyEvaluated(E); 12059 } 12060 12061 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12062 // Do not mark anything as "used" within a dependent context; wait for 12063 // an instantiation. 12064 if (SemaRef.CurContext->isDependentContext()) 12065 return false; 12066 12067 switch (SemaRef.ExprEvalContexts.back().Context) { 12068 case Sema::Unevaluated: 12069 case Sema::UnevaluatedAbstract: 12070 // We are in an expression that is not potentially evaluated; do nothing. 12071 // (Depending on how you read the standard, we actually do need to do 12072 // something here for null pointer constants, but the standard's 12073 // definition of a null pointer constant is completely crazy.) 12074 return false; 12075 12076 case Sema::ConstantEvaluated: 12077 case Sema::PotentiallyEvaluated: 12078 // We are in a potentially evaluated expression (or a constant-expression 12079 // in C++03); we need to do implicit template instantiation, implicitly 12080 // define class members, and mark most declarations as used. 12081 return true; 12082 12083 case Sema::PotentiallyEvaluatedIfUsed: 12084 // Referenced declarations will only be used if the construct in the 12085 // containing expression is used. 12086 return false; 12087 } 12088 llvm_unreachable("Invalid context"); 12089 } 12090 12091 /// \brief Mark a function referenced, and check whether it is odr-used 12092 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12093 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12094 bool OdrUse) { 12095 assert(Func && "No function?"); 12096 12097 Func->setReferenced(); 12098 12099 // C++11 [basic.def.odr]p3: 12100 // A function whose name appears as a potentially-evaluated expression is 12101 // odr-used if it is the unique lookup result or the selected member of a 12102 // set of overloaded functions [...]. 12103 // 12104 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12105 // can just check that here. Skip the rest of this function if we've already 12106 // marked the function as used. 12107 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12108 !IsPotentiallyEvaluatedContext(*this)) { 12109 // C++11 [temp.inst]p3: 12110 // Unless a function template specialization has been explicitly 12111 // instantiated or explicitly specialized, the function template 12112 // specialization is implicitly instantiated when the specialization is 12113 // referenced in a context that requires a function definition to exist. 12114 // 12115 // We consider constexpr function templates to be referenced in a context 12116 // that requires a definition to exist whenever they are referenced. 12117 // 12118 // FIXME: This instantiates constexpr functions too frequently. If this is 12119 // really an unevaluated context (and we're not just in the definition of a 12120 // function template or overload resolution or other cases which we 12121 // incorrectly consider to be unevaluated contexts), and we're not in a 12122 // subexpression which we actually need to evaluate (for instance, a 12123 // template argument, array bound or an expression in a braced-init-list), 12124 // we are not permitted to instantiate this constexpr function definition. 12125 // 12126 // FIXME: This also implicitly defines special members too frequently. They 12127 // are only supposed to be implicitly defined if they are odr-used, but they 12128 // are not odr-used from constant expressions in unevaluated contexts. 12129 // However, they cannot be referenced if they are deleted, and they are 12130 // deleted whenever the implicit definition of the special member would 12131 // fail. 12132 if (!Func->isConstexpr() || Func->getBody()) 12133 return; 12134 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12135 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12136 return; 12137 } 12138 12139 // Note that this declaration has been used. 12140 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12141 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12142 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12143 if (Constructor->isDefaultConstructor()) { 12144 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12145 return; 12146 DefineImplicitDefaultConstructor(Loc, Constructor); 12147 } else if (Constructor->isCopyConstructor()) { 12148 DefineImplicitCopyConstructor(Loc, Constructor); 12149 } else if (Constructor->isMoveConstructor()) { 12150 DefineImplicitMoveConstructor(Loc, Constructor); 12151 } 12152 } else if (Constructor->getInheritedConstructor()) { 12153 DefineInheritingConstructor(Loc, Constructor); 12154 } 12155 } else if (CXXDestructorDecl *Destructor = 12156 dyn_cast<CXXDestructorDecl>(Func)) { 12157 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12158 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12159 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12160 return; 12161 DefineImplicitDestructor(Loc, Destructor); 12162 } 12163 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12164 MarkVTableUsed(Loc, Destructor->getParent()); 12165 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12166 if (MethodDecl->isOverloadedOperator() && 12167 MethodDecl->getOverloadedOperator() == OO_Equal) { 12168 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12169 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12170 if (MethodDecl->isCopyAssignmentOperator()) 12171 DefineImplicitCopyAssignment(Loc, MethodDecl); 12172 else 12173 DefineImplicitMoveAssignment(Loc, MethodDecl); 12174 } 12175 } else if (isa<CXXConversionDecl>(MethodDecl) && 12176 MethodDecl->getParent()->isLambda()) { 12177 CXXConversionDecl *Conversion = 12178 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12179 if (Conversion->isLambdaToBlockPointerConversion()) 12180 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12181 else 12182 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12183 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12184 MarkVTableUsed(Loc, MethodDecl->getParent()); 12185 } 12186 12187 // Recursive functions should be marked when used from another function. 12188 // FIXME: Is this really right? 12189 if (CurContext == Func) return; 12190 12191 // Resolve the exception specification for any function which is 12192 // used: CodeGen will need it. 12193 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12194 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12195 ResolveExceptionSpec(Loc, FPT); 12196 12197 if (!OdrUse) return; 12198 12199 // Implicit instantiation of function templates and member functions of 12200 // class templates. 12201 if (Func->isImplicitlyInstantiable()) { 12202 bool AlreadyInstantiated = false; 12203 SourceLocation PointOfInstantiation = Loc; 12204 if (FunctionTemplateSpecializationInfo *SpecInfo 12205 = Func->getTemplateSpecializationInfo()) { 12206 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12207 SpecInfo->setPointOfInstantiation(Loc); 12208 else if (SpecInfo->getTemplateSpecializationKind() 12209 == TSK_ImplicitInstantiation) { 12210 AlreadyInstantiated = true; 12211 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12212 } 12213 } else if (MemberSpecializationInfo *MSInfo 12214 = Func->getMemberSpecializationInfo()) { 12215 if (MSInfo->getPointOfInstantiation().isInvalid()) 12216 MSInfo->setPointOfInstantiation(Loc); 12217 else if (MSInfo->getTemplateSpecializationKind() 12218 == TSK_ImplicitInstantiation) { 12219 AlreadyInstantiated = true; 12220 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12221 } 12222 } 12223 12224 if (!AlreadyInstantiated || Func->isConstexpr()) { 12225 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12226 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12227 ActiveTemplateInstantiations.size()) 12228 PendingLocalImplicitInstantiations.push_back( 12229 std::make_pair(Func, PointOfInstantiation)); 12230 else if (Func->isConstexpr()) 12231 // Do not defer instantiations of constexpr functions, to avoid the 12232 // expression evaluator needing to call back into Sema if it sees a 12233 // call to such a function. 12234 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12235 else { 12236 PendingInstantiations.push_back(std::make_pair(Func, 12237 PointOfInstantiation)); 12238 // Notify the consumer that a function was implicitly instantiated. 12239 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12240 } 12241 } 12242 } else { 12243 // Walk redefinitions, as some of them may be instantiable. 12244 for (auto i : Func->redecls()) { 12245 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12246 MarkFunctionReferenced(Loc, i); 12247 } 12248 } 12249 12250 // Keep track of used but undefined functions. 12251 if (!Func->isDefined()) { 12252 if (mightHaveNonExternalLinkage(Func)) 12253 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12254 else if (Func->getMostRecentDecl()->isInlined() && 12255 !LangOpts.GNUInline && 12256 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12257 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12258 } 12259 12260 // Normally the most current decl is marked used while processing the use and 12261 // any subsequent decls are marked used by decl merging. This fails with 12262 // template instantiation since marking can happen at the end of the file 12263 // and, because of the two phase lookup, this function is called with at 12264 // decl in the middle of a decl chain. We loop to maintain the invariant 12265 // that once a decl is used, all decls after it are also used. 12266 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12267 F->markUsed(Context); 12268 if (F == Func) 12269 break; 12270 } 12271 } 12272 12273 static void 12274 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12275 VarDecl *var, DeclContext *DC) { 12276 DeclContext *VarDC = var->getDeclContext(); 12277 12278 // If the parameter still belongs to the translation unit, then 12279 // we're actually just using one parameter in the declaration of 12280 // the next. 12281 if (isa<ParmVarDecl>(var) && 12282 isa<TranslationUnitDecl>(VarDC)) 12283 return; 12284 12285 // For C code, don't diagnose about capture if we're not actually in code 12286 // right now; it's impossible to write a non-constant expression outside of 12287 // function context, so we'll get other (more useful) diagnostics later. 12288 // 12289 // For C++, things get a bit more nasty... it would be nice to suppress this 12290 // diagnostic for certain cases like using a local variable in an array bound 12291 // for a member of a local class, but the correct predicate is not obvious. 12292 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12293 return; 12294 12295 if (isa<CXXMethodDecl>(VarDC) && 12296 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12297 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12298 << var->getIdentifier(); 12299 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12300 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12301 << var->getIdentifier() << fn->getDeclName(); 12302 } else if (isa<BlockDecl>(VarDC)) { 12303 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12304 << var->getIdentifier(); 12305 } else { 12306 // FIXME: Is there any other context where a local variable can be 12307 // declared? 12308 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12309 << var->getIdentifier(); 12310 } 12311 12312 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12313 << var->getIdentifier(); 12314 12315 // FIXME: Add additional diagnostic info about class etc. which prevents 12316 // capture. 12317 } 12318 12319 12320 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12321 bool &SubCapturesAreNested, 12322 QualType &CaptureType, 12323 QualType &DeclRefType) { 12324 // Check whether we've already captured it. 12325 if (CSI->CaptureMap.count(Var)) { 12326 // If we found a capture, any subcaptures are nested. 12327 SubCapturesAreNested = true; 12328 12329 // Retrieve the capture type for this variable. 12330 CaptureType = CSI->getCapture(Var).getCaptureType(); 12331 12332 // Compute the type of an expression that refers to this variable. 12333 DeclRefType = CaptureType.getNonReferenceType(); 12334 12335 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 12336 if (Cap.isCopyCapture() && 12337 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 12338 DeclRefType.addConst(); 12339 return true; 12340 } 12341 return false; 12342 } 12343 12344 // Only block literals, captured statements, and lambda expressions can 12345 // capture; other scopes don't work. 12346 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 12347 SourceLocation Loc, 12348 const bool Diagnose, Sema &S) { 12349 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 12350 return getLambdaAwareParentOfDeclContext(DC); 12351 else if (Var->hasLocalStorage()) { 12352 if (Diagnose) 12353 diagnoseUncapturableValueReference(S, Loc, Var, DC); 12354 } 12355 return nullptr; 12356 } 12357 12358 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12359 // certain types of variables (unnamed, variably modified types etc.) 12360 // so check for eligibility. 12361 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 12362 SourceLocation Loc, 12363 const bool Diagnose, Sema &S) { 12364 12365 bool IsBlock = isa<BlockScopeInfo>(CSI); 12366 bool IsLambda = isa<LambdaScopeInfo>(CSI); 12367 12368 // Lambdas are not allowed to capture unnamed variables 12369 // (e.g. anonymous unions). 12370 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 12371 // assuming that's the intent. 12372 if (IsLambda && !Var->getDeclName()) { 12373 if (Diagnose) { 12374 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 12375 S.Diag(Var->getLocation(), diag::note_declared_at); 12376 } 12377 return false; 12378 } 12379 12380 // Prohibit variably-modified types in blocks; they're difficult to deal with. 12381 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 12382 if (Diagnose) { 12383 S.Diag(Loc, diag::err_ref_vm_type); 12384 S.Diag(Var->getLocation(), diag::note_previous_decl) 12385 << Var->getDeclName(); 12386 } 12387 return false; 12388 } 12389 // Prohibit structs with flexible array members too. 12390 // We cannot capture what is in the tail end of the struct. 12391 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 12392 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 12393 if (Diagnose) { 12394 if (IsBlock) 12395 S.Diag(Loc, diag::err_ref_flexarray_type); 12396 else 12397 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 12398 << Var->getDeclName(); 12399 S.Diag(Var->getLocation(), diag::note_previous_decl) 12400 << Var->getDeclName(); 12401 } 12402 return false; 12403 } 12404 } 12405 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12406 // Lambdas and captured statements are not allowed to capture __block 12407 // variables; they don't support the expected semantics. 12408 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 12409 if (Diagnose) { 12410 S.Diag(Loc, diag::err_capture_block_variable) 12411 << Var->getDeclName() << !IsLambda; 12412 S.Diag(Var->getLocation(), diag::note_previous_decl) 12413 << Var->getDeclName(); 12414 } 12415 return false; 12416 } 12417 12418 return true; 12419 } 12420 12421 // Returns true if the capture by block was successful. 12422 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 12423 SourceLocation Loc, 12424 const bool BuildAndDiagnose, 12425 QualType &CaptureType, 12426 QualType &DeclRefType, 12427 const bool Nested, 12428 Sema &S) { 12429 Expr *CopyExpr = nullptr; 12430 bool ByRef = false; 12431 12432 // Blocks are not allowed to capture arrays. 12433 if (CaptureType->isArrayType()) { 12434 if (BuildAndDiagnose) { 12435 S.Diag(Loc, diag::err_ref_array_type); 12436 S.Diag(Var->getLocation(), diag::note_previous_decl) 12437 << Var->getDeclName(); 12438 } 12439 return false; 12440 } 12441 12442 // Forbid the block-capture of autoreleasing variables. 12443 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12444 if (BuildAndDiagnose) { 12445 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 12446 << /*block*/ 0; 12447 S.Diag(Var->getLocation(), diag::note_previous_decl) 12448 << Var->getDeclName(); 12449 } 12450 return false; 12451 } 12452 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12453 if (HasBlocksAttr || CaptureType->isReferenceType()) { 12454 // Block capture by reference does not change the capture or 12455 // declaration reference types. 12456 ByRef = true; 12457 } else { 12458 // Block capture by copy introduces 'const'. 12459 CaptureType = CaptureType.getNonReferenceType().withConst(); 12460 DeclRefType = CaptureType; 12461 12462 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 12463 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 12464 // The capture logic needs the destructor, so make sure we mark it. 12465 // Usually this is unnecessary because most local variables have 12466 // their destructors marked at declaration time, but parameters are 12467 // an exception because it's technically only the call site that 12468 // actually requires the destructor. 12469 if (isa<ParmVarDecl>(Var)) 12470 S.FinalizeVarWithDestructor(Var, Record); 12471 12472 // Enter a new evaluation context to insulate the copy 12473 // full-expression. 12474 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 12475 12476 // According to the blocks spec, the capture of a variable from 12477 // the stack requires a const copy constructor. This is not true 12478 // of the copy/move done to move a __block variable to the heap. 12479 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 12480 DeclRefType.withConst(), 12481 VK_LValue, Loc); 12482 12483 ExprResult Result 12484 = S.PerformCopyInitialization( 12485 InitializedEntity::InitializeBlock(Var->getLocation(), 12486 CaptureType, false), 12487 Loc, DeclRef); 12488 12489 // Build a full-expression copy expression if initialization 12490 // succeeded and used a non-trivial constructor. Recover from 12491 // errors by pretending that the copy isn't necessary. 12492 if (!Result.isInvalid() && 12493 !cast<CXXConstructExpr>(Result.get())->getConstructor() 12494 ->isTrivial()) { 12495 Result = S.MaybeCreateExprWithCleanups(Result); 12496 CopyExpr = Result.get(); 12497 } 12498 } 12499 } 12500 } 12501 12502 // Actually capture the variable. 12503 if (BuildAndDiagnose) 12504 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 12505 SourceLocation(), CaptureType, CopyExpr); 12506 12507 return true; 12508 12509 } 12510 12511 12512 /// \brief Capture the given variable in the captured region. 12513 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 12514 VarDecl *Var, 12515 SourceLocation Loc, 12516 const bool BuildAndDiagnose, 12517 QualType &CaptureType, 12518 QualType &DeclRefType, 12519 const bool RefersToCapturedVariable, 12520 Sema &S) { 12521 12522 // By default, capture variables by reference. 12523 bool ByRef = true; 12524 // Using an LValue reference type is consistent with Lambdas (see below). 12525 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12526 Expr *CopyExpr = nullptr; 12527 if (BuildAndDiagnose) { 12528 // The current implementation assumes that all variables are captured 12529 // by references. Since there is no capture by copy, no expression 12530 // evaluation will be needed. 12531 RecordDecl *RD = RSI->TheRecordDecl; 12532 12533 FieldDecl *Field 12534 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 12535 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 12536 nullptr, false, ICIS_NoInit); 12537 Field->setImplicit(true); 12538 Field->setAccess(AS_private); 12539 RD->addDecl(Field); 12540 12541 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 12542 DeclRefType, VK_LValue, Loc); 12543 Var->setReferenced(true); 12544 Var->markUsed(S.Context); 12545 } 12546 12547 // Actually capture the variable. 12548 if (BuildAndDiagnose) 12549 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 12550 SourceLocation(), CaptureType, CopyExpr); 12551 12552 12553 return true; 12554 } 12555 12556 /// \brief Create a field within the lambda class for the variable 12557 /// being captured. 12558 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 12559 QualType FieldType, QualType DeclRefType, 12560 SourceLocation Loc, 12561 bool RefersToCapturedVariable) { 12562 CXXRecordDecl *Lambda = LSI->Lambda; 12563 12564 // Build the non-static data member. 12565 FieldDecl *Field 12566 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 12567 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 12568 nullptr, false, ICIS_NoInit); 12569 Field->setImplicit(true); 12570 Field->setAccess(AS_private); 12571 Lambda->addDecl(Field); 12572 } 12573 12574 /// \brief Capture the given variable in the lambda. 12575 static bool captureInLambda(LambdaScopeInfo *LSI, 12576 VarDecl *Var, 12577 SourceLocation Loc, 12578 const bool BuildAndDiagnose, 12579 QualType &CaptureType, 12580 QualType &DeclRefType, 12581 const bool RefersToCapturedVariable, 12582 const Sema::TryCaptureKind Kind, 12583 SourceLocation EllipsisLoc, 12584 const bool IsTopScope, 12585 Sema &S) { 12586 12587 // Determine whether we are capturing by reference or by value. 12588 bool ByRef = false; 12589 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 12590 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 12591 } else { 12592 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 12593 } 12594 12595 // Compute the type of the field that will capture this variable. 12596 if (ByRef) { 12597 // C++11 [expr.prim.lambda]p15: 12598 // An entity is captured by reference if it is implicitly or 12599 // explicitly captured but not captured by copy. It is 12600 // unspecified whether additional unnamed non-static data 12601 // members are declared in the closure type for entities 12602 // captured by reference. 12603 // 12604 // FIXME: It is not clear whether we want to build an lvalue reference 12605 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 12606 // to do the former, while EDG does the latter. Core issue 1249 will 12607 // clarify, but for now we follow GCC because it's a more permissive and 12608 // easily defensible position. 12609 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12610 } else { 12611 // C++11 [expr.prim.lambda]p14: 12612 // For each entity captured by copy, an unnamed non-static 12613 // data member is declared in the closure type. The 12614 // declaration order of these members is unspecified. The type 12615 // of such a data member is the type of the corresponding 12616 // captured entity if the entity is not a reference to an 12617 // object, or the referenced type otherwise. [Note: If the 12618 // captured entity is a reference to a function, the 12619 // corresponding data member is also a reference to a 12620 // function. - end note ] 12621 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 12622 if (!RefType->getPointeeType()->isFunctionType()) 12623 CaptureType = RefType->getPointeeType(); 12624 } 12625 12626 // Forbid the lambda copy-capture of autoreleasing variables. 12627 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12628 if (BuildAndDiagnose) { 12629 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 12630 S.Diag(Var->getLocation(), diag::note_previous_decl) 12631 << Var->getDeclName(); 12632 } 12633 return false; 12634 } 12635 12636 // Make sure that by-copy captures are of a complete and non-abstract type. 12637 if (BuildAndDiagnose) { 12638 if (!CaptureType->isDependentType() && 12639 S.RequireCompleteType(Loc, CaptureType, 12640 diag::err_capture_of_incomplete_type, 12641 Var->getDeclName())) 12642 return false; 12643 12644 if (S.RequireNonAbstractType(Loc, CaptureType, 12645 diag::err_capture_of_abstract_type)) 12646 return false; 12647 } 12648 } 12649 12650 // Capture this variable in the lambda. 12651 if (BuildAndDiagnose) 12652 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 12653 RefersToCapturedVariable); 12654 12655 // Compute the type of a reference to this captured variable. 12656 if (ByRef) 12657 DeclRefType = CaptureType.getNonReferenceType(); 12658 else { 12659 // C++ [expr.prim.lambda]p5: 12660 // The closure type for a lambda-expression has a public inline 12661 // function call operator [...]. This function call operator is 12662 // declared const (9.3.1) if and only if the lambda-expression’s 12663 // parameter-declaration-clause is not followed by mutable. 12664 DeclRefType = CaptureType.getNonReferenceType(); 12665 if (!LSI->Mutable && !CaptureType->isReferenceType()) 12666 DeclRefType.addConst(); 12667 } 12668 12669 // Add the capture. 12670 if (BuildAndDiagnose) 12671 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 12672 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 12673 12674 return true; 12675 } 12676 12677 bool Sema::tryCaptureVariable( 12678 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 12679 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 12680 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 12681 // An init-capture is notionally from the context surrounding its 12682 // declaration, but its parent DC is the lambda class. 12683 DeclContext *VarDC = Var->getDeclContext(); 12684 if (Var->isInitCapture()) 12685 VarDC = VarDC->getParent(); 12686 12687 DeclContext *DC = CurContext; 12688 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12689 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 12690 // We need to sync up the Declaration Context with the 12691 // FunctionScopeIndexToStopAt 12692 if (FunctionScopeIndexToStopAt) { 12693 unsigned FSIndex = FunctionScopes.size() - 1; 12694 while (FSIndex != MaxFunctionScopesIndex) { 12695 DC = getLambdaAwareParentOfDeclContext(DC); 12696 --FSIndex; 12697 } 12698 } 12699 12700 12701 // If the variable is declared in the current context, there is no need to 12702 // capture it. 12703 if (VarDC == DC) return true; 12704 12705 // Capture global variables if it is required to use private copy of this 12706 // variable. 12707 bool IsGlobal = !Var->hasLocalStorage(); 12708 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var))) 12709 return true; 12710 12711 // Walk up the stack to determine whether we can capture the variable, 12712 // performing the "simple" checks that don't depend on type. We stop when 12713 // we've either hit the declared scope of the variable or find an existing 12714 // capture of that variable. We start from the innermost capturing-entity 12715 // (the DC) and ensure that all intervening capturing-entities 12716 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 12717 // declcontext can either capture the variable or have already captured 12718 // the variable. 12719 CaptureType = Var->getType(); 12720 DeclRefType = CaptureType.getNonReferenceType(); 12721 bool Nested = false; 12722 bool Explicit = (Kind != TryCapture_Implicit); 12723 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 12724 do { 12725 // Only block literals, captured statements, and lambda expressions can 12726 // capture; other scopes don't work. 12727 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 12728 ExprLoc, 12729 BuildAndDiagnose, 12730 *this); 12731 // We need to check for the parent *first* because, if we *have* 12732 // private-captured a global variable, we need to recursively capture it in 12733 // intermediate blocks, lambdas, etc. 12734 if (!ParentDC) { 12735 if (IsGlobal) { 12736 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 12737 break; 12738 } 12739 return true; 12740 } 12741 12742 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 12743 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 12744 12745 12746 // Check whether we've already captured it. 12747 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 12748 DeclRefType)) 12749 break; 12750 // If we are instantiating a generic lambda call operator body, 12751 // we do not want to capture new variables. What was captured 12752 // during either a lambdas transformation or initial parsing 12753 // should be used. 12754 if (isGenericLambdaCallOperatorSpecialization(DC)) { 12755 if (BuildAndDiagnose) { 12756 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12757 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 12758 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12759 Diag(Var->getLocation(), diag::note_previous_decl) 12760 << Var->getDeclName(); 12761 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 12762 } else 12763 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 12764 } 12765 return true; 12766 } 12767 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12768 // certain types of variables (unnamed, variably modified types etc.) 12769 // so check for eligibility. 12770 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 12771 return true; 12772 12773 // Try to capture variable-length arrays types. 12774 if (Var->getType()->isVariablyModifiedType()) { 12775 // We're going to walk down into the type and look for VLA 12776 // expressions. 12777 QualType QTy = Var->getType(); 12778 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 12779 QTy = PVD->getOriginalType(); 12780 do { 12781 const Type *Ty = QTy.getTypePtr(); 12782 switch (Ty->getTypeClass()) { 12783 #define TYPE(Class, Base) 12784 #define ABSTRACT_TYPE(Class, Base) 12785 #define NON_CANONICAL_TYPE(Class, Base) 12786 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 12787 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 12788 #include "clang/AST/TypeNodes.def" 12789 QTy = QualType(); 12790 break; 12791 // These types are never variably-modified. 12792 case Type::Builtin: 12793 case Type::Complex: 12794 case Type::Vector: 12795 case Type::ExtVector: 12796 case Type::Record: 12797 case Type::Enum: 12798 case Type::Elaborated: 12799 case Type::TemplateSpecialization: 12800 case Type::ObjCObject: 12801 case Type::ObjCInterface: 12802 case Type::ObjCObjectPointer: 12803 llvm_unreachable("type class is never variably-modified!"); 12804 case Type::Adjusted: 12805 QTy = cast<AdjustedType>(Ty)->getOriginalType(); 12806 break; 12807 case Type::Decayed: 12808 QTy = cast<DecayedType>(Ty)->getPointeeType(); 12809 break; 12810 case Type::Pointer: 12811 QTy = cast<PointerType>(Ty)->getPointeeType(); 12812 break; 12813 case Type::BlockPointer: 12814 QTy = cast<BlockPointerType>(Ty)->getPointeeType(); 12815 break; 12816 case Type::LValueReference: 12817 case Type::RValueReference: 12818 QTy = cast<ReferenceType>(Ty)->getPointeeType(); 12819 break; 12820 case Type::MemberPointer: 12821 QTy = cast<MemberPointerType>(Ty)->getPointeeType(); 12822 break; 12823 case Type::ConstantArray: 12824 case Type::IncompleteArray: 12825 // Losing element qualification here is fine. 12826 QTy = cast<ArrayType>(Ty)->getElementType(); 12827 break; 12828 case Type::VariableArray: { 12829 // Losing element qualification here is fine. 12830 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 12831 12832 // Unknown size indication requires no size computation. 12833 // Otherwise, evaluate and record it. 12834 if (auto Size = VAT->getSizeExpr()) { 12835 if (!CSI->isVLATypeCaptured(VAT)) { 12836 RecordDecl *CapRecord = nullptr; 12837 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 12838 CapRecord = LSI->Lambda; 12839 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 12840 CapRecord = CRSI->TheRecordDecl; 12841 } 12842 if (CapRecord) { 12843 auto ExprLoc = Size->getExprLoc(); 12844 auto SizeType = Context.getSizeType(); 12845 // Build the non-static data member. 12846 auto Field = FieldDecl::Create( 12847 Context, CapRecord, ExprLoc, ExprLoc, 12848 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 12849 /*BW*/ nullptr, /*Mutable*/ false, 12850 /*InitStyle*/ ICIS_NoInit); 12851 Field->setImplicit(true); 12852 Field->setAccess(AS_private); 12853 Field->setCapturedVLAType(VAT); 12854 CapRecord->addDecl(Field); 12855 12856 CSI->addVLATypeCapture(ExprLoc, SizeType); 12857 } 12858 } 12859 } 12860 QTy = VAT->getElementType(); 12861 break; 12862 } 12863 case Type::FunctionProto: 12864 case Type::FunctionNoProto: 12865 QTy = cast<FunctionType>(Ty)->getReturnType(); 12866 break; 12867 case Type::Paren: 12868 case Type::TypeOf: 12869 case Type::UnaryTransform: 12870 case Type::Attributed: 12871 case Type::SubstTemplateTypeParm: 12872 case Type::PackExpansion: 12873 // Keep walking after single level desugaring. 12874 QTy = QTy.getSingleStepDesugaredType(getASTContext()); 12875 break; 12876 case Type::Typedef: 12877 QTy = cast<TypedefType>(Ty)->desugar(); 12878 break; 12879 case Type::Decltype: 12880 QTy = cast<DecltypeType>(Ty)->desugar(); 12881 break; 12882 case Type::Auto: 12883 QTy = cast<AutoType>(Ty)->getDeducedType(); 12884 break; 12885 case Type::TypeOfExpr: 12886 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 12887 break; 12888 case Type::Atomic: 12889 QTy = cast<AtomicType>(Ty)->getValueType(); 12890 break; 12891 } 12892 } while (!QTy.isNull() && QTy->isVariablyModifiedType()); 12893 } 12894 12895 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 12896 // No capture-default, and this is not an explicit capture 12897 // so cannot capture this variable. 12898 if (BuildAndDiagnose) { 12899 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12900 Diag(Var->getLocation(), diag::note_previous_decl) 12901 << Var->getDeclName(); 12902 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 12903 diag::note_lambda_decl); 12904 // FIXME: If we error out because an outer lambda can not implicitly 12905 // capture a variable that an inner lambda explicitly captures, we 12906 // should have the inner lambda do the explicit capture - because 12907 // it makes for cleaner diagnostics later. This would purely be done 12908 // so that the diagnostic does not misleadingly claim that a variable 12909 // can not be captured by a lambda implicitly even though it is captured 12910 // explicitly. Suggestion: 12911 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 12912 // at the function head 12913 // - cache the StartingDeclContext - this must be a lambda 12914 // - captureInLambda in the innermost lambda the variable. 12915 } 12916 return true; 12917 } 12918 12919 FunctionScopesIndex--; 12920 DC = ParentDC; 12921 Explicit = false; 12922 } while (!VarDC->Equals(DC)); 12923 12924 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 12925 // computing the type of the capture at each step, checking type-specific 12926 // requirements, and adding captures if requested. 12927 // If the variable had already been captured previously, we start capturing 12928 // at the lambda nested within that one. 12929 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 12930 ++I) { 12931 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 12932 12933 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 12934 if (!captureInBlock(BSI, Var, ExprLoc, 12935 BuildAndDiagnose, CaptureType, 12936 DeclRefType, Nested, *this)) 12937 return true; 12938 Nested = true; 12939 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 12940 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 12941 BuildAndDiagnose, CaptureType, 12942 DeclRefType, Nested, *this)) 12943 return true; 12944 Nested = true; 12945 } else { 12946 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12947 if (!captureInLambda(LSI, Var, ExprLoc, 12948 BuildAndDiagnose, CaptureType, 12949 DeclRefType, Nested, Kind, EllipsisLoc, 12950 /*IsTopScope*/I == N - 1, *this)) 12951 return true; 12952 Nested = true; 12953 } 12954 } 12955 return false; 12956 } 12957 12958 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 12959 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 12960 QualType CaptureType; 12961 QualType DeclRefType; 12962 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 12963 /*BuildAndDiagnose=*/true, CaptureType, 12964 DeclRefType, nullptr); 12965 } 12966 12967 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 12968 QualType CaptureType; 12969 QualType DeclRefType; 12970 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 12971 /*BuildAndDiagnose=*/false, CaptureType, 12972 DeclRefType, nullptr); 12973 } 12974 12975 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 12976 QualType CaptureType; 12977 QualType DeclRefType; 12978 12979 // Determine whether we can capture this variable. 12980 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 12981 /*BuildAndDiagnose=*/false, CaptureType, 12982 DeclRefType, nullptr)) 12983 return QualType(); 12984 12985 return DeclRefType; 12986 } 12987 12988 12989 12990 // If either the type of the variable or the initializer is dependent, 12991 // return false. Otherwise, determine whether the variable is a constant 12992 // expression. Use this if you need to know if a variable that might or 12993 // might not be dependent is truly a constant expression. 12994 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 12995 ASTContext &Context) { 12996 12997 if (Var->getType()->isDependentType()) 12998 return false; 12999 const VarDecl *DefVD = nullptr; 13000 Var->getAnyInitializer(DefVD); 13001 if (!DefVD) 13002 return false; 13003 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13004 Expr *Init = cast<Expr>(Eval->Value); 13005 if (Init->isValueDependent()) 13006 return false; 13007 return IsVariableAConstantExpression(Var, Context); 13008 } 13009 13010 13011 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13012 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13013 // an object that satisfies the requirements for appearing in a 13014 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13015 // is immediately applied." This function handles the lvalue-to-rvalue 13016 // conversion part. 13017 MaybeODRUseExprs.erase(E->IgnoreParens()); 13018 13019 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13020 // to a variable that is a constant expression, and if so, identify it as 13021 // a reference to a variable that does not involve an odr-use of that 13022 // variable. 13023 if (LambdaScopeInfo *LSI = getCurLambda()) { 13024 Expr *SansParensExpr = E->IgnoreParens(); 13025 VarDecl *Var = nullptr; 13026 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13027 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13028 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13029 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13030 13031 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13032 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13033 } 13034 } 13035 13036 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13037 Res = CorrectDelayedTyposInExpr(Res); 13038 13039 if (!Res.isUsable()) 13040 return Res; 13041 13042 // If a constant-expression is a reference to a variable where we delay 13043 // deciding whether it is an odr-use, just assume we will apply the 13044 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13045 // (a non-type template argument), we have special handling anyway. 13046 UpdateMarkingForLValueToRValue(Res.get()); 13047 return Res; 13048 } 13049 13050 void Sema::CleanupVarDeclMarking() { 13051 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 13052 e = MaybeODRUseExprs.end(); 13053 i != e; ++i) { 13054 VarDecl *Var; 13055 SourceLocation Loc; 13056 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 13057 Var = cast<VarDecl>(DRE->getDecl()); 13058 Loc = DRE->getLocation(); 13059 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 13060 Var = cast<VarDecl>(ME->getMemberDecl()); 13061 Loc = ME->getMemberLoc(); 13062 } else { 13063 llvm_unreachable("Unexpected expression"); 13064 } 13065 13066 MarkVarDeclODRUsed(Var, Loc, *this, 13067 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13068 } 13069 13070 MaybeODRUseExprs.clear(); 13071 } 13072 13073 13074 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13075 VarDecl *Var, Expr *E) { 13076 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13077 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13078 Var->setReferenced(); 13079 13080 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13081 bool MarkODRUsed = true; 13082 13083 // If the context is not potentially evaluated, this is not an odr-use and 13084 // does not trigger instantiation. 13085 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13086 if (SemaRef.isUnevaluatedContext()) 13087 return; 13088 13089 // If we don't yet know whether this context is going to end up being an 13090 // evaluated context, and we're referencing a variable from an enclosing 13091 // scope, add a potential capture. 13092 // 13093 // FIXME: Is this necessary? These contexts are only used for default 13094 // arguments, where local variables can't be used. 13095 const bool RefersToEnclosingScope = 13096 (SemaRef.CurContext != Var->getDeclContext() && 13097 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13098 if (RefersToEnclosingScope) { 13099 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13100 // If a variable could potentially be odr-used, defer marking it so 13101 // until we finish analyzing the full expression for any 13102 // lvalue-to-rvalue 13103 // or discarded value conversions that would obviate odr-use. 13104 // Add it to the list of potential captures that will be analyzed 13105 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13106 // unless the variable is a reference that was initialized by a constant 13107 // expression (this will never need to be captured or odr-used). 13108 assert(E && "Capture variable should be used in an expression."); 13109 if (!Var->getType()->isReferenceType() || 13110 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13111 LSI->addPotentialCapture(E->IgnoreParens()); 13112 } 13113 } 13114 13115 if (!isTemplateInstantiation(TSK)) 13116 return; 13117 13118 // Instantiate, but do not mark as odr-used, variable templates. 13119 MarkODRUsed = false; 13120 } 13121 13122 VarTemplateSpecializationDecl *VarSpec = 13123 dyn_cast<VarTemplateSpecializationDecl>(Var); 13124 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13125 "Can't instantiate a partial template specialization."); 13126 13127 // Perform implicit instantiation of static data members, static data member 13128 // templates of class templates, and variable template specializations. Delay 13129 // instantiations of variable templates, except for those that could be used 13130 // in a constant expression. 13131 if (isTemplateInstantiation(TSK)) { 13132 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13133 13134 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13135 if (Var->getPointOfInstantiation().isInvalid()) { 13136 // This is a modification of an existing AST node. Notify listeners. 13137 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13138 L->StaticDataMemberInstantiated(Var); 13139 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13140 // Don't bother trying to instantiate it again, unless we might need 13141 // its initializer before we get to the end of the TU. 13142 TryInstantiating = false; 13143 } 13144 13145 if (Var->getPointOfInstantiation().isInvalid()) 13146 Var->setTemplateSpecializationKind(TSK, Loc); 13147 13148 if (TryInstantiating) { 13149 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13150 bool InstantiationDependent = false; 13151 bool IsNonDependent = 13152 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13153 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13154 : true; 13155 13156 // Do not instantiate specializations that are still type-dependent. 13157 if (IsNonDependent) { 13158 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13159 // Do not defer instantiations of variables which could be used in a 13160 // constant expression. 13161 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13162 } else { 13163 SemaRef.PendingInstantiations 13164 .push_back(std::make_pair(Var, PointOfInstantiation)); 13165 } 13166 } 13167 } 13168 } 13169 13170 if(!MarkODRUsed) return; 13171 13172 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13173 // the requirements for appearing in a constant expression (5.19) and, if 13174 // it is an object, the lvalue-to-rvalue conversion (4.1) 13175 // is immediately applied." We check the first part here, and 13176 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13177 // Note that we use the C++11 definition everywhere because nothing in 13178 // C++03 depends on whether we get the C++03 version correct. The second 13179 // part does not apply to references, since they are not objects. 13180 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13181 // A reference initialized by a constant expression can never be 13182 // odr-used, so simply ignore it. 13183 if (!Var->getType()->isReferenceType()) 13184 SemaRef.MaybeODRUseExprs.insert(E); 13185 } else 13186 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13187 /*MaxFunctionScopeIndex ptr*/ nullptr); 13188 } 13189 13190 /// \brief Mark a variable referenced, and check whether it is odr-used 13191 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13192 /// used directly for normal expressions referring to VarDecl. 13193 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13194 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13195 } 13196 13197 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13198 Decl *D, Expr *E, bool OdrUse) { 13199 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13200 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13201 return; 13202 } 13203 13204 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13205 13206 // If this is a call to a method via a cast, also mark the method in the 13207 // derived class used in case codegen can devirtualize the call. 13208 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13209 if (!ME) 13210 return; 13211 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13212 if (!MD) 13213 return; 13214 // Only attempt to devirtualize if this is truly a virtual call. 13215 bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier(); 13216 if (!IsVirtualCall) 13217 return; 13218 const Expr *Base = ME->getBase(); 13219 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13220 if (!MostDerivedClassDecl) 13221 return; 13222 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13223 if (!DM || DM->isPure()) 13224 return; 13225 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13226 } 13227 13228 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13229 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13230 // TODO: update this with DR# once a defect report is filed. 13231 // C++11 defect. The address of a pure member should not be an ODR use, even 13232 // if it's a qualified reference. 13233 bool OdrUse = true; 13234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13235 if (Method->isVirtual()) 13236 OdrUse = false; 13237 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13238 } 13239 13240 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13241 void Sema::MarkMemberReferenced(MemberExpr *E) { 13242 // C++11 [basic.def.odr]p2: 13243 // A non-overloaded function whose name appears as a potentially-evaluated 13244 // expression or a member of a set of candidate functions, if selected by 13245 // overload resolution when referred to from a potentially-evaluated 13246 // expression, is odr-used, unless it is a pure virtual function and its 13247 // name is not explicitly qualified. 13248 bool OdrUse = true; 13249 if (!E->hasQualifier()) { 13250 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13251 if (Method->isPure()) 13252 OdrUse = false; 13253 } 13254 SourceLocation Loc = E->getMemberLoc().isValid() ? 13255 E->getMemberLoc() : E->getLocStart(); 13256 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13257 } 13258 13259 /// \brief Perform marking for a reference to an arbitrary declaration. It 13260 /// marks the declaration referenced, and performs odr-use checking for 13261 /// functions and variables. This method should not be used when building a 13262 /// normal expression which refers to a variable. 13263 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13264 if (OdrUse) { 13265 if (auto *VD = dyn_cast<VarDecl>(D)) { 13266 MarkVariableReferenced(Loc, VD); 13267 return; 13268 } 13269 } 13270 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13271 MarkFunctionReferenced(Loc, FD, OdrUse); 13272 return; 13273 } 13274 D->setReferenced(); 13275 } 13276 13277 namespace { 13278 // Mark all of the declarations referenced 13279 // FIXME: Not fully implemented yet! We need to have a better understanding 13280 // of when we're entering 13281 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13282 Sema &S; 13283 SourceLocation Loc; 13284 13285 public: 13286 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13287 13288 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13289 13290 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13291 bool TraverseRecordType(RecordType *T); 13292 }; 13293 } 13294 13295 bool MarkReferencedDecls::TraverseTemplateArgument( 13296 const TemplateArgument &Arg) { 13297 if (Arg.getKind() == TemplateArgument::Declaration) { 13298 if (Decl *D = Arg.getAsDecl()) 13299 S.MarkAnyDeclReferenced(Loc, D, true); 13300 } 13301 13302 return Inherited::TraverseTemplateArgument(Arg); 13303 } 13304 13305 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13306 if (ClassTemplateSpecializationDecl *Spec 13307 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13308 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13309 return TraverseTemplateArguments(Args.data(), Args.size()); 13310 } 13311 13312 return true; 13313 } 13314 13315 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13316 MarkReferencedDecls Marker(*this, Loc); 13317 Marker.TraverseType(Context.getCanonicalType(T)); 13318 } 13319 13320 namespace { 13321 /// \brief Helper class that marks all of the declarations referenced by 13322 /// potentially-evaluated subexpressions as "referenced". 13323 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13324 Sema &S; 13325 bool SkipLocalVariables; 13326 13327 public: 13328 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13329 13330 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13331 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13332 13333 void VisitDeclRefExpr(DeclRefExpr *E) { 13334 // If we were asked not to visit local variables, don't. 13335 if (SkipLocalVariables) { 13336 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13337 if (VD->hasLocalStorage()) 13338 return; 13339 } 13340 13341 S.MarkDeclRefReferenced(E); 13342 } 13343 13344 void VisitMemberExpr(MemberExpr *E) { 13345 S.MarkMemberReferenced(E); 13346 Inherited::VisitMemberExpr(E); 13347 } 13348 13349 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13350 S.MarkFunctionReferenced(E->getLocStart(), 13351 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13352 Visit(E->getSubExpr()); 13353 } 13354 13355 void VisitCXXNewExpr(CXXNewExpr *E) { 13356 if (E->getOperatorNew()) 13357 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13358 if (E->getOperatorDelete()) 13359 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13360 Inherited::VisitCXXNewExpr(E); 13361 } 13362 13363 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13364 if (E->getOperatorDelete()) 13365 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13366 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13367 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13368 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13369 S.MarkFunctionReferenced(E->getLocStart(), 13370 S.LookupDestructor(Record)); 13371 } 13372 13373 Inherited::VisitCXXDeleteExpr(E); 13374 } 13375 13376 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13377 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13378 Inherited::VisitCXXConstructExpr(E); 13379 } 13380 13381 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13382 Visit(E->getExpr()); 13383 } 13384 13385 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13386 Inherited::VisitImplicitCastExpr(E); 13387 13388 if (E->getCastKind() == CK_LValueToRValue) 13389 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13390 } 13391 }; 13392 } 13393 13394 /// \brief Mark any declarations that appear within this expression or any 13395 /// potentially-evaluated subexpressions as "referenced". 13396 /// 13397 /// \param SkipLocalVariables If true, don't mark local variables as 13398 /// 'referenced'. 13399 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13400 bool SkipLocalVariables) { 13401 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13402 } 13403 13404 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 13405 /// of the program being compiled. 13406 /// 13407 /// This routine emits the given diagnostic when the code currently being 13408 /// type-checked is "potentially evaluated", meaning that there is a 13409 /// possibility that the code will actually be executable. Code in sizeof() 13410 /// expressions, code used only during overload resolution, etc., are not 13411 /// potentially evaluated. This routine will suppress such diagnostics or, 13412 /// in the absolutely nutty case of potentially potentially evaluated 13413 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 13414 /// later. 13415 /// 13416 /// This routine should be used for all diagnostics that describe the run-time 13417 /// behavior of a program, such as passing a non-POD value through an ellipsis. 13418 /// Failure to do so will likely result in spurious diagnostics or failures 13419 /// during overload resolution or within sizeof/alignof/typeof/typeid. 13420 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 13421 const PartialDiagnostic &PD) { 13422 switch (ExprEvalContexts.back().Context) { 13423 case Unevaluated: 13424 case UnevaluatedAbstract: 13425 // The argument will never be evaluated, so don't complain. 13426 break; 13427 13428 case ConstantEvaluated: 13429 // Relevant diagnostics should be produced by constant evaluation. 13430 break; 13431 13432 case PotentiallyEvaluated: 13433 case PotentiallyEvaluatedIfUsed: 13434 if (Statement && getCurFunctionOrMethodDecl()) { 13435 FunctionScopes.back()->PossiblyUnreachableDiags. 13436 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 13437 } 13438 else 13439 Diag(Loc, PD); 13440 13441 return true; 13442 } 13443 13444 return false; 13445 } 13446 13447 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 13448 CallExpr *CE, FunctionDecl *FD) { 13449 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 13450 return false; 13451 13452 // If we're inside a decltype's expression, don't check for a valid return 13453 // type or construct temporaries until we know whether this is the last call. 13454 if (ExprEvalContexts.back().IsDecltype) { 13455 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 13456 return false; 13457 } 13458 13459 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 13460 FunctionDecl *FD; 13461 CallExpr *CE; 13462 13463 public: 13464 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 13465 : FD(FD), CE(CE) { } 13466 13467 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 13468 if (!FD) { 13469 S.Diag(Loc, diag::err_call_incomplete_return) 13470 << T << CE->getSourceRange(); 13471 return; 13472 } 13473 13474 S.Diag(Loc, diag::err_call_function_incomplete_return) 13475 << CE->getSourceRange() << FD->getDeclName() << T; 13476 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 13477 << FD->getDeclName(); 13478 } 13479 } Diagnoser(FD, CE); 13480 13481 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 13482 return true; 13483 13484 return false; 13485 } 13486 13487 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 13488 // will prevent this condition from triggering, which is what we want. 13489 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 13490 SourceLocation Loc; 13491 13492 unsigned diagnostic = diag::warn_condition_is_assignment; 13493 bool IsOrAssign = false; 13494 13495 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 13496 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 13497 return; 13498 13499 IsOrAssign = Op->getOpcode() == BO_OrAssign; 13500 13501 // Greylist some idioms by putting them into a warning subcategory. 13502 if (ObjCMessageExpr *ME 13503 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 13504 Selector Sel = ME->getSelector(); 13505 13506 // self = [<foo> init...] 13507 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 13508 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13509 13510 // <foo> = [<bar> nextObject] 13511 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 13512 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13513 } 13514 13515 Loc = Op->getOperatorLoc(); 13516 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 13517 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 13518 return; 13519 13520 IsOrAssign = Op->getOperator() == OO_PipeEqual; 13521 Loc = Op->getOperatorLoc(); 13522 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 13523 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 13524 else { 13525 // Not an assignment. 13526 return; 13527 } 13528 13529 Diag(Loc, diagnostic) << E->getSourceRange(); 13530 13531 SourceLocation Open = E->getLocStart(); 13532 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 13533 Diag(Loc, diag::note_condition_assign_silence) 13534 << FixItHint::CreateInsertion(Open, "(") 13535 << FixItHint::CreateInsertion(Close, ")"); 13536 13537 if (IsOrAssign) 13538 Diag(Loc, diag::note_condition_or_assign_to_comparison) 13539 << FixItHint::CreateReplacement(Loc, "!="); 13540 else 13541 Diag(Loc, diag::note_condition_assign_to_comparison) 13542 << FixItHint::CreateReplacement(Loc, "=="); 13543 } 13544 13545 /// \brief Redundant parentheses over an equality comparison can indicate 13546 /// that the user intended an assignment used as condition. 13547 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 13548 // Don't warn if the parens came from a macro. 13549 SourceLocation parenLoc = ParenE->getLocStart(); 13550 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 13551 return; 13552 // Don't warn for dependent expressions. 13553 if (ParenE->isTypeDependent()) 13554 return; 13555 13556 Expr *E = ParenE->IgnoreParens(); 13557 13558 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 13559 if (opE->getOpcode() == BO_EQ && 13560 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 13561 == Expr::MLV_Valid) { 13562 SourceLocation Loc = opE->getOperatorLoc(); 13563 13564 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 13565 SourceRange ParenERange = ParenE->getSourceRange(); 13566 Diag(Loc, diag::note_equality_comparison_silence) 13567 << FixItHint::CreateRemoval(ParenERange.getBegin()) 13568 << FixItHint::CreateRemoval(ParenERange.getEnd()); 13569 Diag(Loc, diag::note_equality_comparison_to_assign) 13570 << FixItHint::CreateReplacement(Loc, "="); 13571 } 13572 } 13573 13574 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 13575 DiagnoseAssignmentAsCondition(E); 13576 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 13577 DiagnoseEqualityWithExtraParens(parenE); 13578 13579 ExprResult result = CheckPlaceholderExpr(E); 13580 if (result.isInvalid()) return ExprError(); 13581 E = result.get(); 13582 13583 if (!E->isTypeDependent()) { 13584 if (getLangOpts().CPlusPlus) 13585 return CheckCXXBooleanCondition(E); // C++ 6.4p4 13586 13587 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 13588 if (ERes.isInvalid()) 13589 return ExprError(); 13590 E = ERes.get(); 13591 13592 QualType T = E->getType(); 13593 if (!T->isScalarType()) { // C99 6.8.4.1p1 13594 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 13595 << T << E->getSourceRange(); 13596 return ExprError(); 13597 } 13598 CheckBoolLikeConversion(E, Loc); 13599 } 13600 13601 return E; 13602 } 13603 13604 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 13605 Expr *SubExpr) { 13606 if (!SubExpr) 13607 return ExprError(); 13608 13609 return CheckBooleanCondition(SubExpr, Loc); 13610 } 13611 13612 namespace { 13613 /// A visitor for rebuilding a call to an __unknown_any expression 13614 /// to have an appropriate type. 13615 struct RebuildUnknownAnyFunction 13616 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 13617 13618 Sema &S; 13619 13620 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 13621 13622 ExprResult VisitStmt(Stmt *S) { 13623 llvm_unreachable("unexpected statement!"); 13624 } 13625 13626 ExprResult VisitExpr(Expr *E) { 13627 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 13628 << E->getSourceRange(); 13629 return ExprError(); 13630 } 13631 13632 /// Rebuild an expression which simply semantically wraps another 13633 /// expression which it shares the type and value kind of. 13634 template <class T> ExprResult rebuildSugarExpr(T *E) { 13635 ExprResult SubResult = Visit(E->getSubExpr()); 13636 if (SubResult.isInvalid()) return ExprError(); 13637 13638 Expr *SubExpr = SubResult.get(); 13639 E->setSubExpr(SubExpr); 13640 E->setType(SubExpr->getType()); 13641 E->setValueKind(SubExpr->getValueKind()); 13642 assert(E->getObjectKind() == OK_Ordinary); 13643 return E; 13644 } 13645 13646 ExprResult VisitParenExpr(ParenExpr *E) { 13647 return rebuildSugarExpr(E); 13648 } 13649 13650 ExprResult VisitUnaryExtension(UnaryOperator *E) { 13651 return rebuildSugarExpr(E); 13652 } 13653 13654 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 13655 ExprResult SubResult = Visit(E->getSubExpr()); 13656 if (SubResult.isInvalid()) return ExprError(); 13657 13658 Expr *SubExpr = SubResult.get(); 13659 E->setSubExpr(SubExpr); 13660 E->setType(S.Context.getPointerType(SubExpr->getType())); 13661 assert(E->getValueKind() == VK_RValue); 13662 assert(E->getObjectKind() == OK_Ordinary); 13663 return E; 13664 } 13665 13666 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 13667 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 13668 13669 E->setType(VD->getType()); 13670 13671 assert(E->getValueKind() == VK_RValue); 13672 if (S.getLangOpts().CPlusPlus && 13673 !(isa<CXXMethodDecl>(VD) && 13674 cast<CXXMethodDecl>(VD)->isInstance())) 13675 E->setValueKind(VK_LValue); 13676 13677 return E; 13678 } 13679 13680 ExprResult VisitMemberExpr(MemberExpr *E) { 13681 return resolveDecl(E, E->getMemberDecl()); 13682 } 13683 13684 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 13685 return resolveDecl(E, E->getDecl()); 13686 } 13687 }; 13688 } 13689 13690 /// Given a function expression of unknown-any type, try to rebuild it 13691 /// to have a function type. 13692 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 13693 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 13694 if (Result.isInvalid()) return ExprError(); 13695 return S.DefaultFunctionArrayConversion(Result.get()); 13696 } 13697 13698 namespace { 13699 /// A visitor for rebuilding an expression of type __unknown_anytype 13700 /// into one which resolves the type directly on the referring 13701 /// expression. Strict preservation of the original source 13702 /// structure is not a goal. 13703 struct RebuildUnknownAnyExpr 13704 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 13705 13706 Sema &S; 13707 13708 /// The current destination type. 13709 QualType DestType; 13710 13711 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 13712 : S(S), DestType(CastType) {} 13713 13714 ExprResult VisitStmt(Stmt *S) { 13715 llvm_unreachable("unexpected statement!"); 13716 } 13717 13718 ExprResult VisitExpr(Expr *E) { 13719 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13720 << E->getSourceRange(); 13721 return ExprError(); 13722 } 13723 13724 ExprResult VisitCallExpr(CallExpr *E); 13725 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 13726 13727 /// Rebuild an expression which simply semantically wraps another 13728 /// expression which it shares the type and value kind of. 13729 template <class T> ExprResult rebuildSugarExpr(T *E) { 13730 ExprResult SubResult = Visit(E->getSubExpr()); 13731 if (SubResult.isInvalid()) return ExprError(); 13732 Expr *SubExpr = SubResult.get(); 13733 E->setSubExpr(SubExpr); 13734 E->setType(SubExpr->getType()); 13735 E->setValueKind(SubExpr->getValueKind()); 13736 assert(E->getObjectKind() == OK_Ordinary); 13737 return E; 13738 } 13739 13740 ExprResult VisitParenExpr(ParenExpr *E) { 13741 return rebuildSugarExpr(E); 13742 } 13743 13744 ExprResult VisitUnaryExtension(UnaryOperator *E) { 13745 return rebuildSugarExpr(E); 13746 } 13747 13748 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 13749 const PointerType *Ptr = DestType->getAs<PointerType>(); 13750 if (!Ptr) { 13751 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 13752 << E->getSourceRange(); 13753 return ExprError(); 13754 } 13755 assert(E->getValueKind() == VK_RValue); 13756 assert(E->getObjectKind() == OK_Ordinary); 13757 E->setType(DestType); 13758 13759 // Build the sub-expression as if it were an object of the pointee type. 13760 DestType = Ptr->getPointeeType(); 13761 ExprResult SubResult = Visit(E->getSubExpr()); 13762 if (SubResult.isInvalid()) return ExprError(); 13763 E->setSubExpr(SubResult.get()); 13764 return E; 13765 } 13766 13767 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 13768 13769 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 13770 13771 ExprResult VisitMemberExpr(MemberExpr *E) { 13772 return resolveDecl(E, E->getMemberDecl()); 13773 } 13774 13775 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 13776 return resolveDecl(E, E->getDecl()); 13777 } 13778 }; 13779 } 13780 13781 /// Rebuilds a call expression which yielded __unknown_anytype. 13782 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 13783 Expr *CalleeExpr = E->getCallee(); 13784 13785 enum FnKind { 13786 FK_MemberFunction, 13787 FK_FunctionPointer, 13788 FK_BlockPointer 13789 }; 13790 13791 FnKind Kind; 13792 QualType CalleeType = CalleeExpr->getType(); 13793 if (CalleeType == S.Context.BoundMemberTy) { 13794 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 13795 Kind = FK_MemberFunction; 13796 CalleeType = Expr::findBoundMemberType(CalleeExpr); 13797 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 13798 CalleeType = Ptr->getPointeeType(); 13799 Kind = FK_FunctionPointer; 13800 } else { 13801 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 13802 Kind = FK_BlockPointer; 13803 } 13804 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 13805 13806 // Verify that this is a legal result type of a function. 13807 if (DestType->isArrayType() || DestType->isFunctionType()) { 13808 unsigned diagID = diag::err_func_returning_array_function; 13809 if (Kind == FK_BlockPointer) 13810 diagID = diag::err_block_returning_array_function; 13811 13812 S.Diag(E->getExprLoc(), diagID) 13813 << DestType->isFunctionType() << DestType; 13814 return ExprError(); 13815 } 13816 13817 // Otherwise, go ahead and set DestType as the call's result. 13818 E->setType(DestType.getNonLValueExprType(S.Context)); 13819 E->setValueKind(Expr::getValueKindForType(DestType)); 13820 assert(E->getObjectKind() == OK_Ordinary); 13821 13822 // Rebuild the function type, replacing the result type with DestType. 13823 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 13824 if (Proto) { 13825 // __unknown_anytype(...) is a special case used by the debugger when 13826 // it has no idea what a function's signature is. 13827 // 13828 // We want to build this call essentially under the K&R 13829 // unprototyped rules, but making a FunctionNoProtoType in C++ 13830 // would foul up all sorts of assumptions. However, we cannot 13831 // simply pass all arguments as variadic arguments, nor can we 13832 // portably just call the function under a non-variadic type; see 13833 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 13834 // However, it turns out that in practice it is generally safe to 13835 // call a function declared as "A foo(B,C,D);" under the prototype 13836 // "A foo(B,C,D,...);". The only known exception is with the 13837 // Windows ABI, where any variadic function is implicitly cdecl 13838 // regardless of its normal CC. Therefore we change the parameter 13839 // types to match the types of the arguments. 13840 // 13841 // This is a hack, but it is far superior to moving the 13842 // corresponding target-specific code from IR-gen to Sema/AST. 13843 13844 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 13845 SmallVector<QualType, 8> ArgTypes; 13846 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 13847 ArgTypes.reserve(E->getNumArgs()); 13848 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 13849 Expr *Arg = E->getArg(i); 13850 QualType ArgType = Arg->getType(); 13851 if (E->isLValue()) { 13852 ArgType = S.Context.getLValueReferenceType(ArgType); 13853 } else if (E->isXValue()) { 13854 ArgType = S.Context.getRValueReferenceType(ArgType); 13855 } 13856 ArgTypes.push_back(ArgType); 13857 } 13858 ParamTypes = ArgTypes; 13859 } 13860 DestType = S.Context.getFunctionType(DestType, ParamTypes, 13861 Proto->getExtProtoInfo()); 13862 } else { 13863 DestType = S.Context.getFunctionNoProtoType(DestType, 13864 FnType->getExtInfo()); 13865 } 13866 13867 // Rebuild the appropriate pointer-to-function type. 13868 switch (Kind) { 13869 case FK_MemberFunction: 13870 // Nothing to do. 13871 break; 13872 13873 case FK_FunctionPointer: 13874 DestType = S.Context.getPointerType(DestType); 13875 break; 13876 13877 case FK_BlockPointer: 13878 DestType = S.Context.getBlockPointerType(DestType); 13879 break; 13880 } 13881 13882 // Finally, we can recurse. 13883 ExprResult CalleeResult = Visit(CalleeExpr); 13884 if (!CalleeResult.isUsable()) return ExprError(); 13885 E->setCallee(CalleeResult.get()); 13886 13887 // Bind a temporary if necessary. 13888 return S.MaybeBindToTemporary(E); 13889 } 13890 13891 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 13892 // Verify that this is a legal result type of a call. 13893 if (DestType->isArrayType() || DestType->isFunctionType()) { 13894 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 13895 << DestType->isFunctionType() << DestType; 13896 return ExprError(); 13897 } 13898 13899 // Rewrite the method result type if available. 13900 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 13901 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 13902 Method->setReturnType(DestType); 13903 } 13904 13905 // Change the type of the message. 13906 E->setType(DestType.getNonReferenceType()); 13907 E->setValueKind(Expr::getValueKindForType(DestType)); 13908 13909 return S.MaybeBindToTemporary(E); 13910 } 13911 13912 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 13913 // The only case we should ever see here is a function-to-pointer decay. 13914 if (E->getCastKind() == CK_FunctionToPointerDecay) { 13915 assert(E->getValueKind() == VK_RValue); 13916 assert(E->getObjectKind() == OK_Ordinary); 13917 13918 E->setType(DestType); 13919 13920 // Rebuild the sub-expression as the pointee (function) type. 13921 DestType = DestType->castAs<PointerType>()->getPointeeType(); 13922 13923 ExprResult Result = Visit(E->getSubExpr()); 13924 if (!Result.isUsable()) return ExprError(); 13925 13926 E->setSubExpr(Result.get()); 13927 return E; 13928 } else if (E->getCastKind() == CK_LValueToRValue) { 13929 assert(E->getValueKind() == VK_RValue); 13930 assert(E->getObjectKind() == OK_Ordinary); 13931 13932 assert(isa<BlockPointerType>(E->getType())); 13933 13934 E->setType(DestType); 13935 13936 // The sub-expression has to be a lvalue reference, so rebuild it as such. 13937 DestType = S.Context.getLValueReferenceType(DestType); 13938 13939 ExprResult Result = Visit(E->getSubExpr()); 13940 if (!Result.isUsable()) return ExprError(); 13941 13942 E->setSubExpr(Result.get()); 13943 return E; 13944 } else { 13945 llvm_unreachable("Unhandled cast type!"); 13946 } 13947 } 13948 13949 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 13950 ExprValueKind ValueKind = VK_LValue; 13951 QualType Type = DestType; 13952 13953 // We know how to make this work for certain kinds of decls: 13954 13955 // - functions 13956 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 13957 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 13958 DestType = Ptr->getPointeeType(); 13959 ExprResult Result = resolveDecl(E, VD); 13960 if (Result.isInvalid()) return ExprError(); 13961 return S.ImpCastExprToType(Result.get(), Type, 13962 CK_FunctionToPointerDecay, VK_RValue); 13963 } 13964 13965 if (!Type->isFunctionType()) { 13966 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 13967 << VD << E->getSourceRange(); 13968 return ExprError(); 13969 } 13970 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 13971 // We must match the FunctionDecl's type to the hack introduced in 13972 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 13973 // type. See the lengthy commentary in that routine. 13974 QualType FDT = FD->getType(); 13975 const FunctionType *FnType = FDT->castAs<FunctionType>(); 13976 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 13977 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 13978 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 13979 SourceLocation Loc = FD->getLocation(); 13980 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 13981 FD->getDeclContext(), 13982 Loc, Loc, FD->getNameInfo().getName(), 13983 DestType, FD->getTypeSourceInfo(), 13984 SC_None, false/*isInlineSpecified*/, 13985 FD->hasPrototype(), 13986 false/*isConstexprSpecified*/); 13987 13988 if (FD->getQualifier()) 13989 NewFD->setQualifierInfo(FD->getQualifierLoc()); 13990 13991 SmallVector<ParmVarDecl*, 16> Params; 13992 for (const auto &AI : FT->param_types()) { 13993 ParmVarDecl *Param = 13994 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 13995 Param->setScopeInfo(0, Params.size()); 13996 Params.push_back(Param); 13997 } 13998 NewFD->setParams(Params); 13999 DRE->setDecl(NewFD); 14000 VD = DRE->getDecl(); 14001 } 14002 } 14003 14004 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14005 if (MD->isInstance()) { 14006 ValueKind = VK_RValue; 14007 Type = S.Context.BoundMemberTy; 14008 } 14009 14010 // Function references aren't l-values in C. 14011 if (!S.getLangOpts().CPlusPlus) 14012 ValueKind = VK_RValue; 14013 14014 // - variables 14015 } else if (isa<VarDecl>(VD)) { 14016 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14017 Type = RefTy->getPointeeType(); 14018 } else if (Type->isFunctionType()) { 14019 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14020 << VD << E->getSourceRange(); 14021 return ExprError(); 14022 } 14023 14024 // - nothing else 14025 } else { 14026 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14027 << VD << E->getSourceRange(); 14028 return ExprError(); 14029 } 14030 14031 // Modifying the declaration like this is friendly to IR-gen but 14032 // also really dangerous. 14033 VD->setType(DestType); 14034 E->setType(Type); 14035 E->setValueKind(ValueKind); 14036 return E; 14037 } 14038 14039 /// Check a cast of an unknown-any type. We intentionally only 14040 /// trigger this for C-style casts. 14041 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14042 Expr *CastExpr, CastKind &CastKind, 14043 ExprValueKind &VK, CXXCastPath &Path) { 14044 // Rewrite the casted expression from scratch. 14045 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14046 if (!result.isUsable()) return ExprError(); 14047 14048 CastExpr = result.get(); 14049 VK = CastExpr->getValueKind(); 14050 CastKind = CK_NoOp; 14051 14052 return CastExpr; 14053 } 14054 14055 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14056 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14057 } 14058 14059 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14060 Expr *arg, QualType ¶mType) { 14061 // If the syntactic form of the argument is not an explicit cast of 14062 // any sort, just do default argument promotion. 14063 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14064 if (!castArg) { 14065 ExprResult result = DefaultArgumentPromotion(arg); 14066 if (result.isInvalid()) return ExprError(); 14067 paramType = result.get()->getType(); 14068 return result; 14069 } 14070 14071 // Otherwise, use the type that was written in the explicit cast. 14072 assert(!arg->hasPlaceholderType()); 14073 paramType = castArg->getTypeAsWritten(); 14074 14075 // Copy-initialize a parameter of that type. 14076 InitializedEntity entity = 14077 InitializedEntity::InitializeParameter(Context, paramType, 14078 /*consumed*/ false); 14079 return PerformCopyInitialization(entity, callLoc, arg); 14080 } 14081 14082 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14083 Expr *orig = E; 14084 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14085 while (true) { 14086 E = E->IgnoreParenImpCasts(); 14087 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14088 E = call->getCallee(); 14089 diagID = diag::err_uncasted_call_of_unknown_any; 14090 } else { 14091 break; 14092 } 14093 } 14094 14095 SourceLocation loc; 14096 NamedDecl *d; 14097 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14098 loc = ref->getLocation(); 14099 d = ref->getDecl(); 14100 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14101 loc = mem->getMemberLoc(); 14102 d = mem->getMemberDecl(); 14103 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14104 diagID = diag::err_uncasted_call_of_unknown_any; 14105 loc = msg->getSelectorStartLoc(); 14106 d = msg->getMethodDecl(); 14107 if (!d) { 14108 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14109 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14110 << orig->getSourceRange(); 14111 return ExprError(); 14112 } 14113 } else { 14114 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14115 << E->getSourceRange(); 14116 return ExprError(); 14117 } 14118 14119 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14120 14121 // Never recoverable. 14122 return ExprError(); 14123 } 14124 14125 /// Check for operands with placeholder types and complain if found. 14126 /// Returns true if there was an error and no recovery was possible. 14127 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14128 if (!getLangOpts().CPlusPlus) { 14129 // C cannot handle TypoExpr nodes on either side of a binop because it 14130 // doesn't handle dependent types properly, so make sure any TypoExprs have 14131 // been dealt with before checking the operands. 14132 ExprResult Result = CorrectDelayedTyposInExpr(E); 14133 if (!Result.isUsable()) return ExprError(); 14134 E = Result.get(); 14135 } 14136 14137 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14138 if (!placeholderType) return E; 14139 14140 switch (placeholderType->getKind()) { 14141 14142 // Overloaded expressions. 14143 case BuiltinType::Overload: { 14144 // Try to resolve a single function template specialization. 14145 // This is obligatory. 14146 ExprResult result = E; 14147 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14148 return result; 14149 14150 // If that failed, try to recover with a call. 14151 } else { 14152 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14153 /*complain*/ true); 14154 return result; 14155 } 14156 } 14157 14158 // Bound member functions. 14159 case BuiltinType::BoundMember: { 14160 ExprResult result = E; 14161 const Expr *BME = E->IgnoreParens(); 14162 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14163 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14164 if (isa<CXXPseudoDestructorExpr>(BME)) { 14165 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14166 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14167 if (ME->getMemberNameInfo().getName().getNameKind() == 14168 DeclarationName::CXXDestructorName) 14169 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14170 } 14171 tryToRecoverWithCall(result, PD, 14172 /*complain*/ true); 14173 return result; 14174 } 14175 14176 // ARC unbridged casts. 14177 case BuiltinType::ARCUnbridgedCast: { 14178 Expr *realCast = stripARCUnbridgedCast(E); 14179 diagnoseARCUnbridgedCast(realCast); 14180 return realCast; 14181 } 14182 14183 // Expressions of unknown type. 14184 case BuiltinType::UnknownAny: 14185 return diagnoseUnknownAnyExpr(*this, E); 14186 14187 // Pseudo-objects. 14188 case BuiltinType::PseudoObject: 14189 return checkPseudoObjectRValue(E); 14190 14191 case BuiltinType::BuiltinFn: { 14192 // Accept __noop without parens by implicitly converting it to a call expr. 14193 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14194 if (DRE) { 14195 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14196 if (FD->getBuiltinID() == Builtin::BI__noop) { 14197 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14198 CK_BuiltinFnToFnPtr).get(); 14199 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14200 VK_RValue, SourceLocation()); 14201 } 14202 } 14203 14204 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14205 return ExprError(); 14206 } 14207 14208 // Everything else should be impossible. 14209 #define BUILTIN_TYPE(Id, SingletonId) \ 14210 case BuiltinType::Id: 14211 #define PLACEHOLDER_TYPE(Id, SingletonId) 14212 #include "clang/AST/BuiltinTypes.def" 14213 break; 14214 } 14215 14216 llvm_unreachable("invalid placeholder type!"); 14217 } 14218 14219 bool Sema::CheckCaseExpression(Expr *E) { 14220 if (E->isTypeDependent()) 14221 return true; 14222 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14223 return E->getType()->isIntegralOrEnumerationType(); 14224 return false; 14225 } 14226 14227 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14228 ExprResult 14229 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14230 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14231 "Unknown Objective-C Boolean value!"); 14232 QualType BoolT = Context.ObjCBuiltinBoolTy; 14233 if (!Context.getBOOLDecl()) { 14234 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14235 Sema::LookupOrdinaryName); 14236 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14237 NamedDecl *ND = Result.getFoundDecl(); 14238 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14239 Context.setBOOLDecl(TD); 14240 } 14241 } 14242 if (Context.getBOOLDecl()) 14243 BoolT = Context.getBOOLType(); 14244 return new (Context) 14245 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14246 } 14247