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/ExprOpenMP.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (D->hasAttr<UnusedAttr>()) { 80 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 81 if (DC && !DC->hasAttr<UnusedAttr>()) 82 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 83 } 84 } 85 86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 87 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 88 if (!OMD) 89 return false; 90 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 91 if (!OID) 92 return false; 93 94 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 95 if (ObjCMethodDecl *CatMeth = 96 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 97 if (!CatMeth->hasAttr<AvailabilityAttr>()) 98 return true; 99 return false; 100 } 101 102 static AvailabilityResult 103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 104 const ObjCInterfaceDecl *UnknownObjCClass, 105 bool ObjCPropertyAccess) { 106 // See if this declaration is unavailable or deprecated. 107 std::string Message; 108 AvailabilityResult Result = D->getAvailability(&Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(&Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(&Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(&Message); 136 } 137 138 const ObjCPropertyDecl *ObjCPDecl = nullptr; 139 if (Result == AR_Deprecated || Result == AR_Unavailable || 140 AR_NotYetIntroduced) { 141 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 142 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 143 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 144 if (PDeclResult == Result) 145 ObjCPDecl = PD; 146 } 147 } 148 } 149 150 switch (Result) { 151 case AR_Available: 152 break; 153 154 case AR_Deprecated: 155 if (S.getCurContextAvailability() != AR_Deprecated) 156 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 157 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 158 ObjCPropertyAccess); 159 break; 160 161 case AR_NotYetIntroduced: { 162 // Don't do this for enums, they can't be redeclared. 163 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 164 break; 165 166 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 167 // Objective-C method declarations in categories are not modelled as 168 // redeclarations, so manually look for a redeclaration in a category 169 // if necessary. 170 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 171 Warn = false; 172 // In general, D will point to the most recent redeclaration. However, 173 // for `@class A;` decls, this isn't true -- manually go through the 174 // redecl chain in that case. 175 if (Warn && isa<ObjCInterfaceDecl>(D)) 176 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 177 Redecl = Redecl->getPreviousDecl()) 178 if (!Redecl->hasAttr<AvailabilityAttr>() || 179 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 180 Warn = false; 181 182 if (Warn) 183 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 184 UnknownObjCClass, ObjCPDecl, 185 ObjCPropertyAccess); 186 break; 187 } 188 189 case AR_Unavailable: 190 if (S.getCurContextAvailability() != AR_Unavailable) 191 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 192 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 193 ObjCPropertyAccess); 194 break; 195 196 } 197 return Result; 198 } 199 200 /// \brief Emit a note explaining that this function is deleted. 201 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 202 assert(Decl->isDeleted()); 203 204 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 205 206 if (Method && Method->isDeleted() && Method->isDefaulted()) { 207 // If the method was explicitly defaulted, point at that declaration. 208 if (!Method->isImplicit()) 209 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 210 211 // Try to diagnose why this special member function was implicitly 212 // deleted. This might fail, if that reason no longer applies. 213 CXXSpecialMember CSM = getSpecialMember(Method); 214 if (CSM != CXXInvalid) 215 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 216 217 return; 218 } 219 220 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 221 if (CXXConstructorDecl *BaseCD = 222 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 223 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 224 if (BaseCD->isDeleted()) { 225 NoteDeletedFunction(BaseCD); 226 } else { 227 // FIXME: An explanation of why exactly it can't be inherited 228 // would be nice. 229 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 230 } 231 return; 232 } 233 } 234 235 Diag(Decl->getLocation(), diag::note_availability_specified_here) 236 << Decl << true; 237 } 238 239 /// \brief Determine whether a FunctionDecl was ever declared with an 240 /// explicit storage class. 241 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 242 for (auto I : D->redecls()) { 243 if (I->getStorageClass() != SC_None) 244 return true; 245 } 246 return false; 247 } 248 249 /// \brief Check whether we're in an extern inline function and referring to a 250 /// variable or function with internal linkage (C11 6.7.4p3). 251 /// 252 /// This is only a warning because we used to silently accept this code, but 253 /// in many cases it will not behave correctly. This is not enabled in C++ mode 254 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 255 /// and so while there may still be user mistakes, most of the time we can't 256 /// prove that there are errors. 257 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 258 const NamedDecl *D, 259 SourceLocation Loc) { 260 // This is disabled under C++; there are too many ways for this to fire in 261 // contexts where the warning is a false positive, or where it is technically 262 // correct but benign. 263 if (S.getLangOpts().CPlusPlus) 264 return; 265 266 // Check if this is an inlined function or method. 267 FunctionDecl *Current = S.getCurFunctionDecl(); 268 if (!Current) 269 return; 270 if (!Current->isInlined()) 271 return; 272 if (!Current->isExternallyVisible()) 273 return; 274 275 // Check if the decl has internal linkage. 276 if (D->getFormalLinkage() != InternalLinkage) 277 return; 278 279 // Downgrade from ExtWarn to Extension if 280 // (1) the supposedly external inline function is in the main file, 281 // and probably won't be included anywhere else. 282 // (2) the thing we're referencing is a pure function. 283 // (3) the thing we're referencing is another inline function. 284 // This last can give us false negatives, but it's better than warning on 285 // wrappers for simple C library functions. 286 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 287 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 288 if (!DowngradeWarning && UsedFn) 289 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 290 291 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 292 : diag::ext_internal_in_extern_inline) 293 << /*IsVar=*/!UsedFn << D; 294 295 S.MaybeSuggestAddingStaticToDecl(Current); 296 297 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 298 << D; 299 } 300 301 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 302 const FunctionDecl *First = Cur->getFirstDecl(); 303 304 // Suggest "static" on the function, if possible. 305 if (!hasAnyExplicitStorageClass(First)) { 306 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 307 Diag(DeclBegin, diag::note_convert_inline_to_static) 308 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 309 } 310 } 311 312 /// \brief Determine whether the use of this declaration is valid, and 313 /// emit any corresponding diagnostics. 314 /// 315 /// This routine diagnoses various problems with referencing 316 /// declarations that can occur when using a declaration. For example, 317 /// it might warn if a deprecated or unavailable declaration is being 318 /// used, or produce an error (and return true) if a C++0x deleted 319 /// function is being used. 320 /// 321 /// \returns true if there was an error (this declaration cannot be 322 /// referenced), false otherwise. 323 /// 324 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 325 const ObjCInterfaceDecl *UnknownObjCClass, 326 bool ObjCPropertyAccess) { 327 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 328 // If there were any diagnostics suppressed by template argument deduction, 329 // emit them now. 330 SuppressedDiagnosticsMap::iterator 331 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 332 if (Pos != SuppressedDiagnostics.end()) { 333 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 334 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 335 Diag(Suppressed[I].first, Suppressed[I].second); 336 337 // Clear out the list of suppressed diagnostics, so that we don't emit 338 // them again for this specialization. However, we don't obsolete this 339 // entry from the table, because we want to avoid ever emitting these 340 // diagnostics again. 341 Suppressed.clear(); 342 } 343 344 // C++ [basic.start.main]p3: 345 // The function 'main' shall not be used within a program. 346 if (cast<FunctionDecl>(D)->isMain()) 347 Diag(Loc, diag::ext_main_used); 348 } 349 350 // See if this is an auto-typed variable whose initializer we are parsing. 351 if (ParsingInitForAutoVars.count(D)) { 352 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 353 354 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 355 << D->getDeclName() << (unsigned)AT->getKeyword(); 356 return true; 357 } 358 359 // See if this is a deleted function. 360 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 361 if (FD->isDeleted()) { 362 Diag(Loc, diag::err_deleted_function_use); 363 NoteDeletedFunction(FD); 364 return true; 365 } 366 367 // If the function has a deduced return type, and we can't deduce it, 368 // then we can't use it either. 369 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 370 DeduceReturnType(FD, Loc)) 371 return true; 372 } 373 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 374 ObjCPropertyAccess); 375 376 DiagnoseUnusedOfDecl(*this, D, Loc); 377 378 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 379 380 return false; 381 } 382 383 /// \brief Retrieve the message suffix that should be added to a 384 /// diagnostic complaining about the given function being deleted or 385 /// unavailable. 386 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 387 std::string Message; 388 if (FD->getAvailability(&Message)) 389 return ": " + Message; 390 391 return std::string(); 392 } 393 394 /// DiagnoseSentinelCalls - This routine checks whether a call or 395 /// message-send is to a declaration with the sentinel attribute, and 396 /// if so, it checks that the requirements of the sentinel are 397 /// satisfied. 398 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 399 ArrayRef<Expr *> Args) { 400 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 401 if (!attr) 402 return; 403 404 // The number of formal parameters of the declaration. 405 unsigned numFormalParams; 406 407 // The kind of declaration. This is also an index into a %select in 408 // the diagnostic. 409 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 410 411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 412 numFormalParams = MD->param_size(); 413 calleeType = CT_Method; 414 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 415 numFormalParams = FD->param_size(); 416 calleeType = CT_Function; 417 } else if (isa<VarDecl>(D)) { 418 QualType type = cast<ValueDecl>(D)->getType(); 419 const FunctionType *fn = nullptr; 420 if (const PointerType *ptr = type->getAs<PointerType>()) { 421 fn = ptr->getPointeeType()->getAs<FunctionType>(); 422 if (!fn) return; 423 calleeType = CT_Function; 424 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 425 fn = ptr->getPointeeType()->castAs<FunctionType>(); 426 calleeType = CT_Block; 427 } else { 428 return; 429 } 430 431 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 432 numFormalParams = proto->getNumParams(); 433 } else { 434 numFormalParams = 0; 435 } 436 } else { 437 return; 438 } 439 440 // "nullPos" is the number of formal parameters at the end which 441 // effectively count as part of the variadic arguments. This is 442 // useful if you would prefer to not have *any* formal parameters, 443 // but the language forces you to have at least one. 444 unsigned nullPos = attr->getNullPos(); 445 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 446 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 447 448 // The number of arguments which should follow the sentinel. 449 unsigned numArgsAfterSentinel = attr->getSentinel(); 450 451 // If there aren't enough arguments for all the formal parameters, 452 // the sentinel, and the args after the sentinel, complain. 453 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 454 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 455 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 456 return; 457 } 458 459 // Otherwise, find the sentinel expression. 460 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 461 if (!sentinelExpr) return; 462 if (sentinelExpr->isValueDependent()) return; 463 if (Context.isSentinelNullExpr(sentinelExpr)) return; 464 465 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 466 // or 'NULL' if those are actually defined in the context. Only use 467 // 'nil' for ObjC methods, where it's much more likely that the 468 // variadic arguments form a list of object pointers. 469 SourceLocation MissingNilLoc 470 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 471 std::string NullValue; 472 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 473 NullValue = "nil"; 474 else if (getLangOpts().CPlusPlus11) 475 NullValue = "nullptr"; 476 else if (PP.isMacroDefined("NULL")) 477 NullValue = "NULL"; 478 else 479 NullValue = "(void*) 0"; 480 481 if (MissingNilLoc.isInvalid()) 482 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 483 else 484 Diag(MissingNilLoc, diag::warn_missing_sentinel) 485 << int(calleeType) 486 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 487 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 488 } 489 490 SourceRange Sema::getExprRange(Expr *E) const { 491 return E ? E->getSourceRange() : SourceRange(); 492 } 493 494 //===----------------------------------------------------------------------===// 495 // Standard Promotions and Conversions 496 //===----------------------------------------------------------------------===// 497 498 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 499 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 500 // Handle any placeholder expressions which made it here. 501 if (E->getType()->isPlaceholderType()) { 502 ExprResult result = CheckPlaceholderExpr(E); 503 if (result.isInvalid()) return ExprError(); 504 E = result.get(); 505 } 506 507 QualType Ty = E->getType(); 508 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 509 510 if (Ty->isFunctionType()) { 511 // If we are here, we are not calling a function but taking 512 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 513 if (getLangOpts().OpenCL) { 514 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 515 return ExprError(); 516 } 517 E = ImpCastExprToType(E, Context.getPointerType(Ty), 518 CK_FunctionToPointerDecay).get(); 519 } else if (Ty->isArrayType()) { 520 // In C90 mode, arrays only promote to pointers if the array expression is 521 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 522 // type 'array of type' is converted to an expression that has type 'pointer 523 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 524 // that has type 'array of type' ...". The relevant change is "an lvalue" 525 // (C90) to "an expression" (C99). 526 // 527 // C++ 4.2p1: 528 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 529 // T" can be converted to an rvalue of type "pointer to T". 530 // 531 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 532 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 533 CK_ArrayToPointerDecay).get(); 534 } 535 return E; 536 } 537 538 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 539 // Check to see if we are dereferencing a null pointer. If so, 540 // and if not volatile-qualified, this is undefined behavior that the 541 // optimizer will delete, so warn about it. People sometimes try to use this 542 // to get a deterministic trap and are surprised by clang's behavior. This 543 // only handles the pattern "*null", which is a very syntactic check. 544 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 545 if (UO->getOpcode() == UO_Deref && 546 UO->getSubExpr()->IgnoreParenCasts()-> 547 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 548 !UO->getType().isVolatileQualified()) { 549 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 550 S.PDiag(diag::warn_indirection_through_null) 551 << UO->getSubExpr()->getSourceRange()); 552 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 553 S.PDiag(diag::note_indirection_through_null)); 554 } 555 } 556 557 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 558 SourceLocation AssignLoc, 559 const Expr* RHS) { 560 const ObjCIvarDecl *IV = OIRE->getDecl(); 561 if (!IV) 562 return; 563 564 DeclarationName MemberName = IV->getDeclName(); 565 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 566 if (!Member || !Member->isStr("isa")) 567 return; 568 569 const Expr *Base = OIRE->getBase(); 570 QualType BaseType = Base->getType(); 571 if (OIRE->isArrow()) 572 BaseType = BaseType->getPointeeType(); 573 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 574 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 575 ObjCInterfaceDecl *ClassDeclared = nullptr; 576 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 577 if (!ClassDeclared->getSuperClass() 578 && (*ClassDeclared->ivar_begin()) == IV) { 579 if (RHS) { 580 NamedDecl *ObjectSetClass = 581 S.LookupSingleName(S.TUScope, 582 &S.Context.Idents.get("object_setClass"), 583 SourceLocation(), S.LookupOrdinaryName); 584 if (ObjectSetClass) { 585 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 586 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 587 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 588 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 589 AssignLoc), ",") << 590 FixItHint::CreateInsertion(RHSLocEnd, ")"); 591 } 592 else 593 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 594 } else { 595 NamedDecl *ObjectGetClass = 596 S.LookupSingleName(S.TUScope, 597 &S.Context.Idents.get("object_getClass"), 598 SourceLocation(), S.LookupOrdinaryName); 599 if (ObjectGetClass) 600 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 601 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 602 FixItHint::CreateReplacement( 603 SourceRange(OIRE->getOpLoc(), 604 OIRE->getLocEnd()), ")"); 605 else 606 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 607 } 608 S.Diag(IV->getLocation(), diag::note_ivar_decl); 609 } 610 } 611 } 612 613 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 614 // Handle any placeholder expressions which made it here. 615 if (E->getType()->isPlaceholderType()) { 616 ExprResult result = CheckPlaceholderExpr(E); 617 if (result.isInvalid()) return ExprError(); 618 E = result.get(); 619 } 620 621 // C++ [conv.lval]p1: 622 // A glvalue of a non-function, non-array type T can be 623 // converted to a prvalue. 624 if (!E->isGLValue()) return E; 625 626 QualType T = E->getType(); 627 assert(!T.isNull() && "r-value conversion on typeless expression?"); 628 629 // We don't want to throw lvalue-to-rvalue casts on top of 630 // expressions of certain types in C++. 631 if (getLangOpts().CPlusPlus && 632 (E->getType() == Context.OverloadTy || 633 T->isDependentType() || 634 T->isRecordType())) 635 return E; 636 637 // The C standard is actually really unclear on this point, and 638 // DR106 tells us what the result should be but not why. It's 639 // generally best to say that void types just doesn't undergo 640 // lvalue-to-rvalue at all. Note that expressions of unqualified 641 // 'void' type are never l-values, but qualified void can be. 642 if (T->isVoidType()) 643 return E; 644 645 // OpenCL usually rejects direct accesses to values of 'half' type. 646 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 647 T->isHalfType()) { 648 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 649 << 0 << T; 650 return ExprError(); 651 } 652 653 CheckForNullPointerDereference(*this, E); 654 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 655 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 656 &Context.Idents.get("object_getClass"), 657 SourceLocation(), LookupOrdinaryName); 658 if (ObjectGetClass) 659 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 660 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 661 FixItHint::CreateReplacement( 662 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 663 else 664 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 665 } 666 else if (const ObjCIvarRefExpr *OIRE = 667 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 668 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 669 670 // C++ [conv.lval]p1: 671 // [...] If T is a non-class type, the type of the prvalue is the 672 // cv-unqualified version of T. Otherwise, the type of the 673 // rvalue is T. 674 // 675 // C99 6.3.2.1p2: 676 // If the lvalue has qualified type, the value has the unqualified 677 // version of the type of the lvalue; otherwise, the value has the 678 // type of the lvalue. 679 if (T.hasQualifiers()) 680 T = T.getUnqualifiedType(); 681 682 if (T->isMemberPointerType() && 683 Context.getTargetInfo().getCXXABI().isMicrosoft()) 684 RequireCompleteType(E->getExprLoc(), T, 0); 685 686 UpdateMarkingForLValueToRValue(E); 687 688 // Loading a __weak object implicitly retains the value, so we need a cleanup to 689 // balance that. 690 if (getLangOpts().ObjCAutoRefCount && 691 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 692 ExprNeedsCleanups = true; 693 694 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 695 nullptr, VK_RValue); 696 697 // C11 6.3.2.1p2: 698 // ... if the lvalue has atomic type, the value has the non-atomic version 699 // of the type of the lvalue ... 700 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 701 T = Atomic->getValueType().getUnqualifiedType(); 702 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 703 nullptr, VK_RValue); 704 } 705 706 return Res; 707 } 708 709 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 710 ExprResult Res = DefaultFunctionArrayConversion(E); 711 if (Res.isInvalid()) 712 return ExprError(); 713 Res = DefaultLvalueConversion(Res.get()); 714 if (Res.isInvalid()) 715 return ExprError(); 716 return Res; 717 } 718 719 /// CallExprUnaryConversions - a special case of an unary conversion 720 /// performed on a function designator of a call expression. 721 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 722 QualType Ty = E->getType(); 723 ExprResult Res = E; 724 // Only do implicit cast for a function type, but not for a pointer 725 // to function type. 726 if (Ty->isFunctionType()) { 727 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 728 CK_FunctionToPointerDecay).get(); 729 if (Res.isInvalid()) 730 return ExprError(); 731 } 732 Res = DefaultLvalueConversion(Res.get()); 733 if (Res.isInvalid()) 734 return ExprError(); 735 return Res.get(); 736 } 737 738 /// UsualUnaryConversions - Performs various conversions that are common to most 739 /// operators (C99 6.3). The conversions of array and function types are 740 /// sometimes suppressed. For example, the array->pointer conversion doesn't 741 /// apply if the array is an argument to the sizeof or address (&) operators. 742 /// In these instances, this routine should *not* be called. 743 ExprResult Sema::UsualUnaryConversions(Expr *E) { 744 // First, convert to an r-value. 745 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 746 if (Res.isInvalid()) 747 return ExprError(); 748 E = Res.get(); 749 750 QualType Ty = E->getType(); 751 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 752 753 // Half FP have to be promoted to float unless it is natively supported 754 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 755 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 756 757 // Try to perform integral promotions if the object has a theoretically 758 // promotable type. 759 if (Ty->isIntegralOrUnscopedEnumerationType()) { 760 // C99 6.3.1.1p2: 761 // 762 // The following may be used in an expression wherever an int or 763 // unsigned int may be used: 764 // - an object or expression with an integer type whose integer 765 // conversion rank is less than or equal to the rank of int 766 // and unsigned int. 767 // - A bit-field of type _Bool, int, signed int, or unsigned int. 768 // 769 // If an int can represent all values of the original type, the 770 // value is converted to an int; otherwise, it is converted to an 771 // unsigned int. These are called the integer promotions. All 772 // other types are unchanged by the integer promotions. 773 774 QualType PTy = Context.isPromotableBitField(E); 775 if (!PTy.isNull()) { 776 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 777 return E; 778 } 779 if (Ty->isPromotableIntegerType()) { 780 QualType PT = Context.getPromotedIntegerType(Ty); 781 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 782 return E; 783 } 784 } 785 return E; 786 } 787 788 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 789 /// do not have a prototype. Arguments that have type float or __fp16 790 /// are promoted to double. All other argument types are converted by 791 /// UsualUnaryConversions(). 792 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 793 QualType Ty = E->getType(); 794 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 795 796 ExprResult Res = UsualUnaryConversions(E); 797 if (Res.isInvalid()) 798 return ExprError(); 799 E = Res.get(); 800 801 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 802 // double. 803 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 804 if (BTy && (BTy->getKind() == BuiltinType::Half || 805 BTy->getKind() == BuiltinType::Float)) 806 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 807 808 // C++ performs lvalue-to-rvalue conversion as a default argument 809 // promotion, even on class types, but note: 810 // C++11 [conv.lval]p2: 811 // When an lvalue-to-rvalue conversion occurs in an unevaluated 812 // operand or a subexpression thereof the value contained in the 813 // referenced object is not accessed. Otherwise, if the glvalue 814 // has a class type, the conversion copy-initializes a temporary 815 // of type T from the glvalue and the result of the conversion 816 // is a prvalue for the temporary. 817 // FIXME: add some way to gate this entire thing for correctness in 818 // potentially potentially evaluated contexts. 819 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 820 ExprResult Temp = PerformCopyInitialization( 821 InitializedEntity::InitializeTemporary(E->getType()), 822 E->getExprLoc(), E); 823 if (Temp.isInvalid()) 824 return ExprError(); 825 E = Temp.get(); 826 } 827 828 return E; 829 } 830 831 /// Determine the degree of POD-ness for an expression. 832 /// Incomplete types are considered POD, since this check can be performed 833 /// when we're in an unevaluated context. 834 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 835 if (Ty->isIncompleteType()) { 836 // C++11 [expr.call]p7: 837 // After these conversions, if the argument does not have arithmetic, 838 // enumeration, pointer, pointer to member, or class type, the program 839 // is ill-formed. 840 // 841 // Since we've already performed array-to-pointer and function-to-pointer 842 // decay, the only such type in C++ is cv void. This also handles 843 // initializer lists as variadic arguments. 844 if (Ty->isVoidType()) 845 return VAK_Invalid; 846 847 if (Ty->isObjCObjectType()) 848 return VAK_Invalid; 849 return VAK_Valid; 850 } 851 852 if (Ty.isCXX98PODType(Context)) 853 return VAK_Valid; 854 855 // C++11 [expr.call]p7: 856 // Passing a potentially-evaluated argument of class type (Clause 9) 857 // having a non-trivial copy constructor, a non-trivial move constructor, 858 // or a non-trivial destructor, with no corresponding parameter, 859 // is conditionally-supported with implementation-defined semantics. 860 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 861 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 862 if (!Record->hasNonTrivialCopyConstructor() && 863 !Record->hasNonTrivialMoveConstructor() && 864 !Record->hasNonTrivialDestructor()) 865 return VAK_ValidInCXX11; 866 867 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 868 return VAK_Valid; 869 870 if (Ty->isObjCObjectType()) 871 return VAK_Invalid; 872 873 if (getLangOpts().MSVCCompat) 874 return VAK_MSVCUndefined; 875 876 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 877 // permitted to reject them. We should consider doing so. 878 return VAK_Undefined; 879 } 880 881 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 882 // Don't allow one to pass an Objective-C interface to a vararg. 883 const QualType &Ty = E->getType(); 884 VarArgKind VAK = isValidVarArgType(Ty); 885 886 // Complain about passing non-POD types through varargs. 887 switch (VAK) { 888 case VAK_ValidInCXX11: 889 DiagRuntimeBehavior( 890 E->getLocStart(), nullptr, 891 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 892 << Ty << CT); 893 // Fall through. 894 case VAK_Valid: 895 if (Ty->isRecordType()) { 896 // This is unlikely to be what the user intended. If the class has a 897 // 'c_str' member function, the user probably meant to call that. 898 DiagRuntimeBehavior(E->getLocStart(), nullptr, 899 PDiag(diag::warn_pass_class_arg_to_vararg) 900 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 901 } 902 break; 903 904 case VAK_Undefined: 905 case VAK_MSVCUndefined: 906 DiagRuntimeBehavior( 907 E->getLocStart(), nullptr, 908 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 909 << getLangOpts().CPlusPlus11 << Ty << CT); 910 break; 911 912 case VAK_Invalid: 913 if (Ty->isObjCObjectType()) 914 DiagRuntimeBehavior( 915 E->getLocStart(), nullptr, 916 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 917 << Ty << CT); 918 else 919 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 920 << isa<InitListExpr>(E) << Ty << CT; 921 break; 922 } 923 } 924 925 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 926 /// will create a trap if the resulting type is not a POD type. 927 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 928 FunctionDecl *FDecl) { 929 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 930 // Strip the unbridged-cast placeholder expression off, if applicable. 931 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 932 (CT == VariadicMethod || 933 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 934 E = stripARCUnbridgedCast(E); 935 936 // Otherwise, do normal placeholder checking. 937 } else { 938 ExprResult ExprRes = CheckPlaceholderExpr(E); 939 if (ExprRes.isInvalid()) 940 return ExprError(); 941 E = ExprRes.get(); 942 } 943 } 944 945 ExprResult ExprRes = DefaultArgumentPromotion(E); 946 if (ExprRes.isInvalid()) 947 return ExprError(); 948 E = ExprRes.get(); 949 950 // Diagnostics regarding non-POD argument types are 951 // emitted along with format string checking in Sema::CheckFunctionCall(). 952 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 953 // Turn this into a trap. 954 CXXScopeSpec SS; 955 SourceLocation TemplateKWLoc; 956 UnqualifiedId Name; 957 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 958 E->getLocStart()); 959 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 960 Name, true, false); 961 if (TrapFn.isInvalid()) 962 return ExprError(); 963 964 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 965 E->getLocStart(), None, 966 E->getLocEnd()); 967 if (Call.isInvalid()) 968 return ExprError(); 969 970 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 971 Call.get(), E); 972 if (Comma.isInvalid()) 973 return ExprError(); 974 return Comma.get(); 975 } 976 977 if (!getLangOpts().CPlusPlus && 978 RequireCompleteType(E->getExprLoc(), E->getType(), 979 diag::err_call_incomplete_argument)) 980 return ExprError(); 981 982 return E; 983 } 984 985 /// \brief Converts an integer to complex float type. Helper function of 986 /// UsualArithmeticConversions() 987 /// 988 /// \return false if the integer expression is an integer type and is 989 /// successfully converted to the complex type. 990 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 991 ExprResult &ComplexExpr, 992 QualType IntTy, 993 QualType ComplexTy, 994 bool SkipCast) { 995 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 996 if (SkipCast) return false; 997 if (IntTy->isIntegerType()) { 998 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 999 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1000 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1001 CK_FloatingRealToComplex); 1002 } else { 1003 assert(IntTy->isComplexIntegerType()); 1004 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1005 CK_IntegralComplexToFloatingComplex); 1006 } 1007 return false; 1008 } 1009 1010 /// \brief Handle arithmetic conversion with complex types. Helper function of 1011 /// UsualArithmeticConversions() 1012 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1013 ExprResult &RHS, QualType LHSType, 1014 QualType RHSType, 1015 bool IsCompAssign) { 1016 // if we have an integer operand, the result is the complex type. 1017 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1018 /*skipCast*/false)) 1019 return LHSType; 1020 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1021 /*skipCast*/IsCompAssign)) 1022 return RHSType; 1023 1024 // This handles complex/complex, complex/float, or float/complex. 1025 // When both operands are complex, the shorter operand is converted to the 1026 // type of the longer, and that is the type of the result. This corresponds 1027 // to what is done when combining two real floating-point operands. 1028 // The fun begins when size promotion occur across type domains. 1029 // From H&S 6.3.4: When one operand is complex and the other is a real 1030 // floating-point type, the less precise type is converted, within it's 1031 // real or complex domain, to the precision of the other type. For example, 1032 // when combining a "long double" with a "double _Complex", the 1033 // "double _Complex" is promoted to "long double _Complex". 1034 1035 // Compute the rank of the two types, regardless of whether they are complex. 1036 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1037 1038 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1039 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1040 QualType LHSElementType = 1041 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1042 QualType RHSElementType = 1043 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1044 1045 QualType ResultType = S.Context.getComplexType(LHSElementType); 1046 if (Order < 0) { 1047 // Promote the precision of the LHS if not an assignment. 1048 ResultType = S.Context.getComplexType(RHSElementType); 1049 if (!IsCompAssign) { 1050 if (LHSComplexType) 1051 LHS = 1052 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1053 else 1054 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1055 } 1056 } else if (Order > 0) { 1057 // Promote the precision of the RHS. 1058 if (RHSComplexType) 1059 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1060 else 1061 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1062 } 1063 return ResultType; 1064 } 1065 1066 /// \brief Hande arithmetic conversion from integer to float. Helper function 1067 /// of UsualArithmeticConversions() 1068 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1069 ExprResult &IntExpr, 1070 QualType FloatTy, QualType IntTy, 1071 bool ConvertFloat, bool ConvertInt) { 1072 if (IntTy->isIntegerType()) { 1073 if (ConvertInt) 1074 // Convert intExpr to the lhs floating point type. 1075 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1076 CK_IntegralToFloating); 1077 return FloatTy; 1078 } 1079 1080 // Convert both sides to the appropriate complex float. 1081 assert(IntTy->isComplexIntegerType()); 1082 QualType result = S.Context.getComplexType(FloatTy); 1083 1084 // _Complex int -> _Complex float 1085 if (ConvertInt) 1086 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1087 CK_IntegralComplexToFloatingComplex); 1088 1089 // float -> _Complex float 1090 if (ConvertFloat) 1091 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1092 CK_FloatingRealToComplex); 1093 1094 return result; 1095 } 1096 1097 /// \brief Handle arithmethic conversion with floating point types. Helper 1098 /// function of UsualArithmeticConversions() 1099 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1100 ExprResult &RHS, QualType LHSType, 1101 QualType RHSType, bool IsCompAssign) { 1102 bool LHSFloat = LHSType->isRealFloatingType(); 1103 bool RHSFloat = RHSType->isRealFloatingType(); 1104 1105 // If we have two real floating types, convert the smaller operand 1106 // to the bigger result. 1107 if (LHSFloat && RHSFloat) { 1108 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1109 if (order > 0) { 1110 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1111 return LHSType; 1112 } 1113 1114 assert(order < 0 && "illegal float comparison"); 1115 if (!IsCompAssign) 1116 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1117 return RHSType; 1118 } 1119 1120 if (LHSFloat) { 1121 // Half FP has to be promoted to float unless it is natively supported 1122 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1123 LHSType = S.Context.FloatTy; 1124 1125 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1126 /*convertFloat=*/!IsCompAssign, 1127 /*convertInt=*/ true); 1128 } 1129 assert(RHSFloat); 1130 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1131 /*convertInt=*/ true, 1132 /*convertFloat=*/!IsCompAssign); 1133 } 1134 1135 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1136 1137 namespace { 1138 /// These helper callbacks are placed in an anonymous namespace to 1139 /// permit their use as function template parameters. 1140 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1141 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1142 } 1143 1144 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1145 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1146 CK_IntegralComplexCast); 1147 } 1148 } 1149 1150 /// \brief Handle integer arithmetic conversions. Helper function of 1151 /// UsualArithmeticConversions() 1152 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1153 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1154 ExprResult &RHS, QualType LHSType, 1155 QualType RHSType, bool IsCompAssign) { 1156 // The rules for this case are in C99 6.3.1.8 1157 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1158 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1159 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1160 if (LHSSigned == RHSSigned) { 1161 // Same signedness; use the higher-ranked type 1162 if (order >= 0) { 1163 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1164 return LHSType; 1165 } else if (!IsCompAssign) 1166 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1167 return RHSType; 1168 } else if (order != (LHSSigned ? 1 : -1)) { 1169 // The unsigned type has greater than or equal rank to the 1170 // signed type, so use the unsigned type 1171 if (RHSSigned) { 1172 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1173 return LHSType; 1174 } else if (!IsCompAssign) 1175 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1176 return RHSType; 1177 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1178 // The two types are different widths; if we are here, that 1179 // means the signed type is larger than the unsigned type, so 1180 // use the signed type. 1181 if (LHSSigned) { 1182 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1183 return LHSType; 1184 } else if (!IsCompAssign) 1185 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1186 return RHSType; 1187 } else { 1188 // The signed type is higher-ranked than the unsigned type, 1189 // but isn't actually any bigger (like unsigned int and long 1190 // on most 32-bit systems). Use the unsigned type corresponding 1191 // to the signed type. 1192 QualType result = 1193 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1194 RHS = (*doRHSCast)(S, RHS.get(), result); 1195 if (!IsCompAssign) 1196 LHS = (*doLHSCast)(S, LHS.get(), result); 1197 return result; 1198 } 1199 } 1200 1201 /// \brief Handle conversions with GCC complex int extension. Helper function 1202 /// of UsualArithmeticConversions() 1203 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1204 ExprResult &RHS, QualType LHSType, 1205 QualType RHSType, 1206 bool IsCompAssign) { 1207 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1208 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1209 1210 if (LHSComplexInt && RHSComplexInt) { 1211 QualType LHSEltType = LHSComplexInt->getElementType(); 1212 QualType RHSEltType = RHSComplexInt->getElementType(); 1213 QualType ScalarType = 1214 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1215 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1216 1217 return S.Context.getComplexType(ScalarType); 1218 } 1219 1220 if (LHSComplexInt) { 1221 QualType LHSEltType = LHSComplexInt->getElementType(); 1222 QualType ScalarType = 1223 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1224 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1225 QualType ComplexType = S.Context.getComplexType(ScalarType); 1226 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1227 CK_IntegralRealToComplex); 1228 1229 return ComplexType; 1230 } 1231 1232 assert(RHSComplexInt); 1233 1234 QualType RHSEltType = RHSComplexInt->getElementType(); 1235 QualType ScalarType = 1236 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1237 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1238 QualType ComplexType = S.Context.getComplexType(ScalarType); 1239 1240 if (!IsCompAssign) 1241 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1242 CK_IntegralRealToComplex); 1243 return ComplexType; 1244 } 1245 1246 /// UsualArithmeticConversions - Performs various conversions that are common to 1247 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1248 /// routine returns the first non-arithmetic type found. The client is 1249 /// responsible for emitting appropriate error diagnostics. 1250 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1251 bool IsCompAssign) { 1252 if (!IsCompAssign) { 1253 LHS = UsualUnaryConversions(LHS.get()); 1254 if (LHS.isInvalid()) 1255 return QualType(); 1256 } 1257 1258 RHS = UsualUnaryConversions(RHS.get()); 1259 if (RHS.isInvalid()) 1260 return QualType(); 1261 1262 // For conversion purposes, we ignore any qualifiers. 1263 // For example, "const float" and "float" are equivalent. 1264 QualType LHSType = 1265 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1266 QualType RHSType = 1267 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1268 1269 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1270 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1271 LHSType = AtomicLHS->getValueType(); 1272 1273 // If both types are identical, no conversion is needed. 1274 if (LHSType == RHSType) 1275 return LHSType; 1276 1277 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1278 // The caller can deal with this (e.g. pointer + int). 1279 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1280 return QualType(); 1281 1282 // Apply unary and bitfield promotions to the LHS's type. 1283 QualType LHSUnpromotedType = LHSType; 1284 if (LHSType->isPromotableIntegerType()) 1285 LHSType = Context.getPromotedIntegerType(LHSType); 1286 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1287 if (!LHSBitfieldPromoteTy.isNull()) 1288 LHSType = LHSBitfieldPromoteTy; 1289 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1290 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1291 1292 // If both types are identical, no conversion is needed. 1293 if (LHSType == RHSType) 1294 return LHSType; 1295 1296 // At this point, we have two different arithmetic types. 1297 1298 // Handle complex types first (C99 6.3.1.8p1). 1299 if (LHSType->isComplexType() || RHSType->isComplexType()) 1300 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1301 IsCompAssign); 1302 1303 // Now handle "real" floating types (i.e. float, double, long double). 1304 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1305 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1306 IsCompAssign); 1307 1308 // Handle GCC complex int extension. 1309 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1310 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1311 IsCompAssign); 1312 1313 // Finally, we have two differing integer types. 1314 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1315 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1316 } 1317 1318 1319 //===----------------------------------------------------------------------===// 1320 // Semantic Analysis for various Expression Types 1321 //===----------------------------------------------------------------------===// 1322 1323 1324 ExprResult 1325 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1326 SourceLocation DefaultLoc, 1327 SourceLocation RParenLoc, 1328 Expr *ControllingExpr, 1329 ArrayRef<ParsedType> ArgTypes, 1330 ArrayRef<Expr *> ArgExprs) { 1331 unsigned NumAssocs = ArgTypes.size(); 1332 assert(NumAssocs == ArgExprs.size()); 1333 1334 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1335 for (unsigned i = 0; i < NumAssocs; ++i) { 1336 if (ArgTypes[i]) 1337 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1338 else 1339 Types[i] = nullptr; 1340 } 1341 1342 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1343 ControllingExpr, 1344 llvm::makeArrayRef(Types, NumAssocs), 1345 ArgExprs); 1346 delete [] Types; 1347 return ER; 1348 } 1349 1350 ExprResult 1351 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1352 SourceLocation DefaultLoc, 1353 SourceLocation RParenLoc, 1354 Expr *ControllingExpr, 1355 ArrayRef<TypeSourceInfo *> Types, 1356 ArrayRef<Expr *> Exprs) { 1357 unsigned NumAssocs = Types.size(); 1358 assert(NumAssocs == Exprs.size()); 1359 1360 // Decay and strip qualifiers for the controlling expression type, and handle 1361 // placeholder type replacement. See committee discussion from WG14 DR423. 1362 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1363 if (R.isInvalid()) 1364 return ExprError(); 1365 ControllingExpr = R.get(); 1366 1367 // The controlling expression is an unevaluated operand, so side effects are 1368 // likely unintended. 1369 if (ActiveTemplateInstantiations.empty() && 1370 ControllingExpr->HasSideEffects(Context, false)) 1371 Diag(ControllingExpr->getExprLoc(), 1372 diag::warn_side_effects_unevaluated_context); 1373 1374 bool TypeErrorFound = false, 1375 IsResultDependent = ControllingExpr->isTypeDependent(), 1376 ContainsUnexpandedParameterPack 1377 = ControllingExpr->containsUnexpandedParameterPack(); 1378 1379 for (unsigned i = 0; i < NumAssocs; ++i) { 1380 if (Exprs[i]->containsUnexpandedParameterPack()) 1381 ContainsUnexpandedParameterPack = true; 1382 1383 if (Types[i]) { 1384 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1385 ContainsUnexpandedParameterPack = true; 1386 1387 if (Types[i]->getType()->isDependentType()) { 1388 IsResultDependent = true; 1389 } else { 1390 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1391 // complete object type other than a variably modified type." 1392 unsigned D = 0; 1393 if (Types[i]->getType()->isIncompleteType()) 1394 D = diag::err_assoc_type_incomplete; 1395 else if (!Types[i]->getType()->isObjectType()) 1396 D = diag::err_assoc_type_nonobject; 1397 else if (Types[i]->getType()->isVariablyModifiedType()) 1398 D = diag::err_assoc_type_variably_modified; 1399 1400 if (D != 0) { 1401 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1402 << Types[i]->getTypeLoc().getSourceRange() 1403 << Types[i]->getType(); 1404 TypeErrorFound = true; 1405 } 1406 1407 // C11 6.5.1.1p2 "No two generic associations in the same generic 1408 // selection shall specify compatible types." 1409 for (unsigned j = i+1; j < NumAssocs; ++j) 1410 if (Types[j] && !Types[j]->getType()->isDependentType() && 1411 Context.typesAreCompatible(Types[i]->getType(), 1412 Types[j]->getType())) { 1413 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1414 diag::err_assoc_compatible_types) 1415 << Types[j]->getTypeLoc().getSourceRange() 1416 << Types[j]->getType() 1417 << Types[i]->getType(); 1418 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1419 diag::note_compat_assoc) 1420 << Types[i]->getTypeLoc().getSourceRange() 1421 << Types[i]->getType(); 1422 TypeErrorFound = true; 1423 } 1424 } 1425 } 1426 } 1427 if (TypeErrorFound) 1428 return ExprError(); 1429 1430 // If we determined that the generic selection is result-dependent, don't 1431 // try to compute the result expression. 1432 if (IsResultDependent) 1433 return new (Context) GenericSelectionExpr( 1434 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1435 ContainsUnexpandedParameterPack); 1436 1437 SmallVector<unsigned, 1> CompatIndices; 1438 unsigned DefaultIndex = -1U; 1439 for (unsigned i = 0; i < NumAssocs; ++i) { 1440 if (!Types[i]) 1441 DefaultIndex = i; 1442 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1443 Types[i]->getType())) 1444 CompatIndices.push_back(i); 1445 } 1446 1447 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1448 // type compatible with at most one of the types named in its generic 1449 // association list." 1450 if (CompatIndices.size() > 1) { 1451 // We strip parens here because the controlling expression is typically 1452 // parenthesized in macro definitions. 1453 ControllingExpr = ControllingExpr->IgnoreParens(); 1454 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1455 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1456 << (unsigned) CompatIndices.size(); 1457 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1458 E = CompatIndices.end(); I != E; ++I) { 1459 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1460 diag::note_compat_assoc) 1461 << Types[*I]->getTypeLoc().getSourceRange() 1462 << Types[*I]->getType(); 1463 } 1464 return ExprError(); 1465 } 1466 1467 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1468 // its controlling expression shall have type compatible with exactly one of 1469 // the types named in its generic association list." 1470 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1471 // We strip parens here because the controlling expression is typically 1472 // parenthesized in macro definitions. 1473 ControllingExpr = ControllingExpr->IgnoreParens(); 1474 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1475 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1476 return ExprError(); 1477 } 1478 1479 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1480 // type name that is compatible with the type of the controlling expression, 1481 // then the result expression of the generic selection is the expression 1482 // in that generic association. Otherwise, the result expression of the 1483 // generic selection is the expression in the default generic association." 1484 unsigned ResultIndex = 1485 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1486 1487 return new (Context) GenericSelectionExpr( 1488 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1489 ContainsUnexpandedParameterPack, ResultIndex); 1490 } 1491 1492 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1493 /// location of the token and the offset of the ud-suffix within it. 1494 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1495 unsigned Offset) { 1496 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1497 S.getLangOpts()); 1498 } 1499 1500 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1501 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1502 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1503 IdentifierInfo *UDSuffix, 1504 SourceLocation UDSuffixLoc, 1505 ArrayRef<Expr*> Args, 1506 SourceLocation LitEndLoc) { 1507 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1508 1509 QualType ArgTy[2]; 1510 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1511 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1512 if (ArgTy[ArgIdx]->isArrayType()) 1513 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1514 } 1515 1516 DeclarationName OpName = 1517 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1518 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1519 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1520 1521 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1522 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1523 /*AllowRaw*/false, /*AllowTemplate*/false, 1524 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1525 return ExprError(); 1526 1527 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1528 } 1529 1530 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1531 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1532 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1533 /// multiple tokens. However, the common case is that StringToks points to one 1534 /// string. 1535 /// 1536 ExprResult 1537 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1538 assert(!StringToks.empty() && "Must have at least one string!"); 1539 1540 StringLiteralParser Literal(StringToks, PP); 1541 if (Literal.hadError) 1542 return ExprError(); 1543 1544 SmallVector<SourceLocation, 4> StringTokLocs; 1545 for (unsigned i = 0; i != StringToks.size(); ++i) 1546 StringTokLocs.push_back(StringToks[i].getLocation()); 1547 1548 QualType CharTy = Context.CharTy; 1549 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1550 if (Literal.isWide()) { 1551 CharTy = Context.getWideCharType(); 1552 Kind = StringLiteral::Wide; 1553 } else if (Literal.isUTF8()) { 1554 Kind = StringLiteral::UTF8; 1555 } else if (Literal.isUTF16()) { 1556 CharTy = Context.Char16Ty; 1557 Kind = StringLiteral::UTF16; 1558 } else if (Literal.isUTF32()) { 1559 CharTy = Context.Char32Ty; 1560 Kind = StringLiteral::UTF32; 1561 } else if (Literal.isPascal()) { 1562 CharTy = Context.UnsignedCharTy; 1563 } 1564 1565 QualType CharTyConst = CharTy; 1566 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1567 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1568 CharTyConst.addConst(); 1569 1570 // Get an array type for the string, according to C99 6.4.5. This includes 1571 // the nul terminator character as well as the string length for pascal 1572 // strings. 1573 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1574 llvm::APInt(32, Literal.GetNumStringChars()+1), 1575 ArrayType::Normal, 0); 1576 1577 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1578 if (getLangOpts().OpenCL) { 1579 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1580 } 1581 1582 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1583 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1584 Kind, Literal.Pascal, StrTy, 1585 &StringTokLocs[0], 1586 StringTokLocs.size()); 1587 if (Literal.getUDSuffix().empty()) 1588 return Lit; 1589 1590 // We're building a user-defined literal. 1591 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1592 SourceLocation UDSuffixLoc = 1593 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1594 Literal.getUDSuffixOffset()); 1595 1596 // Make sure we're allowed user-defined literals here. 1597 if (!UDLScope) 1598 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1599 1600 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1601 // operator "" X (str, len) 1602 QualType SizeType = Context.getSizeType(); 1603 1604 DeclarationName OpName = 1605 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1606 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1607 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1608 1609 QualType ArgTy[] = { 1610 Context.getArrayDecayedType(StrTy), SizeType 1611 }; 1612 1613 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1614 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1615 /*AllowRaw*/false, /*AllowTemplate*/false, 1616 /*AllowStringTemplate*/true)) { 1617 1618 case LOLR_Cooked: { 1619 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1620 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1621 StringTokLocs[0]); 1622 Expr *Args[] = { Lit, LenArg }; 1623 1624 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1625 } 1626 1627 case LOLR_StringTemplate: { 1628 TemplateArgumentListInfo ExplicitArgs; 1629 1630 unsigned CharBits = Context.getIntWidth(CharTy); 1631 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1632 llvm::APSInt Value(CharBits, CharIsUnsigned); 1633 1634 TemplateArgument TypeArg(CharTy); 1635 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1636 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1637 1638 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1639 Value = Lit->getCodeUnit(I); 1640 TemplateArgument Arg(Context, Value, CharTy); 1641 TemplateArgumentLocInfo ArgInfo; 1642 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1643 } 1644 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1645 &ExplicitArgs); 1646 } 1647 case LOLR_Raw: 1648 case LOLR_Template: 1649 llvm_unreachable("unexpected literal operator lookup result"); 1650 case LOLR_Error: 1651 return ExprError(); 1652 } 1653 llvm_unreachable("unexpected literal operator lookup result"); 1654 } 1655 1656 ExprResult 1657 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1658 SourceLocation Loc, 1659 const CXXScopeSpec *SS) { 1660 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1661 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1662 } 1663 1664 /// BuildDeclRefExpr - Build an expression that references a 1665 /// declaration that does not require a closure capture. 1666 ExprResult 1667 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1668 const DeclarationNameInfo &NameInfo, 1669 const CXXScopeSpec *SS, NamedDecl *FoundD, 1670 const TemplateArgumentListInfo *TemplateArgs) { 1671 if (getLangOpts().CUDA) 1672 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1673 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1674 if (CheckCUDATarget(Caller, Callee)) { 1675 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1676 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1677 << IdentifyCUDATarget(Caller); 1678 Diag(D->getLocation(), diag::note_previous_decl) 1679 << D->getIdentifier(); 1680 return ExprError(); 1681 } 1682 } 1683 1684 bool RefersToCapturedVariable = 1685 isa<VarDecl>(D) && 1686 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1687 1688 DeclRefExpr *E; 1689 if (isa<VarTemplateSpecializationDecl>(D)) { 1690 VarTemplateSpecializationDecl *VarSpec = 1691 cast<VarTemplateSpecializationDecl>(D); 1692 1693 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1694 : NestedNameSpecifierLoc(), 1695 VarSpec->getTemplateKeywordLoc(), D, 1696 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1697 FoundD, TemplateArgs); 1698 } else { 1699 assert(!TemplateArgs && "No template arguments for non-variable" 1700 " template specialization references"); 1701 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1702 : NestedNameSpecifierLoc(), 1703 SourceLocation(), D, RefersToCapturedVariable, 1704 NameInfo, Ty, VK, FoundD); 1705 } 1706 1707 MarkDeclRefReferenced(E); 1708 1709 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1710 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1711 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1712 recordUseOfEvaluatedWeak(E); 1713 1714 // Just in case we're building an illegal pointer-to-member. 1715 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1716 if (FD && FD->isBitField()) 1717 E->setObjectKind(OK_BitField); 1718 1719 return E; 1720 } 1721 1722 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1723 /// possibly a list of template arguments. 1724 /// 1725 /// If this produces template arguments, it is permitted to call 1726 /// DecomposeTemplateName. 1727 /// 1728 /// This actually loses a lot of source location information for 1729 /// non-standard name kinds; we should consider preserving that in 1730 /// some way. 1731 void 1732 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1733 TemplateArgumentListInfo &Buffer, 1734 DeclarationNameInfo &NameInfo, 1735 const TemplateArgumentListInfo *&TemplateArgs) { 1736 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1737 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1738 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1739 1740 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1741 Id.TemplateId->NumArgs); 1742 translateTemplateArguments(TemplateArgsPtr, Buffer); 1743 1744 TemplateName TName = Id.TemplateId->Template.get(); 1745 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1746 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1747 TemplateArgs = &Buffer; 1748 } else { 1749 NameInfo = GetNameFromUnqualifiedId(Id); 1750 TemplateArgs = nullptr; 1751 } 1752 } 1753 1754 static void emitEmptyLookupTypoDiagnostic( 1755 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1756 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1757 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1758 DeclContext *Ctx = 1759 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1760 if (!TC) { 1761 // Emit a special diagnostic for failed member lookups. 1762 // FIXME: computing the declaration context might fail here (?) 1763 if (Ctx) 1764 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1765 << SS.getRange(); 1766 else 1767 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1768 return; 1769 } 1770 1771 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1772 bool DroppedSpecifier = 1773 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1774 unsigned NoteID = 1775 (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl())) 1776 ? diag::note_implicit_param_decl 1777 : diag::note_previous_decl; 1778 if (!Ctx) 1779 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1780 SemaRef.PDiag(NoteID)); 1781 else 1782 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1783 << Typo << Ctx << DroppedSpecifier 1784 << SS.getRange(), 1785 SemaRef.PDiag(NoteID)); 1786 } 1787 1788 /// Diagnose an empty lookup. 1789 /// 1790 /// \return false if new lookup candidates were found 1791 bool 1792 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1793 std::unique_ptr<CorrectionCandidateCallback> CCC, 1794 TemplateArgumentListInfo *ExplicitTemplateArgs, 1795 ArrayRef<Expr *> Args, TypoExpr **Out) { 1796 DeclarationName Name = R.getLookupName(); 1797 1798 unsigned diagnostic = diag::err_undeclared_var_use; 1799 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1800 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1801 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1802 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1803 diagnostic = diag::err_undeclared_use; 1804 diagnostic_suggest = diag::err_undeclared_use_suggest; 1805 } 1806 1807 // If the original lookup was an unqualified lookup, fake an 1808 // unqualified lookup. This is useful when (for example) the 1809 // original lookup would not have found something because it was a 1810 // dependent name. 1811 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1812 while (DC) { 1813 if (isa<CXXRecordDecl>(DC)) { 1814 LookupQualifiedName(R, DC); 1815 1816 if (!R.empty()) { 1817 // Don't give errors about ambiguities in this lookup. 1818 R.suppressDiagnostics(); 1819 1820 // During a default argument instantiation the CurContext points 1821 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1822 // function parameter list, hence add an explicit check. 1823 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1824 ActiveTemplateInstantiations.back().Kind == 1825 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1826 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1827 bool isInstance = CurMethod && 1828 CurMethod->isInstance() && 1829 DC == CurMethod->getParent() && !isDefaultArgument; 1830 1831 // Give a code modification hint to insert 'this->'. 1832 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1833 // Actually quite difficult! 1834 if (getLangOpts().MSVCCompat) 1835 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1836 if (isInstance) { 1837 Diag(R.getNameLoc(), diagnostic) << Name 1838 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1839 CheckCXXThisCapture(R.getNameLoc()); 1840 } else { 1841 Diag(R.getNameLoc(), diagnostic) << Name; 1842 } 1843 1844 // Do we really want to note all of these? 1845 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1846 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1847 1848 // Return true if we are inside a default argument instantiation 1849 // and the found name refers to an instance member function, otherwise 1850 // the function calling DiagnoseEmptyLookup will try to create an 1851 // implicit member call and this is wrong for default argument. 1852 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1853 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1854 return true; 1855 } 1856 1857 // Tell the callee to try to recover. 1858 return false; 1859 } 1860 1861 R.clear(); 1862 } 1863 1864 // In Microsoft mode, if we are performing lookup from within a friend 1865 // function definition declared at class scope then we must set 1866 // DC to the lexical parent to be able to search into the parent 1867 // class. 1868 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1869 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1870 DC->getLexicalParent()->isRecord()) 1871 DC = DC->getLexicalParent(); 1872 else 1873 DC = DC->getParent(); 1874 } 1875 1876 // We didn't find anything, so try to correct for a typo. 1877 TypoCorrection Corrected; 1878 if (S && Out) { 1879 SourceLocation TypoLoc = R.getNameLoc(); 1880 assert(!ExplicitTemplateArgs && 1881 "Diagnosing an empty lookup with explicit template args!"); 1882 *Out = CorrectTypoDelayed( 1883 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1884 [=](const TypoCorrection &TC) { 1885 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1886 diagnostic, diagnostic_suggest); 1887 }, 1888 nullptr, CTK_ErrorRecovery); 1889 if (*Out) 1890 return true; 1891 } else if (S && (Corrected = 1892 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1893 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1894 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1895 bool DroppedSpecifier = 1896 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1897 R.setLookupName(Corrected.getCorrection()); 1898 1899 bool AcceptableWithRecovery = false; 1900 bool AcceptableWithoutRecovery = false; 1901 NamedDecl *ND = Corrected.getCorrectionDecl(); 1902 if (ND) { 1903 if (Corrected.isOverloaded()) { 1904 OverloadCandidateSet OCS(R.getNameLoc(), 1905 OverloadCandidateSet::CSK_Normal); 1906 OverloadCandidateSet::iterator Best; 1907 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1908 CDEnd = Corrected.end(); 1909 CD != CDEnd; ++CD) { 1910 if (FunctionTemplateDecl *FTD = 1911 dyn_cast<FunctionTemplateDecl>(*CD)) 1912 AddTemplateOverloadCandidate( 1913 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1914 Args, OCS); 1915 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1916 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1917 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1918 Args, OCS); 1919 } 1920 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1921 case OR_Success: 1922 ND = Best->Function; 1923 Corrected.setCorrectionDecl(ND); 1924 break; 1925 default: 1926 // FIXME: Arbitrarily pick the first declaration for the note. 1927 Corrected.setCorrectionDecl(ND); 1928 break; 1929 } 1930 } 1931 R.addDecl(ND); 1932 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1933 CXXRecordDecl *Record = nullptr; 1934 if (Corrected.getCorrectionSpecifier()) { 1935 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1936 Record = Ty->getAsCXXRecordDecl(); 1937 } 1938 if (!Record) 1939 Record = cast<CXXRecordDecl>( 1940 ND->getDeclContext()->getRedeclContext()); 1941 R.setNamingClass(Record); 1942 } 1943 1944 AcceptableWithRecovery = 1945 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1946 // FIXME: If we ended up with a typo for a type name or 1947 // Objective-C class name, we're in trouble because the parser 1948 // is in the wrong place to recover. Suggest the typo 1949 // correction, but don't make it a fix-it since we're not going 1950 // to recover well anyway. 1951 AcceptableWithoutRecovery = 1952 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1953 } else { 1954 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1955 // because we aren't able to recover. 1956 AcceptableWithoutRecovery = true; 1957 } 1958 1959 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1960 unsigned NoteID = (Corrected.getCorrectionDecl() && 1961 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1962 ? diag::note_implicit_param_decl 1963 : diag::note_previous_decl; 1964 if (SS.isEmpty()) 1965 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1966 PDiag(NoteID), AcceptableWithRecovery); 1967 else 1968 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1969 << Name << computeDeclContext(SS, false) 1970 << DroppedSpecifier << SS.getRange(), 1971 PDiag(NoteID), AcceptableWithRecovery); 1972 1973 // Tell the callee whether to try to recover. 1974 return !AcceptableWithRecovery; 1975 } 1976 } 1977 R.clear(); 1978 1979 // Emit a special diagnostic for failed member lookups. 1980 // FIXME: computing the declaration context might fail here (?) 1981 if (!SS.isEmpty()) { 1982 Diag(R.getNameLoc(), diag::err_no_member) 1983 << Name << computeDeclContext(SS, false) 1984 << SS.getRange(); 1985 return true; 1986 } 1987 1988 // Give up, we can't recover. 1989 Diag(R.getNameLoc(), diagnostic) << Name; 1990 return true; 1991 } 1992 1993 /// In Microsoft mode, if we are inside a template class whose parent class has 1994 /// dependent base classes, and we can't resolve an unqualified identifier, then 1995 /// assume the identifier is a member of a dependent base class. We can only 1996 /// recover successfully in static methods, instance methods, and other contexts 1997 /// where 'this' is available. This doesn't precisely match MSVC's 1998 /// instantiation model, but it's close enough. 1999 static Expr * 2000 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2001 DeclarationNameInfo &NameInfo, 2002 SourceLocation TemplateKWLoc, 2003 const TemplateArgumentListInfo *TemplateArgs) { 2004 // Only try to recover from lookup into dependent bases in static methods or 2005 // contexts where 'this' is available. 2006 QualType ThisType = S.getCurrentThisType(); 2007 const CXXRecordDecl *RD = nullptr; 2008 if (!ThisType.isNull()) 2009 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2010 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2011 RD = MD->getParent(); 2012 if (!RD || !RD->hasAnyDependentBases()) 2013 return nullptr; 2014 2015 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2016 // is available, suggest inserting 'this->' as a fixit. 2017 SourceLocation Loc = NameInfo.getLoc(); 2018 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2019 DB << NameInfo.getName() << RD; 2020 2021 if (!ThisType.isNull()) { 2022 DB << FixItHint::CreateInsertion(Loc, "this->"); 2023 return CXXDependentScopeMemberExpr::Create( 2024 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2025 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2026 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2027 } 2028 2029 // Synthesize a fake NNS that points to the derived class. This will 2030 // perform name lookup during template instantiation. 2031 CXXScopeSpec SS; 2032 auto *NNS = 2033 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2034 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2035 return DependentScopeDeclRefExpr::Create( 2036 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2037 TemplateArgs); 2038 } 2039 2040 ExprResult 2041 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2042 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2043 bool HasTrailingLParen, bool IsAddressOfOperand, 2044 std::unique_ptr<CorrectionCandidateCallback> CCC, 2045 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2046 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2047 "cannot be direct & operand and have a trailing lparen"); 2048 if (SS.isInvalid()) 2049 return ExprError(); 2050 2051 TemplateArgumentListInfo TemplateArgsBuffer; 2052 2053 // Decompose the UnqualifiedId into the following data. 2054 DeclarationNameInfo NameInfo; 2055 const TemplateArgumentListInfo *TemplateArgs; 2056 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2057 2058 DeclarationName Name = NameInfo.getName(); 2059 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2060 SourceLocation NameLoc = NameInfo.getLoc(); 2061 2062 // C++ [temp.dep.expr]p3: 2063 // An id-expression is type-dependent if it contains: 2064 // -- an identifier that was declared with a dependent type, 2065 // (note: handled after lookup) 2066 // -- a template-id that is dependent, 2067 // (note: handled in BuildTemplateIdExpr) 2068 // -- a conversion-function-id that specifies a dependent type, 2069 // -- a nested-name-specifier that contains a class-name that 2070 // names a dependent type. 2071 // Determine whether this is a member of an unknown specialization; 2072 // we need to handle these differently. 2073 bool DependentID = false; 2074 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2075 Name.getCXXNameType()->isDependentType()) { 2076 DependentID = true; 2077 } else if (SS.isSet()) { 2078 if (DeclContext *DC = computeDeclContext(SS, false)) { 2079 if (RequireCompleteDeclContext(SS, DC)) 2080 return ExprError(); 2081 } else { 2082 DependentID = true; 2083 } 2084 } 2085 2086 if (DependentID) 2087 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2088 IsAddressOfOperand, TemplateArgs); 2089 2090 // Perform the required lookup. 2091 LookupResult R(*this, NameInfo, 2092 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2093 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2094 if (TemplateArgs) { 2095 // Lookup the template name again to correctly establish the context in 2096 // which it was found. This is really unfortunate as we already did the 2097 // lookup to determine that it was a template name in the first place. If 2098 // this becomes a performance hit, we can work harder to preserve those 2099 // results until we get here but it's likely not worth it. 2100 bool MemberOfUnknownSpecialization; 2101 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2102 MemberOfUnknownSpecialization); 2103 2104 if (MemberOfUnknownSpecialization || 2105 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2106 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2107 IsAddressOfOperand, TemplateArgs); 2108 } else { 2109 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2110 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2111 2112 // If the result might be in a dependent base class, this is a dependent 2113 // id-expression. 2114 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2115 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2116 IsAddressOfOperand, TemplateArgs); 2117 2118 // If this reference is in an Objective-C method, then we need to do 2119 // some special Objective-C lookup, too. 2120 if (IvarLookupFollowUp) { 2121 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2122 if (E.isInvalid()) 2123 return ExprError(); 2124 2125 if (Expr *Ex = E.getAs<Expr>()) 2126 return Ex; 2127 } 2128 } 2129 2130 if (R.isAmbiguous()) 2131 return ExprError(); 2132 2133 // This could be an implicitly declared function reference (legal in C90, 2134 // extension in C99, forbidden in C++). 2135 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2136 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2137 if (D) R.addDecl(D); 2138 } 2139 2140 // Determine whether this name might be a candidate for 2141 // argument-dependent lookup. 2142 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2143 2144 if (R.empty() && !ADL) { 2145 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2146 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2147 TemplateKWLoc, TemplateArgs)) 2148 return E; 2149 } 2150 2151 // Don't diagnose an empty lookup for inline assembly. 2152 if (IsInlineAsmIdentifier) 2153 return ExprError(); 2154 2155 // If this name wasn't predeclared and if this is not a function 2156 // call, diagnose the problem. 2157 TypoExpr *TE = nullptr; 2158 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2159 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2160 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2161 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2162 "Typo correction callback misconfigured"); 2163 if (CCC) { 2164 // Make sure the callback knows what the typo being diagnosed is. 2165 CCC->setTypoName(II); 2166 if (SS.isValid()) 2167 CCC->setTypoNNS(SS.getScopeRep()); 2168 } 2169 if (DiagnoseEmptyLookup(S, SS, R, 2170 CCC ? std::move(CCC) : std::move(DefaultValidator), 2171 nullptr, None, &TE)) { 2172 if (TE && KeywordReplacement) { 2173 auto &State = getTypoExprState(TE); 2174 auto BestTC = State.Consumer->getNextCorrection(); 2175 if (BestTC.isKeyword()) { 2176 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2177 if (State.DiagHandler) 2178 State.DiagHandler(BestTC); 2179 KeywordReplacement->startToken(); 2180 KeywordReplacement->setKind(II->getTokenID()); 2181 KeywordReplacement->setIdentifierInfo(II); 2182 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2183 // Clean up the state associated with the TypoExpr, since it has 2184 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2185 clearDelayedTypo(TE); 2186 // Signal that a correction to a keyword was performed by returning a 2187 // valid-but-null ExprResult. 2188 return (Expr*)nullptr; 2189 } 2190 State.Consumer->resetCorrectionStream(); 2191 } 2192 return TE ? TE : ExprError(); 2193 } 2194 2195 assert(!R.empty() && 2196 "DiagnoseEmptyLookup returned false but added no results"); 2197 2198 // If we found an Objective-C instance variable, let 2199 // LookupInObjCMethod build the appropriate expression to 2200 // reference the ivar. 2201 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2202 R.clear(); 2203 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2204 // In a hopelessly buggy code, Objective-C instance variable 2205 // lookup fails and no expression will be built to reference it. 2206 if (!E.isInvalid() && !E.get()) 2207 return ExprError(); 2208 return E; 2209 } 2210 } 2211 2212 // This is guaranteed from this point on. 2213 assert(!R.empty() || ADL); 2214 2215 // Check whether this might be a C++ implicit instance member access. 2216 // C++ [class.mfct.non-static]p3: 2217 // When an id-expression that is not part of a class member access 2218 // syntax and not used to form a pointer to member is used in the 2219 // body of a non-static member function of class X, if name lookup 2220 // resolves the name in the id-expression to a non-static non-type 2221 // member of some class C, the id-expression is transformed into a 2222 // class member access expression using (*this) as the 2223 // postfix-expression to the left of the . operator. 2224 // 2225 // But we don't actually need to do this for '&' operands if R 2226 // resolved to a function or overloaded function set, because the 2227 // expression is ill-formed if it actually works out to be a 2228 // non-static member function: 2229 // 2230 // C++ [expr.ref]p4: 2231 // Otherwise, if E1.E2 refers to a non-static member function. . . 2232 // [t]he expression can be used only as the left-hand operand of a 2233 // member function call. 2234 // 2235 // There are other safeguards against such uses, but it's important 2236 // to get this right here so that we don't end up making a 2237 // spuriously dependent expression if we're inside a dependent 2238 // instance method. 2239 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2240 bool MightBeImplicitMember; 2241 if (!IsAddressOfOperand) 2242 MightBeImplicitMember = true; 2243 else if (!SS.isEmpty()) 2244 MightBeImplicitMember = false; 2245 else if (R.isOverloadedResult()) 2246 MightBeImplicitMember = false; 2247 else if (R.isUnresolvableResult()) 2248 MightBeImplicitMember = true; 2249 else 2250 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2251 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2252 isa<MSPropertyDecl>(R.getFoundDecl()); 2253 2254 if (MightBeImplicitMember) 2255 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2256 R, TemplateArgs, S); 2257 } 2258 2259 if (TemplateArgs || TemplateKWLoc.isValid()) { 2260 2261 // In C++1y, if this is a variable template id, then check it 2262 // in BuildTemplateIdExpr(). 2263 // The single lookup result must be a variable template declaration. 2264 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2265 Id.TemplateId->Kind == TNK_Var_template) { 2266 assert(R.getAsSingle<VarTemplateDecl>() && 2267 "There should only be one declaration found."); 2268 } 2269 2270 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2271 } 2272 2273 return BuildDeclarationNameExpr(SS, R, ADL); 2274 } 2275 2276 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2277 /// declaration name, generally during template instantiation. 2278 /// There's a large number of things which don't need to be done along 2279 /// this path. 2280 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2281 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2282 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2283 DeclContext *DC = computeDeclContext(SS, false); 2284 if (!DC) 2285 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2286 NameInfo, /*TemplateArgs=*/nullptr); 2287 2288 if (RequireCompleteDeclContext(SS, DC)) 2289 return ExprError(); 2290 2291 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2292 LookupQualifiedName(R, DC); 2293 2294 if (R.isAmbiguous()) 2295 return ExprError(); 2296 2297 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2298 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2299 NameInfo, /*TemplateArgs=*/nullptr); 2300 2301 if (R.empty()) { 2302 Diag(NameInfo.getLoc(), diag::err_no_member) 2303 << NameInfo.getName() << DC << SS.getRange(); 2304 return ExprError(); 2305 } 2306 2307 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2308 // Diagnose a missing typename if this resolved unambiguously to a type in 2309 // a dependent context. If we can recover with a type, downgrade this to 2310 // a warning in Microsoft compatibility mode. 2311 unsigned DiagID = diag::err_typename_missing; 2312 if (RecoveryTSI && getLangOpts().MSVCCompat) 2313 DiagID = diag::ext_typename_missing; 2314 SourceLocation Loc = SS.getBeginLoc(); 2315 auto D = Diag(Loc, DiagID); 2316 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2317 << SourceRange(Loc, NameInfo.getEndLoc()); 2318 2319 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2320 // context. 2321 if (!RecoveryTSI) 2322 return ExprError(); 2323 2324 // Only issue the fixit if we're prepared to recover. 2325 D << FixItHint::CreateInsertion(Loc, "typename "); 2326 2327 // Recover by pretending this was an elaborated type. 2328 QualType Ty = Context.getTypeDeclType(TD); 2329 TypeLocBuilder TLB; 2330 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2331 2332 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2333 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2334 QTL.setElaboratedKeywordLoc(SourceLocation()); 2335 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2336 2337 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2338 2339 return ExprEmpty(); 2340 } 2341 2342 // Defend against this resolving to an implicit member access. We usually 2343 // won't get here if this might be a legitimate a class member (we end up in 2344 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2345 // a pointer-to-member or in an unevaluated context in C++11. 2346 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2347 return BuildPossibleImplicitMemberExpr(SS, 2348 /*TemplateKWLoc=*/SourceLocation(), 2349 R, /*TemplateArgs=*/nullptr, S); 2350 2351 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2352 } 2353 2354 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2355 /// detected that we're currently inside an ObjC method. Perform some 2356 /// additional lookup. 2357 /// 2358 /// Ideally, most of this would be done by lookup, but there's 2359 /// actually quite a lot of extra work involved. 2360 /// 2361 /// Returns a null sentinel to indicate trivial success. 2362 ExprResult 2363 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2364 IdentifierInfo *II, bool AllowBuiltinCreation) { 2365 SourceLocation Loc = Lookup.getNameLoc(); 2366 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2367 2368 // Check for error condition which is already reported. 2369 if (!CurMethod) 2370 return ExprError(); 2371 2372 // There are two cases to handle here. 1) scoped lookup could have failed, 2373 // in which case we should look for an ivar. 2) scoped lookup could have 2374 // found a decl, but that decl is outside the current instance method (i.e. 2375 // a global variable). In these two cases, we do a lookup for an ivar with 2376 // this name, if the lookup sucedes, we replace it our current decl. 2377 2378 // If we're in a class method, we don't normally want to look for 2379 // ivars. But if we don't find anything else, and there's an 2380 // ivar, that's an error. 2381 bool IsClassMethod = CurMethod->isClassMethod(); 2382 2383 bool LookForIvars; 2384 if (Lookup.empty()) 2385 LookForIvars = true; 2386 else if (IsClassMethod) 2387 LookForIvars = false; 2388 else 2389 LookForIvars = (Lookup.isSingleResult() && 2390 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2391 ObjCInterfaceDecl *IFace = nullptr; 2392 if (LookForIvars) { 2393 IFace = CurMethod->getClassInterface(); 2394 ObjCInterfaceDecl *ClassDeclared; 2395 ObjCIvarDecl *IV = nullptr; 2396 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2397 // Diagnose using an ivar in a class method. 2398 if (IsClassMethod) 2399 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2400 << IV->getDeclName()); 2401 2402 // If we're referencing an invalid decl, just return this as a silent 2403 // error node. The error diagnostic was already emitted on the decl. 2404 if (IV->isInvalidDecl()) 2405 return ExprError(); 2406 2407 // Check if referencing a field with __attribute__((deprecated)). 2408 if (DiagnoseUseOfDecl(IV, Loc)) 2409 return ExprError(); 2410 2411 // Diagnose the use of an ivar outside of the declaring class. 2412 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2413 !declaresSameEntity(ClassDeclared, IFace) && 2414 !getLangOpts().DebuggerSupport) 2415 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2416 2417 // FIXME: This should use a new expr for a direct reference, don't 2418 // turn this into Self->ivar, just return a BareIVarExpr or something. 2419 IdentifierInfo &II = Context.Idents.get("self"); 2420 UnqualifiedId SelfName; 2421 SelfName.setIdentifier(&II, SourceLocation()); 2422 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2423 CXXScopeSpec SelfScopeSpec; 2424 SourceLocation TemplateKWLoc; 2425 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2426 SelfName, false, false); 2427 if (SelfExpr.isInvalid()) 2428 return ExprError(); 2429 2430 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2431 if (SelfExpr.isInvalid()) 2432 return ExprError(); 2433 2434 MarkAnyDeclReferenced(Loc, IV, true); 2435 2436 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2437 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2438 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2439 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2440 2441 ObjCIvarRefExpr *Result = new (Context) 2442 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2443 IV->getLocation(), SelfExpr.get(), true, true); 2444 2445 if (getLangOpts().ObjCAutoRefCount) { 2446 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2447 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2448 recordUseOfEvaluatedWeak(Result); 2449 } 2450 if (CurContext->isClosure()) 2451 Diag(Loc, diag::warn_implicitly_retains_self) 2452 << FixItHint::CreateInsertion(Loc, "self->"); 2453 } 2454 2455 return Result; 2456 } 2457 } else if (CurMethod->isInstanceMethod()) { 2458 // We should warn if a local variable hides an ivar. 2459 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2460 ObjCInterfaceDecl *ClassDeclared; 2461 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2462 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2463 declaresSameEntity(IFace, ClassDeclared)) 2464 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2465 } 2466 } 2467 } else if (Lookup.isSingleResult() && 2468 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2469 // If accessing a stand-alone ivar in a class method, this is an error. 2470 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2471 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2472 << IV->getDeclName()); 2473 } 2474 2475 if (Lookup.empty() && II && AllowBuiltinCreation) { 2476 // FIXME. Consolidate this with similar code in LookupName. 2477 if (unsigned BuiltinID = II->getBuiltinID()) { 2478 if (!(getLangOpts().CPlusPlus && 2479 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2480 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2481 S, Lookup.isForRedeclaration(), 2482 Lookup.getNameLoc()); 2483 if (D) Lookup.addDecl(D); 2484 } 2485 } 2486 } 2487 // Sentinel value saying that we didn't do anything special. 2488 return ExprResult((Expr *)nullptr); 2489 } 2490 2491 /// \brief Cast a base object to a member's actual type. 2492 /// 2493 /// Logically this happens in three phases: 2494 /// 2495 /// * First we cast from the base type to the naming class. 2496 /// The naming class is the class into which we were looking 2497 /// when we found the member; it's the qualifier type if a 2498 /// qualifier was provided, and otherwise it's the base type. 2499 /// 2500 /// * Next we cast from the naming class to the declaring class. 2501 /// If the member we found was brought into a class's scope by 2502 /// a using declaration, this is that class; otherwise it's 2503 /// the class declaring the member. 2504 /// 2505 /// * Finally we cast from the declaring class to the "true" 2506 /// declaring class of the member. This conversion does not 2507 /// obey access control. 2508 ExprResult 2509 Sema::PerformObjectMemberConversion(Expr *From, 2510 NestedNameSpecifier *Qualifier, 2511 NamedDecl *FoundDecl, 2512 NamedDecl *Member) { 2513 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2514 if (!RD) 2515 return From; 2516 2517 QualType DestRecordType; 2518 QualType DestType; 2519 QualType FromRecordType; 2520 QualType FromType = From->getType(); 2521 bool PointerConversions = false; 2522 if (isa<FieldDecl>(Member)) { 2523 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2524 2525 if (FromType->getAs<PointerType>()) { 2526 DestType = Context.getPointerType(DestRecordType); 2527 FromRecordType = FromType->getPointeeType(); 2528 PointerConversions = true; 2529 } else { 2530 DestType = DestRecordType; 2531 FromRecordType = FromType; 2532 } 2533 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2534 if (Method->isStatic()) 2535 return From; 2536 2537 DestType = Method->getThisType(Context); 2538 DestRecordType = DestType->getPointeeType(); 2539 2540 if (FromType->getAs<PointerType>()) { 2541 FromRecordType = FromType->getPointeeType(); 2542 PointerConversions = true; 2543 } else { 2544 FromRecordType = FromType; 2545 DestType = DestRecordType; 2546 } 2547 } else { 2548 // No conversion necessary. 2549 return From; 2550 } 2551 2552 if (DestType->isDependentType() || FromType->isDependentType()) 2553 return From; 2554 2555 // If the unqualified types are the same, no conversion is necessary. 2556 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2557 return From; 2558 2559 SourceRange FromRange = From->getSourceRange(); 2560 SourceLocation FromLoc = FromRange.getBegin(); 2561 2562 ExprValueKind VK = From->getValueKind(); 2563 2564 // C++ [class.member.lookup]p8: 2565 // [...] Ambiguities can often be resolved by qualifying a name with its 2566 // class name. 2567 // 2568 // If the member was a qualified name and the qualified referred to a 2569 // specific base subobject type, we'll cast to that intermediate type 2570 // first and then to the object in which the member is declared. That allows 2571 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2572 // 2573 // class Base { public: int x; }; 2574 // class Derived1 : public Base { }; 2575 // class Derived2 : public Base { }; 2576 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2577 // 2578 // void VeryDerived::f() { 2579 // x = 17; // error: ambiguous base subobjects 2580 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2581 // } 2582 if (Qualifier && Qualifier->getAsType()) { 2583 QualType QType = QualType(Qualifier->getAsType(), 0); 2584 assert(QType->isRecordType() && "lookup done with non-record type"); 2585 2586 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2587 2588 // In C++98, the qualifier type doesn't actually have to be a base 2589 // type of the object type, in which case we just ignore it. 2590 // Otherwise build the appropriate casts. 2591 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2592 CXXCastPath BasePath; 2593 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2594 FromLoc, FromRange, &BasePath)) 2595 return ExprError(); 2596 2597 if (PointerConversions) 2598 QType = Context.getPointerType(QType); 2599 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2600 VK, &BasePath).get(); 2601 2602 FromType = QType; 2603 FromRecordType = QRecordType; 2604 2605 // If the qualifier type was the same as the destination type, 2606 // we're done. 2607 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2608 return From; 2609 } 2610 } 2611 2612 bool IgnoreAccess = false; 2613 2614 // If we actually found the member through a using declaration, cast 2615 // down to the using declaration's type. 2616 // 2617 // Pointer equality is fine here because only one declaration of a 2618 // class ever has member declarations. 2619 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2620 assert(isa<UsingShadowDecl>(FoundDecl)); 2621 QualType URecordType = Context.getTypeDeclType( 2622 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2623 2624 // We only need to do this if the naming-class to declaring-class 2625 // conversion is non-trivial. 2626 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2627 assert(IsDerivedFrom(FromRecordType, URecordType)); 2628 CXXCastPath BasePath; 2629 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2630 FromLoc, FromRange, &BasePath)) 2631 return ExprError(); 2632 2633 QualType UType = URecordType; 2634 if (PointerConversions) 2635 UType = Context.getPointerType(UType); 2636 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2637 VK, &BasePath).get(); 2638 FromType = UType; 2639 FromRecordType = URecordType; 2640 } 2641 2642 // We don't do access control for the conversion from the 2643 // declaring class to the true declaring class. 2644 IgnoreAccess = true; 2645 } 2646 2647 CXXCastPath BasePath; 2648 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2649 FromLoc, FromRange, &BasePath, 2650 IgnoreAccess)) 2651 return ExprError(); 2652 2653 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2654 VK, &BasePath); 2655 } 2656 2657 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2658 const LookupResult &R, 2659 bool HasTrailingLParen) { 2660 // Only when used directly as the postfix-expression of a call. 2661 if (!HasTrailingLParen) 2662 return false; 2663 2664 // Never if a scope specifier was provided. 2665 if (SS.isSet()) 2666 return false; 2667 2668 // Only in C++ or ObjC++. 2669 if (!getLangOpts().CPlusPlus) 2670 return false; 2671 2672 // Turn off ADL when we find certain kinds of declarations during 2673 // normal lookup: 2674 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2675 NamedDecl *D = *I; 2676 2677 // C++0x [basic.lookup.argdep]p3: 2678 // -- a declaration of a class member 2679 // Since using decls preserve this property, we check this on the 2680 // original decl. 2681 if (D->isCXXClassMember()) 2682 return false; 2683 2684 // C++0x [basic.lookup.argdep]p3: 2685 // -- a block-scope function declaration that is not a 2686 // using-declaration 2687 // NOTE: we also trigger this for function templates (in fact, we 2688 // don't check the decl type at all, since all other decl types 2689 // turn off ADL anyway). 2690 if (isa<UsingShadowDecl>(D)) 2691 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2692 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2693 return false; 2694 2695 // C++0x [basic.lookup.argdep]p3: 2696 // -- a declaration that is neither a function or a function 2697 // template 2698 // And also for builtin functions. 2699 if (isa<FunctionDecl>(D)) { 2700 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2701 2702 // But also builtin functions. 2703 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2704 return false; 2705 } else if (!isa<FunctionTemplateDecl>(D)) 2706 return false; 2707 } 2708 2709 return true; 2710 } 2711 2712 2713 /// Diagnoses obvious problems with the use of the given declaration 2714 /// as an expression. This is only actually called for lookups that 2715 /// were not overloaded, and it doesn't promise that the declaration 2716 /// will in fact be used. 2717 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2718 if (isa<TypedefNameDecl>(D)) { 2719 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2720 return true; 2721 } 2722 2723 if (isa<ObjCInterfaceDecl>(D)) { 2724 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2725 return true; 2726 } 2727 2728 if (isa<NamespaceDecl>(D)) { 2729 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2730 return true; 2731 } 2732 2733 return false; 2734 } 2735 2736 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2737 LookupResult &R, bool NeedsADL, 2738 bool AcceptInvalidDecl) { 2739 // If this is a single, fully-resolved result and we don't need ADL, 2740 // just build an ordinary singleton decl ref. 2741 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2742 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2743 R.getRepresentativeDecl(), nullptr, 2744 AcceptInvalidDecl); 2745 2746 // We only need to check the declaration if there's exactly one 2747 // result, because in the overloaded case the results can only be 2748 // functions and function templates. 2749 if (R.isSingleResult() && 2750 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2751 return ExprError(); 2752 2753 // Otherwise, just build an unresolved lookup expression. Suppress 2754 // any lookup-related diagnostics; we'll hash these out later, when 2755 // we've picked a target. 2756 R.suppressDiagnostics(); 2757 2758 UnresolvedLookupExpr *ULE 2759 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2760 SS.getWithLocInContext(Context), 2761 R.getLookupNameInfo(), 2762 NeedsADL, R.isOverloadedResult(), 2763 R.begin(), R.end()); 2764 2765 return ULE; 2766 } 2767 2768 /// \brief Complete semantic analysis for a reference to the given declaration. 2769 ExprResult Sema::BuildDeclarationNameExpr( 2770 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2771 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2772 bool AcceptInvalidDecl) { 2773 assert(D && "Cannot refer to a NULL declaration"); 2774 assert(!isa<FunctionTemplateDecl>(D) && 2775 "Cannot refer unambiguously to a function template"); 2776 2777 SourceLocation Loc = NameInfo.getLoc(); 2778 if (CheckDeclInExpr(*this, Loc, D)) 2779 return ExprError(); 2780 2781 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2782 // Specifically diagnose references to class templates that are missing 2783 // a template argument list. 2784 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2785 << Template << SS.getRange(); 2786 Diag(Template->getLocation(), diag::note_template_decl_here); 2787 return ExprError(); 2788 } 2789 2790 // Make sure that we're referring to a value. 2791 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2792 if (!VD) { 2793 Diag(Loc, diag::err_ref_non_value) 2794 << D << SS.getRange(); 2795 Diag(D->getLocation(), diag::note_declared_at); 2796 return ExprError(); 2797 } 2798 2799 // Check whether this declaration can be used. Note that we suppress 2800 // this check when we're going to perform argument-dependent lookup 2801 // on this function name, because this might not be the function 2802 // that overload resolution actually selects. 2803 if (DiagnoseUseOfDecl(VD, Loc)) 2804 return ExprError(); 2805 2806 // Only create DeclRefExpr's for valid Decl's. 2807 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2808 return ExprError(); 2809 2810 // Handle members of anonymous structs and unions. If we got here, 2811 // and the reference is to a class member indirect field, then this 2812 // must be the subject of a pointer-to-member expression. 2813 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2814 if (!indirectField->isCXXClassMember()) 2815 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2816 indirectField); 2817 2818 { 2819 QualType type = VD->getType(); 2820 ExprValueKind valueKind = VK_RValue; 2821 2822 switch (D->getKind()) { 2823 // Ignore all the non-ValueDecl kinds. 2824 #define ABSTRACT_DECL(kind) 2825 #define VALUE(type, base) 2826 #define DECL(type, base) \ 2827 case Decl::type: 2828 #include "clang/AST/DeclNodes.inc" 2829 llvm_unreachable("invalid value decl kind"); 2830 2831 // These shouldn't make it here. 2832 case Decl::ObjCAtDefsField: 2833 case Decl::ObjCIvar: 2834 llvm_unreachable("forming non-member reference to ivar?"); 2835 2836 // Enum constants are always r-values and never references. 2837 // Unresolved using declarations are dependent. 2838 case Decl::EnumConstant: 2839 case Decl::UnresolvedUsingValue: 2840 valueKind = VK_RValue; 2841 break; 2842 2843 // Fields and indirect fields that got here must be for 2844 // pointer-to-member expressions; we just call them l-values for 2845 // internal consistency, because this subexpression doesn't really 2846 // exist in the high-level semantics. 2847 case Decl::Field: 2848 case Decl::IndirectField: 2849 assert(getLangOpts().CPlusPlus && 2850 "building reference to field in C?"); 2851 2852 // These can't have reference type in well-formed programs, but 2853 // for internal consistency we do this anyway. 2854 type = type.getNonReferenceType(); 2855 valueKind = VK_LValue; 2856 break; 2857 2858 // Non-type template parameters are either l-values or r-values 2859 // depending on the type. 2860 case Decl::NonTypeTemplateParm: { 2861 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2862 type = reftype->getPointeeType(); 2863 valueKind = VK_LValue; // even if the parameter is an r-value reference 2864 break; 2865 } 2866 2867 // For non-references, we need to strip qualifiers just in case 2868 // the template parameter was declared as 'const int' or whatever. 2869 valueKind = VK_RValue; 2870 type = type.getUnqualifiedType(); 2871 break; 2872 } 2873 2874 case Decl::Var: 2875 case Decl::VarTemplateSpecialization: 2876 case Decl::VarTemplatePartialSpecialization: 2877 // In C, "extern void blah;" is valid and is an r-value. 2878 if (!getLangOpts().CPlusPlus && 2879 !type.hasQualifiers() && 2880 type->isVoidType()) { 2881 valueKind = VK_RValue; 2882 break; 2883 } 2884 // fallthrough 2885 2886 case Decl::ImplicitParam: 2887 case Decl::ParmVar: { 2888 // These are always l-values. 2889 valueKind = VK_LValue; 2890 type = type.getNonReferenceType(); 2891 2892 // FIXME: Does the addition of const really only apply in 2893 // potentially-evaluated contexts? Since the variable isn't actually 2894 // captured in an unevaluated context, it seems that the answer is no. 2895 if (!isUnevaluatedContext()) { 2896 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2897 if (!CapturedType.isNull()) 2898 type = CapturedType; 2899 } 2900 2901 break; 2902 } 2903 2904 case Decl::Function: { 2905 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2906 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2907 type = Context.BuiltinFnTy; 2908 valueKind = VK_RValue; 2909 break; 2910 } 2911 } 2912 2913 const FunctionType *fty = type->castAs<FunctionType>(); 2914 2915 // If we're referring to a function with an __unknown_anytype 2916 // result type, make the entire expression __unknown_anytype. 2917 if (fty->getReturnType() == Context.UnknownAnyTy) { 2918 type = Context.UnknownAnyTy; 2919 valueKind = VK_RValue; 2920 break; 2921 } 2922 2923 // Functions are l-values in C++. 2924 if (getLangOpts().CPlusPlus) { 2925 valueKind = VK_LValue; 2926 break; 2927 } 2928 2929 // C99 DR 316 says that, if a function type comes from a 2930 // function definition (without a prototype), that type is only 2931 // used for checking compatibility. Therefore, when referencing 2932 // the function, we pretend that we don't have the full function 2933 // type. 2934 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2935 isa<FunctionProtoType>(fty)) 2936 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2937 fty->getExtInfo()); 2938 2939 // Functions are r-values in C. 2940 valueKind = VK_RValue; 2941 break; 2942 } 2943 2944 case Decl::MSProperty: 2945 valueKind = VK_LValue; 2946 break; 2947 2948 case Decl::CXXMethod: 2949 // If we're referring to a method with an __unknown_anytype 2950 // result type, make the entire expression __unknown_anytype. 2951 // This should only be possible with a type written directly. 2952 if (const FunctionProtoType *proto 2953 = dyn_cast<FunctionProtoType>(VD->getType())) 2954 if (proto->getReturnType() == Context.UnknownAnyTy) { 2955 type = Context.UnknownAnyTy; 2956 valueKind = VK_RValue; 2957 break; 2958 } 2959 2960 // C++ methods are l-values if static, r-values if non-static. 2961 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2962 valueKind = VK_LValue; 2963 break; 2964 } 2965 // fallthrough 2966 2967 case Decl::CXXConversion: 2968 case Decl::CXXDestructor: 2969 case Decl::CXXConstructor: 2970 valueKind = VK_RValue; 2971 break; 2972 } 2973 2974 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2975 TemplateArgs); 2976 } 2977 } 2978 2979 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2980 SmallString<32> &Target) { 2981 Target.resize(CharByteWidth * (Source.size() + 1)); 2982 char *ResultPtr = &Target[0]; 2983 const UTF8 *ErrorPtr; 2984 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2985 (void)success; 2986 assert(success); 2987 Target.resize(ResultPtr - &Target[0]); 2988 } 2989 2990 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2991 PredefinedExpr::IdentType IT) { 2992 // Pick the current block, lambda, captured statement or function. 2993 Decl *currentDecl = nullptr; 2994 if (const BlockScopeInfo *BSI = getCurBlock()) 2995 currentDecl = BSI->TheDecl; 2996 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2997 currentDecl = LSI->CallOperator; 2998 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2999 currentDecl = CSI->TheCapturedDecl; 3000 else 3001 currentDecl = getCurFunctionOrMethodDecl(); 3002 3003 if (!currentDecl) { 3004 Diag(Loc, diag::ext_predef_outside_function); 3005 currentDecl = Context.getTranslationUnitDecl(); 3006 } 3007 3008 QualType ResTy; 3009 StringLiteral *SL = nullptr; 3010 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3011 ResTy = Context.DependentTy; 3012 else { 3013 // Pre-defined identifiers are of type char[x], where x is the length of 3014 // the string. 3015 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3016 unsigned Length = Str.length(); 3017 3018 llvm::APInt LengthI(32, Length + 1); 3019 if (IT == PredefinedExpr::LFunction) { 3020 ResTy = Context.WideCharTy.withConst(); 3021 SmallString<32> RawChars; 3022 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3023 Str, RawChars); 3024 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3025 /*IndexTypeQuals*/ 0); 3026 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3027 /*Pascal*/ false, ResTy, Loc); 3028 } else { 3029 ResTy = Context.CharTy.withConst(); 3030 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3031 /*IndexTypeQuals*/ 0); 3032 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3033 /*Pascal*/ false, ResTy, Loc); 3034 } 3035 } 3036 3037 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3038 } 3039 3040 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3041 PredefinedExpr::IdentType IT; 3042 3043 switch (Kind) { 3044 default: llvm_unreachable("Unknown simple primary expr!"); 3045 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3046 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3047 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3048 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3049 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3050 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3051 } 3052 3053 return BuildPredefinedExpr(Loc, IT); 3054 } 3055 3056 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3057 SmallString<16> CharBuffer; 3058 bool Invalid = false; 3059 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3060 if (Invalid) 3061 return ExprError(); 3062 3063 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3064 PP, Tok.getKind()); 3065 if (Literal.hadError()) 3066 return ExprError(); 3067 3068 QualType Ty; 3069 if (Literal.isWide()) 3070 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3071 else if (Literal.isUTF16()) 3072 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3073 else if (Literal.isUTF32()) 3074 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3075 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3076 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3077 else 3078 Ty = Context.CharTy; // 'x' -> char in C++ 3079 3080 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3081 if (Literal.isWide()) 3082 Kind = CharacterLiteral::Wide; 3083 else if (Literal.isUTF16()) 3084 Kind = CharacterLiteral::UTF16; 3085 else if (Literal.isUTF32()) 3086 Kind = CharacterLiteral::UTF32; 3087 3088 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3089 Tok.getLocation()); 3090 3091 if (Literal.getUDSuffix().empty()) 3092 return Lit; 3093 3094 // We're building a user-defined literal. 3095 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3096 SourceLocation UDSuffixLoc = 3097 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3098 3099 // Make sure we're allowed user-defined literals here. 3100 if (!UDLScope) 3101 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3102 3103 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3104 // operator "" X (ch) 3105 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3106 Lit, Tok.getLocation()); 3107 } 3108 3109 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3110 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3111 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3112 Context.IntTy, Loc); 3113 } 3114 3115 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3116 QualType Ty, SourceLocation Loc) { 3117 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3118 3119 using llvm::APFloat; 3120 APFloat Val(Format); 3121 3122 APFloat::opStatus result = Literal.GetFloatValue(Val); 3123 3124 // Overflow is always an error, but underflow is only an error if 3125 // we underflowed to zero (APFloat reports denormals as underflow). 3126 if ((result & APFloat::opOverflow) || 3127 ((result & APFloat::opUnderflow) && Val.isZero())) { 3128 unsigned diagnostic; 3129 SmallString<20> buffer; 3130 if (result & APFloat::opOverflow) { 3131 diagnostic = diag::warn_float_overflow; 3132 APFloat::getLargest(Format).toString(buffer); 3133 } else { 3134 diagnostic = diag::warn_float_underflow; 3135 APFloat::getSmallest(Format).toString(buffer); 3136 } 3137 3138 S.Diag(Loc, diagnostic) 3139 << Ty 3140 << StringRef(buffer.data(), buffer.size()); 3141 } 3142 3143 bool isExact = (result == APFloat::opOK); 3144 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3145 } 3146 3147 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3148 assert(E && "Invalid expression"); 3149 3150 if (E->isValueDependent()) 3151 return false; 3152 3153 QualType QT = E->getType(); 3154 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3155 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3156 return true; 3157 } 3158 3159 llvm::APSInt ValueAPS; 3160 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3161 3162 if (R.isInvalid()) 3163 return true; 3164 3165 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3166 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3167 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3168 << ValueAPS.toString(10) << ValueIsPositive; 3169 return true; 3170 } 3171 3172 return false; 3173 } 3174 3175 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3176 // Fast path for a single digit (which is quite common). A single digit 3177 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3178 if (Tok.getLength() == 1) { 3179 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3180 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3181 } 3182 3183 SmallString<128> SpellingBuffer; 3184 // NumericLiteralParser wants to overread by one character. Add padding to 3185 // the buffer in case the token is copied to the buffer. If getSpelling() 3186 // returns a StringRef to the memory buffer, it should have a null char at 3187 // the EOF, so it is also safe. 3188 SpellingBuffer.resize(Tok.getLength() + 1); 3189 3190 // Get the spelling of the token, which eliminates trigraphs, etc. 3191 bool Invalid = false; 3192 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3193 if (Invalid) 3194 return ExprError(); 3195 3196 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3197 if (Literal.hadError) 3198 return ExprError(); 3199 3200 if (Literal.hasUDSuffix()) { 3201 // We're building a user-defined literal. 3202 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3203 SourceLocation UDSuffixLoc = 3204 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3205 3206 // Make sure we're allowed user-defined literals here. 3207 if (!UDLScope) 3208 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3209 3210 QualType CookedTy; 3211 if (Literal.isFloatingLiteral()) { 3212 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3213 // long double, the literal is treated as a call of the form 3214 // operator "" X (f L) 3215 CookedTy = Context.LongDoubleTy; 3216 } else { 3217 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3218 // unsigned long long, the literal is treated as a call of the form 3219 // operator "" X (n ULL) 3220 CookedTy = Context.UnsignedLongLongTy; 3221 } 3222 3223 DeclarationName OpName = 3224 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3225 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3226 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3227 3228 SourceLocation TokLoc = Tok.getLocation(); 3229 3230 // Perform literal operator lookup to determine if we're building a raw 3231 // literal or a cooked one. 3232 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3233 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3234 /*AllowRaw*/true, /*AllowTemplate*/true, 3235 /*AllowStringTemplate*/false)) { 3236 case LOLR_Error: 3237 return ExprError(); 3238 3239 case LOLR_Cooked: { 3240 Expr *Lit; 3241 if (Literal.isFloatingLiteral()) { 3242 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3243 } else { 3244 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3245 if (Literal.GetIntegerValue(ResultVal)) 3246 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3247 << /* Unsigned */ 1; 3248 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3249 Tok.getLocation()); 3250 } 3251 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3252 } 3253 3254 case LOLR_Raw: { 3255 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3256 // literal is treated as a call of the form 3257 // operator "" X ("n") 3258 unsigned Length = Literal.getUDSuffixOffset(); 3259 QualType StrTy = Context.getConstantArrayType( 3260 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3261 ArrayType::Normal, 0); 3262 Expr *Lit = StringLiteral::Create( 3263 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3264 /*Pascal*/false, StrTy, &TokLoc, 1); 3265 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3266 } 3267 3268 case LOLR_Template: { 3269 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3270 // template), L is treated as a call fo the form 3271 // operator "" X <'c1', 'c2', ... 'ck'>() 3272 // where n is the source character sequence c1 c2 ... ck. 3273 TemplateArgumentListInfo ExplicitArgs; 3274 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3275 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3276 llvm::APSInt Value(CharBits, CharIsUnsigned); 3277 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3278 Value = TokSpelling[I]; 3279 TemplateArgument Arg(Context, Value, Context.CharTy); 3280 TemplateArgumentLocInfo ArgInfo; 3281 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3282 } 3283 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3284 &ExplicitArgs); 3285 } 3286 case LOLR_StringTemplate: 3287 llvm_unreachable("unexpected literal operator lookup result"); 3288 } 3289 } 3290 3291 Expr *Res; 3292 3293 if (Literal.isFloatingLiteral()) { 3294 QualType Ty; 3295 if (Literal.isFloat) 3296 Ty = Context.FloatTy; 3297 else if (!Literal.isLong) 3298 Ty = Context.DoubleTy; 3299 else 3300 Ty = Context.LongDoubleTy; 3301 3302 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3303 3304 if (Ty == Context.DoubleTy) { 3305 if (getLangOpts().SinglePrecisionConstants) { 3306 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3307 } else if (getLangOpts().OpenCL && 3308 !((getLangOpts().OpenCLVersion >= 120) || 3309 getOpenCLOptions().cl_khr_fp64)) { 3310 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3311 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3312 } 3313 } 3314 } else if (!Literal.isIntegerLiteral()) { 3315 return ExprError(); 3316 } else { 3317 QualType Ty; 3318 3319 // 'long long' is a C99 or C++11 feature. 3320 if (!getLangOpts().C99 && Literal.isLongLong) { 3321 if (getLangOpts().CPlusPlus) 3322 Diag(Tok.getLocation(), 3323 getLangOpts().CPlusPlus11 ? 3324 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3325 else 3326 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3327 } 3328 3329 // Get the value in the widest-possible width. 3330 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3331 llvm::APInt ResultVal(MaxWidth, 0); 3332 3333 if (Literal.GetIntegerValue(ResultVal)) { 3334 // If this value didn't fit into uintmax_t, error and force to ull. 3335 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3336 << /* Unsigned */ 1; 3337 Ty = Context.UnsignedLongLongTy; 3338 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3339 "long long is not intmax_t?"); 3340 } else { 3341 // If this value fits into a ULL, try to figure out what else it fits into 3342 // according to the rules of C99 6.4.4.1p5. 3343 3344 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3345 // be an unsigned int. 3346 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3347 3348 // Check from smallest to largest, picking the smallest type we can. 3349 unsigned Width = 0; 3350 3351 // Microsoft specific integer suffixes are explicitly sized. 3352 if (Literal.MicrosoftInteger) { 3353 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3354 Width = 8; 3355 Ty = Context.CharTy; 3356 } else { 3357 Width = Literal.MicrosoftInteger; 3358 Ty = Context.getIntTypeForBitwidth(Width, 3359 /*Signed=*/!Literal.isUnsigned); 3360 } 3361 } 3362 3363 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3364 // Are int/unsigned possibilities? 3365 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3366 3367 // Does it fit in a unsigned int? 3368 if (ResultVal.isIntN(IntSize)) { 3369 // Does it fit in a signed int? 3370 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3371 Ty = Context.IntTy; 3372 else if (AllowUnsigned) 3373 Ty = Context.UnsignedIntTy; 3374 Width = IntSize; 3375 } 3376 } 3377 3378 // Are long/unsigned long possibilities? 3379 if (Ty.isNull() && !Literal.isLongLong) { 3380 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3381 3382 // Does it fit in a unsigned long? 3383 if (ResultVal.isIntN(LongSize)) { 3384 // Does it fit in a signed long? 3385 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3386 Ty = Context.LongTy; 3387 else if (AllowUnsigned) 3388 Ty = Context.UnsignedLongTy; 3389 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3390 // is compatible. 3391 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3392 const unsigned LongLongSize = 3393 Context.getTargetInfo().getLongLongWidth(); 3394 Diag(Tok.getLocation(), 3395 getLangOpts().CPlusPlus 3396 ? Literal.isLong 3397 ? diag::warn_old_implicitly_unsigned_long_cxx 3398 : /*C++98 UB*/ diag:: 3399 ext_old_implicitly_unsigned_long_cxx 3400 : diag::warn_old_implicitly_unsigned_long) 3401 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3402 : /*will be ill-formed*/ 1); 3403 Ty = Context.UnsignedLongTy; 3404 } 3405 Width = LongSize; 3406 } 3407 } 3408 3409 // Check long long if needed. 3410 if (Ty.isNull()) { 3411 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3412 3413 // Does it fit in a unsigned long long? 3414 if (ResultVal.isIntN(LongLongSize)) { 3415 // Does it fit in a signed long long? 3416 // To be compatible with MSVC, hex integer literals ending with the 3417 // LL or i64 suffix are always signed in Microsoft mode. 3418 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3419 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3420 Ty = Context.LongLongTy; 3421 else if (AllowUnsigned) 3422 Ty = Context.UnsignedLongLongTy; 3423 Width = LongLongSize; 3424 } 3425 } 3426 3427 // If we still couldn't decide a type, we probably have something that 3428 // does not fit in a signed long long, but has no U suffix. 3429 if (Ty.isNull()) { 3430 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3431 Ty = Context.UnsignedLongLongTy; 3432 Width = Context.getTargetInfo().getLongLongWidth(); 3433 } 3434 3435 if (ResultVal.getBitWidth() != Width) 3436 ResultVal = ResultVal.trunc(Width); 3437 } 3438 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3439 } 3440 3441 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3442 if (Literal.isImaginary) 3443 Res = new (Context) ImaginaryLiteral(Res, 3444 Context.getComplexType(Res->getType())); 3445 3446 return Res; 3447 } 3448 3449 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3450 assert(E && "ActOnParenExpr() missing expr"); 3451 return new (Context) ParenExpr(L, R, E); 3452 } 3453 3454 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3455 SourceLocation Loc, 3456 SourceRange ArgRange) { 3457 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3458 // scalar or vector data type argument..." 3459 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3460 // type (C99 6.2.5p18) or void. 3461 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3462 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3463 << T << ArgRange; 3464 return true; 3465 } 3466 3467 assert((T->isVoidType() || !T->isIncompleteType()) && 3468 "Scalar types should always be complete"); 3469 return false; 3470 } 3471 3472 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3473 SourceLocation Loc, 3474 SourceRange ArgRange, 3475 UnaryExprOrTypeTrait TraitKind) { 3476 // Invalid types must be hard errors for SFINAE in C++. 3477 if (S.LangOpts.CPlusPlus) 3478 return true; 3479 3480 // C99 6.5.3.4p1: 3481 if (T->isFunctionType() && 3482 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3483 // sizeof(function)/alignof(function) is allowed as an extension. 3484 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3485 << TraitKind << ArgRange; 3486 return false; 3487 } 3488 3489 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3490 // this is an error (OpenCL v1.1 s6.3.k) 3491 if (T->isVoidType()) { 3492 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3493 : diag::ext_sizeof_alignof_void_type; 3494 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3495 return false; 3496 } 3497 3498 return true; 3499 } 3500 3501 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3502 SourceLocation Loc, 3503 SourceRange ArgRange, 3504 UnaryExprOrTypeTrait TraitKind) { 3505 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3506 // runtime doesn't allow it. 3507 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3508 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3509 << T << (TraitKind == UETT_SizeOf) 3510 << ArgRange; 3511 return true; 3512 } 3513 3514 return false; 3515 } 3516 3517 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3518 /// pointer type is equal to T) and emit a warning if it is. 3519 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3520 Expr *E) { 3521 // Don't warn if the operation changed the type. 3522 if (T != E->getType()) 3523 return; 3524 3525 // Now look for array decays. 3526 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3527 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3528 return; 3529 3530 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3531 << ICE->getType() 3532 << ICE->getSubExpr()->getType(); 3533 } 3534 3535 /// \brief Check the constraints on expression operands to unary type expression 3536 /// and type traits. 3537 /// 3538 /// Completes any types necessary and validates the constraints on the operand 3539 /// expression. The logic mostly mirrors the type-based overload, but may modify 3540 /// the expression as it completes the type for that expression through template 3541 /// instantiation, etc. 3542 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3543 UnaryExprOrTypeTrait ExprKind) { 3544 QualType ExprTy = E->getType(); 3545 assert(!ExprTy->isReferenceType()); 3546 3547 if (ExprKind == UETT_VecStep) 3548 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3549 E->getSourceRange()); 3550 3551 // Whitelist some types as extensions 3552 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3553 E->getSourceRange(), ExprKind)) 3554 return false; 3555 3556 // 'alignof' applied to an expression only requires the base element type of 3557 // the expression to be complete. 'sizeof' requires the expression's type to 3558 // be complete (and will attempt to complete it if it's an array of unknown 3559 // bound). 3560 if (ExprKind == UETT_AlignOf) { 3561 if (RequireCompleteType(E->getExprLoc(), 3562 Context.getBaseElementType(E->getType()), 3563 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3564 E->getSourceRange())) 3565 return true; 3566 } else { 3567 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3568 ExprKind, E->getSourceRange())) 3569 return true; 3570 } 3571 3572 // Completing the expression's type may have changed it. 3573 ExprTy = E->getType(); 3574 assert(!ExprTy->isReferenceType()); 3575 3576 if (ExprTy->isFunctionType()) { 3577 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3578 << ExprKind << E->getSourceRange(); 3579 return true; 3580 } 3581 3582 // The operand for sizeof and alignof is in an unevaluated expression context, 3583 // so side effects could result in unintended consequences. 3584 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3585 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3586 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3587 3588 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3589 E->getSourceRange(), ExprKind)) 3590 return true; 3591 3592 if (ExprKind == UETT_SizeOf) { 3593 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3594 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3595 QualType OType = PVD->getOriginalType(); 3596 QualType Type = PVD->getType(); 3597 if (Type->isPointerType() && OType->isArrayType()) { 3598 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3599 << Type << OType; 3600 Diag(PVD->getLocation(), diag::note_declared_at); 3601 } 3602 } 3603 } 3604 3605 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3606 // decays into a pointer and returns an unintended result. This is most 3607 // likely a typo for "sizeof(array) op x". 3608 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3609 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3610 BO->getLHS()); 3611 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3612 BO->getRHS()); 3613 } 3614 } 3615 3616 return false; 3617 } 3618 3619 /// \brief Check the constraints on operands to unary expression and type 3620 /// traits. 3621 /// 3622 /// This will complete any types necessary, and validate the various constraints 3623 /// on those operands. 3624 /// 3625 /// The UsualUnaryConversions() function is *not* called by this routine. 3626 /// C99 6.3.2.1p[2-4] all state: 3627 /// Except when it is the operand of the sizeof operator ... 3628 /// 3629 /// C++ [expr.sizeof]p4 3630 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3631 /// standard conversions are not applied to the operand of sizeof. 3632 /// 3633 /// This policy is followed for all of the unary trait expressions. 3634 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3635 SourceLocation OpLoc, 3636 SourceRange ExprRange, 3637 UnaryExprOrTypeTrait ExprKind) { 3638 if (ExprType->isDependentType()) 3639 return false; 3640 3641 // C++ [expr.sizeof]p2: 3642 // When applied to a reference or a reference type, the result 3643 // is the size of the referenced type. 3644 // C++11 [expr.alignof]p3: 3645 // When alignof is applied to a reference type, the result 3646 // shall be the alignment of the referenced type. 3647 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3648 ExprType = Ref->getPointeeType(); 3649 3650 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3651 // When alignof or _Alignof is applied to an array type, the result 3652 // is the alignment of the element type. 3653 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3654 ExprType = Context.getBaseElementType(ExprType); 3655 3656 if (ExprKind == UETT_VecStep) 3657 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3658 3659 // Whitelist some types as extensions 3660 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3661 ExprKind)) 3662 return false; 3663 3664 if (RequireCompleteType(OpLoc, ExprType, 3665 diag::err_sizeof_alignof_incomplete_type, 3666 ExprKind, ExprRange)) 3667 return true; 3668 3669 if (ExprType->isFunctionType()) { 3670 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3671 << ExprKind << ExprRange; 3672 return true; 3673 } 3674 3675 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3676 ExprKind)) 3677 return true; 3678 3679 return false; 3680 } 3681 3682 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3683 E = E->IgnoreParens(); 3684 3685 // Cannot know anything else if the expression is dependent. 3686 if (E->isTypeDependent()) 3687 return false; 3688 3689 if (E->getObjectKind() == OK_BitField) { 3690 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3691 << 1 << E->getSourceRange(); 3692 return true; 3693 } 3694 3695 ValueDecl *D = nullptr; 3696 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3697 D = DRE->getDecl(); 3698 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3699 D = ME->getMemberDecl(); 3700 } 3701 3702 // If it's a field, require the containing struct to have a 3703 // complete definition so that we can compute the layout. 3704 // 3705 // This can happen in C++11 onwards, either by naming the member 3706 // in a way that is not transformed into a member access expression 3707 // (in an unevaluated operand, for instance), or by naming the member 3708 // in a trailing-return-type. 3709 // 3710 // For the record, since __alignof__ on expressions is a GCC 3711 // extension, GCC seems to permit this but always gives the 3712 // nonsensical answer 0. 3713 // 3714 // We don't really need the layout here --- we could instead just 3715 // directly check for all the appropriate alignment-lowing 3716 // attributes --- but that would require duplicating a lot of 3717 // logic that just isn't worth duplicating for such a marginal 3718 // use-case. 3719 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3720 // Fast path this check, since we at least know the record has a 3721 // definition if we can find a member of it. 3722 if (!FD->getParent()->isCompleteDefinition()) { 3723 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3724 << E->getSourceRange(); 3725 return true; 3726 } 3727 3728 // Otherwise, if it's a field, and the field doesn't have 3729 // reference type, then it must have a complete type (or be a 3730 // flexible array member, which we explicitly want to 3731 // white-list anyway), which makes the following checks trivial. 3732 if (!FD->getType()->isReferenceType()) 3733 return false; 3734 } 3735 3736 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3737 } 3738 3739 bool Sema::CheckVecStepExpr(Expr *E) { 3740 E = E->IgnoreParens(); 3741 3742 // Cannot know anything else if the expression is dependent. 3743 if (E->isTypeDependent()) 3744 return false; 3745 3746 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3747 } 3748 3749 /// \brief Build a sizeof or alignof expression given a type operand. 3750 ExprResult 3751 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3752 SourceLocation OpLoc, 3753 UnaryExprOrTypeTrait ExprKind, 3754 SourceRange R) { 3755 if (!TInfo) 3756 return ExprError(); 3757 3758 QualType T = TInfo->getType(); 3759 3760 if (!T->isDependentType() && 3761 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3762 return ExprError(); 3763 3764 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3765 return new (Context) UnaryExprOrTypeTraitExpr( 3766 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3767 } 3768 3769 /// \brief Build a sizeof or alignof expression given an expression 3770 /// operand. 3771 ExprResult 3772 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3773 UnaryExprOrTypeTrait ExprKind) { 3774 ExprResult PE = CheckPlaceholderExpr(E); 3775 if (PE.isInvalid()) 3776 return ExprError(); 3777 3778 E = PE.get(); 3779 3780 // Verify that the operand is valid. 3781 bool isInvalid = false; 3782 if (E->isTypeDependent()) { 3783 // Delay type-checking for type-dependent expressions. 3784 } else if (ExprKind == UETT_AlignOf) { 3785 isInvalid = CheckAlignOfExpr(*this, E); 3786 } else if (ExprKind == UETT_VecStep) { 3787 isInvalid = CheckVecStepExpr(E); 3788 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3789 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3790 isInvalid = true; 3791 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3792 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3793 isInvalid = true; 3794 } else { 3795 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3796 } 3797 3798 if (isInvalid) 3799 return ExprError(); 3800 3801 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3802 PE = TransformToPotentiallyEvaluated(E); 3803 if (PE.isInvalid()) return ExprError(); 3804 E = PE.get(); 3805 } 3806 3807 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3808 return new (Context) UnaryExprOrTypeTraitExpr( 3809 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3810 } 3811 3812 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3813 /// expr and the same for @c alignof and @c __alignof 3814 /// Note that the ArgRange is invalid if isType is false. 3815 ExprResult 3816 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3817 UnaryExprOrTypeTrait ExprKind, bool IsType, 3818 void *TyOrEx, SourceRange ArgRange) { 3819 // If error parsing type, ignore. 3820 if (!TyOrEx) return ExprError(); 3821 3822 if (IsType) { 3823 TypeSourceInfo *TInfo; 3824 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3825 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3826 } 3827 3828 Expr *ArgEx = (Expr *)TyOrEx; 3829 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3830 return Result; 3831 } 3832 3833 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3834 bool IsReal) { 3835 if (V.get()->isTypeDependent()) 3836 return S.Context.DependentTy; 3837 3838 // _Real and _Imag are only l-values for normal l-values. 3839 if (V.get()->getObjectKind() != OK_Ordinary) { 3840 V = S.DefaultLvalueConversion(V.get()); 3841 if (V.isInvalid()) 3842 return QualType(); 3843 } 3844 3845 // These operators return the element type of a complex type. 3846 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3847 return CT->getElementType(); 3848 3849 // Otherwise they pass through real integer and floating point types here. 3850 if (V.get()->getType()->isArithmeticType()) 3851 return V.get()->getType(); 3852 3853 // Test for placeholders. 3854 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3855 if (PR.isInvalid()) return QualType(); 3856 if (PR.get() != V.get()) { 3857 V = PR; 3858 return CheckRealImagOperand(S, V, Loc, IsReal); 3859 } 3860 3861 // Reject anything else. 3862 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3863 << (IsReal ? "__real" : "__imag"); 3864 return QualType(); 3865 } 3866 3867 3868 3869 ExprResult 3870 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3871 tok::TokenKind Kind, Expr *Input) { 3872 UnaryOperatorKind Opc; 3873 switch (Kind) { 3874 default: llvm_unreachable("Unknown unary op!"); 3875 case tok::plusplus: Opc = UO_PostInc; break; 3876 case tok::minusminus: Opc = UO_PostDec; break; 3877 } 3878 3879 // Since this might is a postfix expression, get rid of ParenListExprs. 3880 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3881 if (Result.isInvalid()) return ExprError(); 3882 Input = Result.get(); 3883 3884 return BuildUnaryOp(S, OpLoc, Opc, Input); 3885 } 3886 3887 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3888 /// 3889 /// \return true on error 3890 static bool checkArithmeticOnObjCPointer(Sema &S, 3891 SourceLocation opLoc, 3892 Expr *op) { 3893 assert(op->getType()->isObjCObjectPointerType()); 3894 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3895 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3896 return false; 3897 3898 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3899 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3900 << op->getSourceRange(); 3901 return true; 3902 } 3903 3904 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 3905 auto *BaseNoParens = Base->IgnoreParens(); 3906 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 3907 return MSProp->getPropertyDecl()->getType()->isArrayType(); 3908 return isa<MSPropertySubscriptExpr>(BaseNoParens); 3909 } 3910 3911 ExprResult 3912 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3913 Expr *idx, SourceLocation rbLoc) { 3914 if (base && !base->getType().isNull() && 3915 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 3916 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 3917 /*Length=*/nullptr, rbLoc); 3918 3919 // Since this might be a postfix expression, get rid of ParenListExprs. 3920 if (isa<ParenListExpr>(base)) { 3921 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3922 if (result.isInvalid()) return ExprError(); 3923 base = result.get(); 3924 } 3925 3926 // Handle any non-overload placeholder types in the base and index 3927 // expressions. We can't handle overloads here because the other 3928 // operand might be an overloadable type, in which case the overload 3929 // resolution for the operator overload should get the first crack 3930 // at the overload. 3931 bool IsMSPropertySubscript = false; 3932 if (base->getType()->isNonOverloadPlaceholderType()) { 3933 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 3934 if (!IsMSPropertySubscript) { 3935 ExprResult result = CheckPlaceholderExpr(base); 3936 if (result.isInvalid()) 3937 return ExprError(); 3938 base = result.get(); 3939 } 3940 } 3941 if (idx->getType()->isNonOverloadPlaceholderType()) { 3942 ExprResult result = CheckPlaceholderExpr(idx); 3943 if (result.isInvalid()) return ExprError(); 3944 idx = result.get(); 3945 } 3946 3947 // Build an unanalyzed expression if either operand is type-dependent. 3948 if (getLangOpts().CPlusPlus && 3949 (base->isTypeDependent() || idx->isTypeDependent())) { 3950 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3951 VK_LValue, OK_Ordinary, rbLoc); 3952 } 3953 3954 // MSDN, property (C++) 3955 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 3956 // This attribute can also be used in the declaration of an empty array in a 3957 // class or structure definition. For example: 3958 // __declspec(property(get=GetX, put=PutX)) int x[]; 3959 // The above statement indicates that x[] can be used with one or more array 3960 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 3961 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 3962 if (IsMSPropertySubscript) { 3963 // Build MS property subscript expression if base is MS property reference 3964 // or MS property subscript. 3965 return new (Context) MSPropertySubscriptExpr( 3966 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 3967 } 3968 3969 // Use C++ overloaded-operator rules if either operand has record 3970 // type. The spec says to do this if either type is *overloadable*, 3971 // but enum types can't declare subscript operators or conversion 3972 // operators, so there's nothing interesting for overload resolution 3973 // to do if there aren't any record types involved. 3974 // 3975 // ObjC pointers have their own subscripting logic that is not tied 3976 // to overload resolution and so should not take this path. 3977 if (getLangOpts().CPlusPlus && 3978 (base->getType()->isRecordType() || 3979 (!base->getType()->isObjCObjectPointerType() && 3980 idx->getType()->isRecordType()))) { 3981 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3982 } 3983 3984 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3985 } 3986 3987 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 3988 Expr *LowerBound, 3989 SourceLocation ColonLoc, Expr *Length, 3990 SourceLocation RBLoc) { 3991 if (Base->getType()->isPlaceholderType() && 3992 !Base->getType()->isSpecificPlaceholderType( 3993 BuiltinType::OMPArraySection)) { 3994 ExprResult Result = CheckPlaceholderExpr(Base); 3995 if (Result.isInvalid()) 3996 return ExprError(); 3997 Base = Result.get(); 3998 } 3999 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4000 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4001 if (Result.isInvalid()) 4002 return ExprError(); 4003 LowerBound = Result.get(); 4004 } 4005 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4006 ExprResult Result = CheckPlaceholderExpr(Length); 4007 if (Result.isInvalid()) 4008 return ExprError(); 4009 Length = Result.get(); 4010 } 4011 4012 // Build an unanalyzed expression if either operand is type-dependent. 4013 if (Base->isTypeDependent() || 4014 (LowerBound && 4015 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4016 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4017 return new (Context) 4018 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4019 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4020 } 4021 4022 // Perform default conversions. 4023 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4024 QualType ResultTy; 4025 if (OriginalTy->isAnyPointerType()) { 4026 ResultTy = OriginalTy->getPointeeType(); 4027 } else if (OriginalTy->isArrayType()) { 4028 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4029 } else { 4030 return ExprError( 4031 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4032 << Base->getSourceRange()); 4033 } 4034 // C99 6.5.2.1p1 4035 if (LowerBound) { 4036 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4037 LowerBound); 4038 if (Res.isInvalid()) 4039 return ExprError(Diag(LowerBound->getExprLoc(), 4040 diag::err_omp_typecheck_section_not_integer) 4041 << 0 << LowerBound->getSourceRange()); 4042 LowerBound = Res.get(); 4043 4044 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4045 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4046 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4047 << 0 << LowerBound->getSourceRange(); 4048 } 4049 if (Length) { 4050 auto Res = 4051 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4052 if (Res.isInvalid()) 4053 return ExprError(Diag(Length->getExprLoc(), 4054 diag::err_omp_typecheck_section_not_integer) 4055 << 1 << Length->getSourceRange()); 4056 Length = Res.get(); 4057 4058 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4059 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4060 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4061 << 1 << Length->getSourceRange(); 4062 } 4063 4064 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4065 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4066 // type. Note that functions are not objects, and that (in C99 parlance) 4067 // incomplete types are not object types. 4068 if (ResultTy->isFunctionType()) { 4069 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4070 << ResultTy << Base->getSourceRange(); 4071 return ExprError(); 4072 } 4073 4074 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4075 diag::err_omp_section_incomplete_type, Base)) 4076 return ExprError(); 4077 4078 if (LowerBound) { 4079 llvm::APSInt LowerBoundValue; 4080 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4081 // OpenMP 4.0, [2.4 Array Sections] 4082 // The lower-bound and length must evaluate to non-negative integers. 4083 if (LowerBoundValue.isNegative()) { 4084 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4085 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4086 << LowerBound->getSourceRange(); 4087 return ExprError(); 4088 } 4089 } 4090 } 4091 4092 if (Length) { 4093 llvm::APSInt LengthValue; 4094 if (Length->EvaluateAsInt(LengthValue, Context)) { 4095 // OpenMP 4.0, [2.4 Array Sections] 4096 // The lower-bound and length must evaluate to non-negative integers. 4097 if (LengthValue.isNegative()) { 4098 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4099 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4100 << Length->getSourceRange(); 4101 return ExprError(); 4102 } 4103 } 4104 } else if (ColonLoc.isValid() && 4105 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4106 !OriginalTy->isVariableArrayType()))) { 4107 // OpenMP 4.0, [2.4 Array Sections] 4108 // When the size of the array dimension is not known, the length must be 4109 // specified explicitly. 4110 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4111 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4112 return ExprError(); 4113 } 4114 4115 return new (Context) 4116 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4117 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4118 } 4119 4120 ExprResult 4121 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4122 Expr *Idx, SourceLocation RLoc) { 4123 Expr *LHSExp = Base; 4124 Expr *RHSExp = Idx; 4125 4126 // Perform default conversions. 4127 if (!LHSExp->getType()->getAs<VectorType>()) { 4128 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4129 if (Result.isInvalid()) 4130 return ExprError(); 4131 LHSExp = Result.get(); 4132 } 4133 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4134 if (Result.isInvalid()) 4135 return ExprError(); 4136 RHSExp = Result.get(); 4137 4138 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4139 ExprValueKind VK = VK_LValue; 4140 ExprObjectKind OK = OK_Ordinary; 4141 4142 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4143 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4144 // in the subscript position. As a result, we need to derive the array base 4145 // and index from the expression types. 4146 Expr *BaseExpr, *IndexExpr; 4147 QualType ResultType; 4148 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4149 BaseExpr = LHSExp; 4150 IndexExpr = RHSExp; 4151 ResultType = Context.DependentTy; 4152 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4153 BaseExpr = LHSExp; 4154 IndexExpr = RHSExp; 4155 ResultType = PTy->getPointeeType(); 4156 } else if (const ObjCObjectPointerType *PTy = 4157 LHSTy->getAs<ObjCObjectPointerType>()) { 4158 BaseExpr = LHSExp; 4159 IndexExpr = RHSExp; 4160 4161 // Use custom logic if this should be the pseudo-object subscript 4162 // expression. 4163 if (!LangOpts.isSubscriptPointerArithmetic()) 4164 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4165 nullptr); 4166 4167 ResultType = PTy->getPointeeType(); 4168 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4169 // Handle the uncommon case of "123[Ptr]". 4170 BaseExpr = RHSExp; 4171 IndexExpr = LHSExp; 4172 ResultType = PTy->getPointeeType(); 4173 } else if (const ObjCObjectPointerType *PTy = 4174 RHSTy->getAs<ObjCObjectPointerType>()) { 4175 // Handle the uncommon case of "123[Ptr]". 4176 BaseExpr = RHSExp; 4177 IndexExpr = LHSExp; 4178 ResultType = PTy->getPointeeType(); 4179 if (!LangOpts.isSubscriptPointerArithmetic()) { 4180 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4181 << ResultType << BaseExpr->getSourceRange(); 4182 return ExprError(); 4183 } 4184 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4185 BaseExpr = LHSExp; // vectors: V[123] 4186 IndexExpr = RHSExp; 4187 VK = LHSExp->getValueKind(); 4188 if (VK != VK_RValue) 4189 OK = OK_VectorComponent; 4190 4191 // FIXME: need to deal with const... 4192 ResultType = VTy->getElementType(); 4193 } else if (LHSTy->isArrayType()) { 4194 // If we see an array that wasn't promoted by 4195 // DefaultFunctionArrayLvalueConversion, it must be an array that 4196 // wasn't promoted because of the C90 rule that doesn't 4197 // allow promoting non-lvalue arrays. Warn, then 4198 // force the promotion here. 4199 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4200 LHSExp->getSourceRange(); 4201 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4202 CK_ArrayToPointerDecay).get(); 4203 LHSTy = LHSExp->getType(); 4204 4205 BaseExpr = LHSExp; 4206 IndexExpr = RHSExp; 4207 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4208 } else if (RHSTy->isArrayType()) { 4209 // Same as previous, except for 123[f().a] case 4210 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4211 RHSExp->getSourceRange(); 4212 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4213 CK_ArrayToPointerDecay).get(); 4214 RHSTy = RHSExp->getType(); 4215 4216 BaseExpr = RHSExp; 4217 IndexExpr = LHSExp; 4218 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4219 } else { 4220 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4221 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4222 } 4223 // C99 6.5.2.1p1 4224 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4225 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4226 << IndexExpr->getSourceRange()); 4227 4228 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4229 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4230 && !IndexExpr->isTypeDependent()) 4231 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4232 4233 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4234 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4235 // type. Note that Functions are not objects, and that (in C99 parlance) 4236 // incomplete types are not object types. 4237 if (ResultType->isFunctionType()) { 4238 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4239 << ResultType << BaseExpr->getSourceRange(); 4240 return ExprError(); 4241 } 4242 4243 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4244 // GNU extension: subscripting on pointer to void 4245 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4246 << BaseExpr->getSourceRange(); 4247 4248 // C forbids expressions of unqualified void type from being l-values. 4249 // See IsCForbiddenLValueType. 4250 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4251 } else if (!ResultType->isDependentType() && 4252 RequireCompleteType(LLoc, ResultType, 4253 diag::err_subscript_incomplete_type, BaseExpr)) 4254 return ExprError(); 4255 4256 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4257 !ResultType.isCForbiddenLValueType()); 4258 4259 return new (Context) 4260 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4261 } 4262 4263 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4264 FunctionDecl *FD, 4265 ParmVarDecl *Param) { 4266 if (Param->hasUnparsedDefaultArg()) { 4267 Diag(CallLoc, 4268 diag::err_use_of_default_argument_to_function_declared_later) << 4269 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4270 Diag(UnparsedDefaultArgLocs[Param], 4271 diag::note_default_argument_declared_here); 4272 return ExprError(); 4273 } 4274 4275 if (Param->hasUninstantiatedDefaultArg()) { 4276 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4277 4278 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4279 Param); 4280 4281 // Instantiate the expression. 4282 MultiLevelTemplateArgumentList MutiLevelArgList 4283 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4284 4285 InstantiatingTemplate Inst(*this, CallLoc, Param, 4286 MutiLevelArgList.getInnermost()); 4287 if (Inst.isInvalid()) 4288 return ExprError(); 4289 4290 ExprResult Result; 4291 { 4292 // C++ [dcl.fct.default]p5: 4293 // The names in the [default argument] expression are bound, and 4294 // the semantic constraints are checked, at the point where the 4295 // default argument expression appears. 4296 ContextRAII SavedContext(*this, FD); 4297 LocalInstantiationScope Local(*this); 4298 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4299 } 4300 if (Result.isInvalid()) 4301 return ExprError(); 4302 4303 // Check the expression as an initializer for the parameter. 4304 InitializedEntity Entity 4305 = InitializedEntity::InitializeParameter(Context, Param); 4306 InitializationKind Kind 4307 = InitializationKind::CreateCopy(Param->getLocation(), 4308 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4309 Expr *ResultE = Result.getAs<Expr>(); 4310 4311 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4312 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4313 if (Result.isInvalid()) 4314 return ExprError(); 4315 4316 Expr *Arg = Result.getAs<Expr>(); 4317 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4318 // Build the default argument expression. 4319 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4320 } 4321 4322 // If the default expression creates temporaries, we need to 4323 // push them to the current stack of expression temporaries so they'll 4324 // be properly destroyed. 4325 // FIXME: We should really be rebuilding the default argument with new 4326 // bound temporaries; see the comment in PR5810. 4327 // We don't need to do that with block decls, though, because 4328 // blocks in default argument expression can never capture anything. 4329 if (isa<ExprWithCleanups>(Param->getInit())) { 4330 // Set the "needs cleanups" bit regardless of whether there are 4331 // any explicit objects. 4332 ExprNeedsCleanups = true; 4333 4334 // Append all the objects to the cleanup list. Right now, this 4335 // should always be a no-op, because blocks in default argument 4336 // expressions should never be able to capture anything. 4337 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4338 "default argument expression has capturing blocks?"); 4339 } 4340 4341 // We already type-checked the argument, so we know it works. 4342 // Just mark all of the declarations in this potentially-evaluated expression 4343 // as being "referenced". 4344 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4345 /*SkipLocalVariables=*/true); 4346 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4347 } 4348 4349 4350 Sema::VariadicCallType 4351 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4352 Expr *Fn) { 4353 if (Proto && Proto->isVariadic()) { 4354 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4355 return VariadicConstructor; 4356 else if (Fn && Fn->getType()->isBlockPointerType()) 4357 return VariadicBlock; 4358 else if (FDecl) { 4359 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4360 if (Method->isInstance()) 4361 return VariadicMethod; 4362 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4363 return VariadicMethod; 4364 return VariadicFunction; 4365 } 4366 return VariadicDoesNotApply; 4367 } 4368 4369 namespace { 4370 class FunctionCallCCC : public FunctionCallFilterCCC { 4371 public: 4372 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4373 unsigned NumArgs, MemberExpr *ME) 4374 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4375 FunctionName(FuncName) {} 4376 4377 bool ValidateCandidate(const TypoCorrection &candidate) override { 4378 if (!candidate.getCorrectionSpecifier() || 4379 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4380 return false; 4381 } 4382 4383 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4384 } 4385 4386 private: 4387 const IdentifierInfo *const FunctionName; 4388 }; 4389 } 4390 4391 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4392 FunctionDecl *FDecl, 4393 ArrayRef<Expr *> Args) { 4394 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4395 DeclarationName FuncName = FDecl->getDeclName(); 4396 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4397 4398 if (TypoCorrection Corrected = S.CorrectTypo( 4399 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4400 S.getScopeForContext(S.CurContext), nullptr, 4401 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4402 Args.size(), ME), 4403 Sema::CTK_ErrorRecovery)) { 4404 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4405 if (Corrected.isOverloaded()) { 4406 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4407 OverloadCandidateSet::iterator Best; 4408 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4409 CDEnd = Corrected.end(); 4410 CD != CDEnd; ++CD) { 4411 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4412 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4413 OCS); 4414 } 4415 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4416 case OR_Success: 4417 ND = Best->Function; 4418 Corrected.setCorrectionDecl(ND); 4419 break; 4420 default: 4421 break; 4422 } 4423 } 4424 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4425 return Corrected; 4426 } 4427 } 4428 } 4429 return TypoCorrection(); 4430 } 4431 4432 /// ConvertArgumentsForCall - Converts the arguments specified in 4433 /// Args/NumArgs to the parameter types of the function FDecl with 4434 /// function prototype Proto. Call is the call expression itself, and 4435 /// Fn is the function expression. For a C++ member function, this 4436 /// routine does not attempt to convert the object argument. Returns 4437 /// true if the call is ill-formed. 4438 bool 4439 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4440 FunctionDecl *FDecl, 4441 const FunctionProtoType *Proto, 4442 ArrayRef<Expr *> Args, 4443 SourceLocation RParenLoc, 4444 bool IsExecConfig) { 4445 // Bail out early if calling a builtin with custom typechecking. 4446 if (FDecl) 4447 if (unsigned ID = FDecl->getBuiltinID()) 4448 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4449 return false; 4450 4451 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4452 // assignment, to the types of the corresponding parameter, ... 4453 unsigned NumParams = Proto->getNumParams(); 4454 bool Invalid = false; 4455 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4456 unsigned FnKind = Fn->getType()->isBlockPointerType() 4457 ? 1 /* block */ 4458 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4459 : 0 /* function */); 4460 4461 // If too few arguments are available (and we don't have default 4462 // arguments for the remaining parameters), don't make the call. 4463 if (Args.size() < NumParams) { 4464 if (Args.size() < MinArgs) { 4465 TypoCorrection TC; 4466 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4467 unsigned diag_id = 4468 MinArgs == NumParams && !Proto->isVariadic() 4469 ? diag::err_typecheck_call_too_few_args_suggest 4470 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4471 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4472 << static_cast<unsigned>(Args.size()) 4473 << TC.getCorrectionRange()); 4474 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4475 Diag(RParenLoc, 4476 MinArgs == NumParams && !Proto->isVariadic() 4477 ? diag::err_typecheck_call_too_few_args_one 4478 : diag::err_typecheck_call_too_few_args_at_least_one) 4479 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4480 else 4481 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4482 ? diag::err_typecheck_call_too_few_args 4483 : diag::err_typecheck_call_too_few_args_at_least) 4484 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4485 << Fn->getSourceRange(); 4486 4487 // Emit the location of the prototype. 4488 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4489 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4490 << FDecl; 4491 4492 return true; 4493 } 4494 Call->setNumArgs(Context, NumParams); 4495 } 4496 4497 // If too many are passed and not variadic, error on the extras and drop 4498 // them. 4499 if (Args.size() > NumParams) { 4500 if (!Proto->isVariadic()) { 4501 TypoCorrection TC; 4502 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4503 unsigned diag_id = 4504 MinArgs == NumParams && !Proto->isVariadic() 4505 ? diag::err_typecheck_call_too_many_args_suggest 4506 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4507 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4508 << static_cast<unsigned>(Args.size()) 4509 << TC.getCorrectionRange()); 4510 } else if (NumParams == 1 && FDecl && 4511 FDecl->getParamDecl(0)->getDeclName()) 4512 Diag(Args[NumParams]->getLocStart(), 4513 MinArgs == NumParams 4514 ? diag::err_typecheck_call_too_many_args_one 4515 : diag::err_typecheck_call_too_many_args_at_most_one) 4516 << FnKind << FDecl->getParamDecl(0) 4517 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4518 << SourceRange(Args[NumParams]->getLocStart(), 4519 Args.back()->getLocEnd()); 4520 else 4521 Diag(Args[NumParams]->getLocStart(), 4522 MinArgs == NumParams 4523 ? diag::err_typecheck_call_too_many_args 4524 : diag::err_typecheck_call_too_many_args_at_most) 4525 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4526 << Fn->getSourceRange() 4527 << SourceRange(Args[NumParams]->getLocStart(), 4528 Args.back()->getLocEnd()); 4529 4530 // Emit the location of the prototype. 4531 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4532 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4533 << FDecl; 4534 4535 // This deletes the extra arguments. 4536 Call->setNumArgs(Context, NumParams); 4537 return true; 4538 } 4539 } 4540 SmallVector<Expr *, 8> AllArgs; 4541 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4542 4543 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4544 Proto, 0, Args, AllArgs, CallType); 4545 if (Invalid) 4546 return true; 4547 unsigned TotalNumArgs = AllArgs.size(); 4548 for (unsigned i = 0; i < TotalNumArgs; ++i) 4549 Call->setArg(i, AllArgs[i]); 4550 4551 return false; 4552 } 4553 4554 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4555 const FunctionProtoType *Proto, 4556 unsigned FirstParam, ArrayRef<Expr *> Args, 4557 SmallVectorImpl<Expr *> &AllArgs, 4558 VariadicCallType CallType, bool AllowExplicit, 4559 bool IsListInitialization) { 4560 unsigned NumParams = Proto->getNumParams(); 4561 bool Invalid = false; 4562 unsigned ArgIx = 0; 4563 // Continue to check argument types (even if we have too few/many args). 4564 for (unsigned i = FirstParam; i < NumParams; i++) { 4565 QualType ProtoArgType = Proto->getParamType(i); 4566 4567 Expr *Arg; 4568 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4569 if (ArgIx < Args.size()) { 4570 Arg = Args[ArgIx++]; 4571 4572 if (RequireCompleteType(Arg->getLocStart(), 4573 ProtoArgType, 4574 diag::err_call_incomplete_argument, Arg)) 4575 return true; 4576 4577 // Strip the unbridged-cast placeholder expression off, if applicable. 4578 bool CFAudited = false; 4579 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4580 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4581 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4582 Arg = stripARCUnbridgedCast(Arg); 4583 else if (getLangOpts().ObjCAutoRefCount && 4584 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4585 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4586 CFAudited = true; 4587 4588 InitializedEntity Entity = 4589 Param ? InitializedEntity::InitializeParameter(Context, Param, 4590 ProtoArgType) 4591 : InitializedEntity::InitializeParameter( 4592 Context, ProtoArgType, Proto->isParamConsumed(i)); 4593 4594 // Remember that parameter belongs to a CF audited API. 4595 if (CFAudited) 4596 Entity.setParameterCFAudited(); 4597 4598 ExprResult ArgE = PerformCopyInitialization( 4599 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4600 if (ArgE.isInvalid()) 4601 return true; 4602 4603 Arg = ArgE.getAs<Expr>(); 4604 } else { 4605 assert(Param && "can't use default arguments without a known callee"); 4606 4607 ExprResult ArgExpr = 4608 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4609 if (ArgExpr.isInvalid()) 4610 return true; 4611 4612 Arg = ArgExpr.getAs<Expr>(); 4613 } 4614 4615 // Check for array bounds violations for each argument to the call. This 4616 // check only triggers warnings when the argument isn't a more complex Expr 4617 // with its own checking, such as a BinaryOperator. 4618 CheckArrayAccess(Arg); 4619 4620 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4621 CheckStaticArrayArgument(CallLoc, Param, Arg); 4622 4623 AllArgs.push_back(Arg); 4624 } 4625 4626 // If this is a variadic call, handle args passed through "...". 4627 if (CallType != VariadicDoesNotApply) { 4628 // Assume that extern "C" functions with variadic arguments that 4629 // return __unknown_anytype aren't *really* variadic. 4630 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4631 FDecl->isExternC()) { 4632 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4633 QualType paramType; // ignored 4634 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4635 Invalid |= arg.isInvalid(); 4636 AllArgs.push_back(arg.get()); 4637 } 4638 4639 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4640 } else { 4641 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4642 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4643 FDecl); 4644 Invalid |= Arg.isInvalid(); 4645 AllArgs.push_back(Arg.get()); 4646 } 4647 } 4648 4649 // Check for array bounds violations. 4650 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4651 CheckArrayAccess(Args[i]); 4652 } 4653 return Invalid; 4654 } 4655 4656 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4657 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4658 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4659 TL = DTL.getOriginalLoc(); 4660 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4661 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4662 << ATL.getLocalSourceRange(); 4663 } 4664 4665 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4666 /// array parameter, check that it is non-null, and that if it is formed by 4667 /// array-to-pointer decay, the underlying array is sufficiently large. 4668 /// 4669 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4670 /// array type derivation, then for each call to the function, the value of the 4671 /// corresponding actual argument shall provide access to the first element of 4672 /// an array with at least as many elements as specified by the size expression. 4673 void 4674 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4675 ParmVarDecl *Param, 4676 const Expr *ArgExpr) { 4677 // Static array parameters are not supported in C++. 4678 if (!Param || getLangOpts().CPlusPlus) 4679 return; 4680 4681 QualType OrigTy = Param->getOriginalType(); 4682 4683 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4684 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4685 return; 4686 4687 if (ArgExpr->isNullPointerConstant(Context, 4688 Expr::NPC_NeverValueDependent)) { 4689 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4690 DiagnoseCalleeStaticArrayParam(*this, Param); 4691 return; 4692 } 4693 4694 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4695 if (!CAT) 4696 return; 4697 4698 const ConstantArrayType *ArgCAT = 4699 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4700 if (!ArgCAT) 4701 return; 4702 4703 if (ArgCAT->getSize().ult(CAT->getSize())) { 4704 Diag(CallLoc, diag::warn_static_array_too_small) 4705 << ArgExpr->getSourceRange() 4706 << (unsigned) ArgCAT->getSize().getZExtValue() 4707 << (unsigned) CAT->getSize().getZExtValue(); 4708 DiagnoseCalleeStaticArrayParam(*this, Param); 4709 } 4710 } 4711 4712 /// Given a function expression of unknown-any type, try to rebuild it 4713 /// to have a function type. 4714 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4715 4716 /// Is the given type a placeholder that we need to lower out 4717 /// immediately during argument processing? 4718 static bool isPlaceholderToRemoveAsArg(QualType type) { 4719 // Placeholders are never sugared. 4720 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4721 if (!placeholder) return false; 4722 4723 switch (placeholder->getKind()) { 4724 // Ignore all the non-placeholder types. 4725 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4726 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4727 #include "clang/AST/BuiltinTypes.def" 4728 return false; 4729 4730 // We cannot lower out overload sets; they might validly be resolved 4731 // by the call machinery. 4732 case BuiltinType::Overload: 4733 return false; 4734 4735 // Unbridged casts in ARC can be handled in some call positions and 4736 // should be left in place. 4737 case BuiltinType::ARCUnbridgedCast: 4738 return false; 4739 4740 // Pseudo-objects should be converted as soon as possible. 4741 case BuiltinType::PseudoObject: 4742 return true; 4743 4744 // The debugger mode could theoretically but currently does not try 4745 // to resolve unknown-typed arguments based on known parameter types. 4746 case BuiltinType::UnknownAny: 4747 return true; 4748 4749 // These are always invalid as call arguments and should be reported. 4750 case BuiltinType::BoundMember: 4751 case BuiltinType::BuiltinFn: 4752 case BuiltinType::OMPArraySection: 4753 return true; 4754 4755 } 4756 llvm_unreachable("bad builtin type kind"); 4757 } 4758 4759 /// Check an argument list for placeholders that we won't try to 4760 /// handle later. 4761 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4762 // Apply this processing to all the arguments at once instead of 4763 // dying at the first failure. 4764 bool hasInvalid = false; 4765 for (size_t i = 0, e = args.size(); i != e; i++) { 4766 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4767 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4768 if (result.isInvalid()) hasInvalid = true; 4769 else args[i] = result.get(); 4770 } else if (hasInvalid) { 4771 (void)S.CorrectDelayedTyposInExpr(args[i]); 4772 } 4773 } 4774 return hasInvalid; 4775 } 4776 4777 /// If a builtin function has a pointer argument with no explicit address 4778 /// space, than it should be able to accept a pointer to any address 4779 /// space as input. In order to do this, we need to replace the 4780 /// standard builtin declaration with one that uses the same address space 4781 /// as the call. 4782 /// 4783 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4784 /// it does not contain any pointer arguments without 4785 /// an address space qualifer. Otherwise the rewritten 4786 /// FunctionDecl is returned. 4787 /// TODO: Handle pointer return types. 4788 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4789 const FunctionDecl *FDecl, 4790 MultiExprArg ArgExprs) { 4791 4792 QualType DeclType = FDecl->getType(); 4793 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4794 4795 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4796 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4797 return nullptr; 4798 4799 bool NeedsNewDecl = false; 4800 unsigned i = 0; 4801 SmallVector<QualType, 8> OverloadParams; 4802 4803 for (QualType ParamType : FT->param_types()) { 4804 4805 // Convert array arguments to pointer to simplify type lookup. 4806 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4807 QualType ArgType = Arg->getType(); 4808 if (!ParamType->isPointerType() || 4809 ParamType.getQualifiers().hasAddressSpace() || 4810 !ArgType->isPointerType() || 4811 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4812 OverloadParams.push_back(ParamType); 4813 continue; 4814 } 4815 4816 NeedsNewDecl = true; 4817 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 4818 4819 QualType PointeeType = ParamType->getPointeeType(); 4820 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 4821 OverloadParams.push_back(Context.getPointerType(PointeeType)); 4822 } 4823 4824 if (!NeedsNewDecl) 4825 return nullptr; 4826 4827 FunctionProtoType::ExtProtoInfo EPI; 4828 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 4829 OverloadParams, EPI); 4830 DeclContext *Parent = Context.getTranslationUnitDecl(); 4831 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 4832 FDecl->getLocation(), 4833 FDecl->getLocation(), 4834 FDecl->getIdentifier(), 4835 OverloadTy, 4836 /*TInfo=*/nullptr, 4837 SC_Extern, false, 4838 /*hasPrototype=*/true); 4839 SmallVector<ParmVarDecl*, 16> Params; 4840 FT = cast<FunctionProtoType>(OverloadTy); 4841 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 4842 QualType ParamType = FT->getParamType(i); 4843 ParmVarDecl *Parm = 4844 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 4845 SourceLocation(), nullptr, ParamType, 4846 /*TInfo=*/nullptr, SC_None, nullptr); 4847 Parm->setScopeInfo(0, i); 4848 Params.push_back(Parm); 4849 } 4850 OverloadDecl->setParams(Params); 4851 return OverloadDecl; 4852 } 4853 4854 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4855 /// This provides the location of the left/right parens and a list of comma 4856 /// locations. 4857 ExprResult 4858 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4859 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4860 Expr *ExecConfig, bool IsExecConfig) { 4861 // Since this might be a postfix expression, get rid of ParenListExprs. 4862 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4863 if (Result.isInvalid()) return ExprError(); 4864 Fn = Result.get(); 4865 4866 if (checkArgsForPlaceholders(*this, ArgExprs)) 4867 return ExprError(); 4868 4869 if (getLangOpts().CPlusPlus) { 4870 // If this is a pseudo-destructor expression, build the call immediately. 4871 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4872 if (!ArgExprs.empty()) { 4873 // Pseudo-destructor calls should not have any arguments. 4874 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4875 << FixItHint::CreateRemoval( 4876 SourceRange(ArgExprs.front()->getLocStart(), 4877 ArgExprs.back()->getLocEnd())); 4878 } 4879 4880 return new (Context) 4881 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4882 } 4883 if (Fn->getType() == Context.PseudoObjectTy) { 4884 ExprResult result = CheckPlaceholderExpr(Fn); 4885 if (result.isInvalid()) return ExprError(); 4886 Fn = result.get(); 4887 } 4888 4889 // Determine whether this is a dependent call inside a C++ template, 4890 // in which case we won't do any semantic analysis now. 4891 // FIXME: Will need to cache the results of name lookup (including ADL) in 4892 // Fn. 4893 bool Dependent = false; 4894 if (Fn->isTypeDependent()) 4895 Dependent = true; 4896 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4897 Dependent = true; 4898 4899 if (Dependent) { 4900 if (ExecConfig) { 4901 return new (Context) CUDAKernelCallExpr( 4902 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4903 Context.DependentTy, VK_RValue, RParenLoc); 4904 } else { 4905 return new (Context) CallExpr( 4906 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4907 } 4908 } 4909 4910 // Determine whether this is a call to an object (C++ [over.call.object]). 4911 if (Fn->getType()->isRecordType()) 4912 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4913 RParenLoc); 4914 4915 if (Fn->getType() == Context.UnknownAnyTy) { 4916 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4917 if (result.isInvalid()) return ExprError(); 4918 Fn = result.get(); 4919 } 4920 4921 if (Fn->getType() == Context.BoundMemberTy) { 4922 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4923 } 4924 } 4925 4926 // Check for overloaded calls. This can happen even in C due to extensions. 4927 if (Fn->getType() == Context.OverloadTy) { 4928 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4929 4930 // We aren't supposed to apply this logic for if there's an '&' involved. 4931 if (!find.HasFormOfMemberPointer) { 4932 OverloadExpr *ovl = find.Expression; 4933 if (isa<UnresolvedLookupExpr>(ovl)) { 4934 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4935 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4936 RParenLoc, ExecConfig); 4937 } else { 4938 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4939 RParenLoc); 4940 } 4941 } 4942 } 4943 4944 // If we're directly calling a function, get the appropriate declaration. 4945 if (Fn->getType() == Context.UnknownAnyTy) { 4946 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4947 if (result.isInvalid()) return ExprError(); 4948 Fn = result.get(); 4949 } 4950 4951 Expr *NakedFn = Fn->IgnoreParens(); 4952 4953 NamedDecl *NDecl = nullptr; 4954 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4955 if (UnOp->getOpcode() == UO_AddrOf) 4956 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4957 4958 if (isa<DeclRefExpr>(NakedFn)) { 4959 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4960 4961 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 4962 if (FDecl && FDecl->getBuiltinID()) { 4963 // Rewrite the function decl for this builtin by replacing paramaters 4964 // with no explicit address space with the address space of the arguments 4965 // in ArgExprs. 4966 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 4967 NDecl = FDecl; 4968 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 4969 SourceLocation(), FDecl, false, 4970 SourceLocation(), FDecl->getType(), 4971 Fn->getValueKind(), FDecl); 4972 } 4973 } 4974 } else if (isa<MemberExpr>(NakedFn)) 4975 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4976 4977 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4978 if (FD->hasAttr<EnableIfAttr>()) { 4979 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4980 Diag(Fn->getLocStart(), 4981 isa<CXXMethodDecl>(FD) ? 4982 diag::err_ovl_no_viable_member_function_in_call : 4983 diag::err_ovl_no_viable_function_in_call) 4984 << FD << FD->getSourceRange(); 4985 Diag(FD->getLocation(), 4986 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4987 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4988 } 4989 } 4990 } 4991 4992 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4993 ExecConfig, IsExecConfig); 4994 } 4995 4996 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4997 /// 4998 /// __builtin_astype( value, dst type ) 4999 /// 5000 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5001 SourceLocation BuiltinLoc, 5002 SourceLocation RParenLoc) { 5003 ExprValueKind VK = VK_RValue; 5004 ExprObjectKind OK = OK_Ordinary; 5005 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5006 QualType SrcTy = E->getType(); 5007 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5008 return ExprError(Diag(BuiltinLoc, 5009 diag::err_invalid_astype_of_different_size) 5010 << DstTy 5011 << SrcTy 5012 << E->getSourceRange()); 5013 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5014 } 5015 5016 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5017 /// provided arguments. 5018 /// 5019 /// __builtin_convertvector( value, dst type ) 5020 /// 5021 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5022 SourceLocation BuiltinLoc, 5023 SourceLocation RParenLoc) { 5024 TypeSourceInfo *TInfo; 5025 GetTypeFromParser(ParsedDestTy, &TInfo); 5026 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5027 } 5028 5029 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5030 /// i.e. an expression not of \p OverloadTy. The expression should 5031 /// unary-convert to an expression of function-pointer or 5032 /// block-pointer type. 5033 /// 5034 /// \param NDecl the declaration being called, if available 5035 ExprResult 5036 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5037 SourceLocation LParenLoc, 5038 ArrayRef<Expr *> Args, 5039 SourceLocation RParenLoc, 5040 Expr *Config, bool IsExecConfig) { 5041 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5042 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5043 5044 // Promote the function operand. 5045 // We special-case function promotion here because we only allow promoting 5046 // builtin functions to function pointers in the callee of a call. 5047 ExprResult Result; 5048 if (BuiltinID && 5049 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5050 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5051 CK_BuiltinFnToFnPtr).get(); 5052 } else { 5053 Result = CallExprUnaryConversions(Fn); 5054 } 5055 if (Result.isInvalid()) 5056 return ExprError(); 5057 Fn = Result.get(); 5058 5059 // Make the call expr early, before semantic checks. This guarantees cleanup 5060 // of arguments and function on error. 5061 CallExpr *TheCall; 5062 if (Config) 5063 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5064 cast<CallExpr>(Config), Args, 5065 Context.BoolTy, VK_RValue, 5066 RParenLoc); 5067 else 5068 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5069 VK_RValue, RParenLoc); 5070 5071 if (!getLangOpts().CPlusPlus) { 5072 // C cannot always handle TypoExpr nodes in builtin calls and direct 5073 // function calls as their argument checking don't necessarily handle 5074 // dependent types properly, so make sure any TypoExprs have been 5075 // dealt with. 5076 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5077 if (!Result.isUsable()) return ExprError(); 5078 TheCall = dyn_cast<CallExpr>(Result.get()); 5079 if (!TheCall) return Result; 5080 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5081 } 5082 5083 // Bail out early if calling a builtin with custom typechecking. 5084 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5085 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5086 5087 retry: 5088 const FunctionType *FuncT; 5089 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5090 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5091 // have type pointer to function". 5092 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5093 if (!FuncT) 5094 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5095 << Fn->getType() << Fn->getSourceRange()); 5096 } else if (const BlockPointerType *BPT = 5097 Fn->getType()->getAs<BlockPointerType>()) { 5098 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5099 } else { 5100 // Handle calls to expressions of unknown-any type. 5101 if (Fn->getType() == Context.UnknownAnyTy) { 5102 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5103 if (rewrite.isInvalid()) return ExprError(); 5104 Fn = rewrite.get(); 5105 TheCall->setCallee(Fn); 5106 goto retry; 5107 } 5108 5109 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5110 << Fn->getType() << Fn->getSourceRange()); 5111 } 5112 5113 if (getLangOpts().CUDA) { 5114 if (Config) { 5115 // CUDA: Kernel calls must be to global functions 5116 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5117 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5118 << FDecl->getName() << Fn->getSourceRange()); 5119 5120 // CUDA: Kernel function must have 'void' return type 5121 if (!FuncT->getReturnType()->isVoidType()) 5122 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5123 << Fn->getType() << Fn->getSourceRange()); 5124 } else { 5125 // CUDA: Calls to global functions must be configured 5126 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5127 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5128 << FDecl->getName() << Fn->getSourceRange()); 5129 } 5130 } 5131 5132 // Check for a valid return type 5133 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5134 FDecl)) 5135 return ExprError(); 5136 5137 // We know the result type of the call, set it. 5138 TheCall->setType(FuncT->getCallResultType(Context)); 5139 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5140 5141 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5142 if (Proto) { 5143 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5144 IsExecConfig)) 5145 return ExprError(); 5146 } else { 5147 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5148 5149 if (FDecl) { 5150 // Check if we have too few/too many template arguments, based 5151 // on our knowledge of the function definition. 5152 const FunctionDecl *Def = nullptr; 5153 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5154 Proto = Def->getType()->getAs<FunctionProtoType>(); 5155 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5156 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5157 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5158 } 5159 5160 // If the function we're calling isn't a function prototype, but we have 5161 // a function prototype from a prior declaratiom, use that prototype. 5162 if (!FDecl->hasPrototype()) 5163 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5164 } 5165 5166 // Promote the arguments (C99 6.5.2.2p6). 5167 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5168 Expr *Arg = Args[i]; 5169 5170 if (Proto && i < Proto->getNumParams()) { 5171 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5172 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5173 ExprResult ArgE = 5174 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5175 if (ArgE.isInvalid()) 5176 return true; 5177 5178 Arg = ArgE.getAs<Expr>(); 5179 5180 } else { 5181 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5182 5183 if (ArgE.isInvalid()) 5184 return true; 5185 5186 Arg = ArgE.getAs<Expr>(); 5187 } 5188 5189 if (RequireCompleteType(Arg->getLocStart(), 5190 Arg->getType(), 5191 diag::err_call_incomplete_argument, Arg)) 5192 return ExprError(); 5193 5194 TheCall->setArg(i, Arg); 5195 } 5196 } 5197 5198 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5199 if (!Method->isStatic()) 5200 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5201 << Fn->getSourceRange()); 5202 5203 // Check for sentinels 5204 if (NDecl) 5205 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5206 5207 // Do special checking on direct calls to functions. 5208 if (FDecl) { 5209 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5210 return ExprError(); 5211 5212 if (BuiltinID) 5213 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5214 } else if (NDecl) { 5215 if (CheckPointerCall(NDecl, TheCall, Proto)) 5216 return ExprError(); 5217 } else { 5218 if (CheckOtherCall(TheCall, Proto)) 5219 return ExprError(); 5220 } 5221 5222 return MaybeBindToTemporary(TheCall); 5223 } 5224 5225 ExprResult 5226 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5227 SourceLocation RParenLoc, Expr *InitExpr) { 5228 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5229 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5230 5231 TypeSourceInfo *TInfo; 5232 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5233 if (!TInfo) 5234 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5235 5236 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5237 } 5238 5239 ExprResult 5240 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5241 SourceLocation RParenLoc, Expr *LiteralExpr) { 5242 QualType literalType = TInfo->getType(); 5243 5244 if (literalType->isArrayType()) { 5245 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5246 diag::err_illegal_decl_array_incomplete_type, 5247 SourceRange(LParenLoc, 5248 LiteralExpr->getSourceRange().getEnd()))) 5249 return ExprError(); 5250 if (literalType->isVariableArrayType()) 5251 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5252 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5253 } else if (!literalType->isDependentType() && 5254 RequireCompleteType(LParenLoc, literalType, 5255 diag::err_typecheck_decl_incomplete_type, 5256 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5257 return ExprError(); 5258 5259 InitializedEntity Entity 5260 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5261 InitializationKind Kind 5262 = InitializationKind::CreateCStyleCast(LParenLoc, 5263 SourceRange(LParenLoc, RParenLoc), 5264 /*InitList=*/true); 5265 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5266 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5267 &literalType); 5268 if (Result.isInvalid()) 5269 return ExprError(); 5270 LiteralExpr = Result.get(); 5271 5272 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5273 if (isFileScope && 5274 !LiteralExpr->isTypeDependent() && 5275 !LiteralExpr->isValueDependent() && 5276 !literalType->isDependentType()) { // 6.5.2.5p3 5277 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5278 return ExprError(); 5279 } 5280 5281 // In C, compound literals are l-values for some reason. 5282 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5283 5284 return MaybeBindToTemporary( 5285 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5286 VK, LiteralExpr, isFileScope)); 5287 } 5288 5289 ExprResult 5290 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5291 SourceLocation RBraceLoc) { 5292 // Immediately handle non-overload placeholders. Overloads can be 5293 // resolved contextually, but everything else here can't. 5294 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5295 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5296 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5297 5298 // Ignore failures; dropping the entire initializer list because 5299 // of one failure would be terrible for indexing/etc. 5300 if (result.isInvalid()) continue; 5301 5302 InitArgList[I] = result.get(); 5303 } 5304 } 5305 5306 // Semantic analysis for initializers is done by ActOnDeclarator() and 5307 // CheckInitializer() - it requires knowledge of the object being intialized. 5308 5309 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5310 RBraceLoc); 5311 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5312 return E; 5313 } 5314 5315 /// Do an explicit extend of the given block pointer if we're in ARC. 5316 void Sema::maybeExtendBlockObject(ExprResult &E) { 5317 assert(E.get()->getType()->isBlockPointerType()); 5318 assert(E.get()->isRValue()); 5319 5320 // Only do this in an r-value context. 5321 if (!getLangOpts().ObjCAutoRefCount) return; 5322 5323 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5324 CK_ARCExtendBlockObject, E.get(), 5325 /*base path*/ nullptr, VK_RValue); 5326 ExprNeedsCleanups = true; 5327 } 5328 5329 /// Prepare a conversion of the given expression to an ObjC object 5330 /// pointer type. 5331 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5332 QualType type = E.get()->getType(); 5333 if (type->isObjCObjectPointerType()) { 5334 return CK_BitCast; 5335 } else if (type->isBlockPointerType()) { 5336 maybeExtendBlockObject(E); 5337 return CK_BlockPointerToObjCPointerCast; 5338 } else { 5339 assert(type->isPointerType()); 5340 return CK_CPointerToObjCPointerCast; 5341 } 5342 } 5343 5344 /// Prepares for a scalar cast, performing all the necessary stages 5345 /// except the final cast and returning the kind required. 5346 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5347 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5348 // Also, callers should have filtered out the invalid cases with 5349 // pointers. Everything else should be possible. 5350 5351 QualType SrcTy = Src.get()->getType(); 5352 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5353 return CK_NoOp; 5354 5355 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5356 case Type::STK_MemberPointer: 5357 llvm_unreachable("member pointer type in C"); 5358 5359 case Type::STK_CPointer: 5360 case Type::STK_BlockPointer: 5361 case Type::STK_ObjCObjectPointer: 5362 switch (DestTy->getScalarTypeKind()) { 5363 case Type::STK_CPointer: { 5364 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5365 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5366 if (SrcAS != DestAS) 5367 return CK_AddressSpaceConversion; 5368 return CK_BitCast; 5369 } 5370 case Type::STK_BlockPointer: 5371 return (SrcKind == Type::STK_BlockPointer 5372 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5373 case Type::STK_ObjCObjectPointer: 5374 if (SrcKind == Type::STK_ObjCObjectPointer) 5375 return CK_BitCast; 5376 if (SrcKind == Type::STK_CPointer) 5377 return CK_CPointerToObjCPointerCast; 5378 maybeExtendBlockObject(Src); 5379 return CK_BlockPointerToObjCPointerCast; 5380 case Type::STK_Bool: 5381 return CK_PointerToBoolean; 5382 case Type::STK_Integral: 5383 return CK_PointerToIntegral; 5384 case Type::STK_Floating: 5385 case Type::STK_FloatingComplex: 5386 case Type::STK_IntegralComplex: 5387 case Type::STK_MemberPointer: 5388 llvm_unreachable("illegal cast from pointer"); 5389 } 5390 llvm_unreachable("Should have returned before this"); 5391 5392 case Type::STK_Bool: // casting from bool is like casting from an integer 5393 case Type::STK_Integral: 5394 switch (DestTy->getScalarTypeKind()) { 5395 case Type::STK_CPointer: 5396 case Type::STK_ObjCObjectPointer: 5397 case Type::STK_BlockPointer: 5398 if (Src.get()->isNullPointerConstant(Context, 5399 Expr::NPC_ValueDependentIsNull)) 5400 return CK_NullToPointer; 5401 return CK_IntegralToPointer; 5402 case Type::STK_Bool: 5403 return CK_IntegralToBoolean; 5404 case Type::STK_Integral: 5405 return CK_IntegralCast; 5406 case Type::STK_Floating: 5407 return CK_IntegralToFloating; 5408 case Type::STK_IntegralComplex: 5409 Src = ImpCastExprToType(Src.get(), 5410 DestTy->castAs<ComplexType>()->getElementType(), 5411 CK_IntegralCast); 5412 return CK_IntegralRealToComplex; 5413 case Type::STK_FloatingComplex: 5414 Src = ImpCastExprToType(Src.get(), 5415 DestTy->castAs<ComplexType>()->getElementType(), 5416 CK_IntegralToFloating); 5417 return CK_FloatingRealToComplex; 5418 case Type::STK_MemberPointer: 5419 llvm_unreachable("member pointer type in C"); 5420 } 5421 llvm_unreachable("Should have returned before this"); 5422 5423 case Type::STK_Floating: 5424 switch (DestTy->getScalarTypeKind()) { 5425 case Type::STK_Floating: 5426 return CK_FloatingCast; 5427 case Type::STK_Bool: 5428 return CK_FloatingToBoolean; 5429 case Type::STK_Integral: 5430 return CK_FloatingToIntegral; 5431 case Type::STK_FloatingComplex: 5432 Src = ImpCastExprToType(Src.get(), 5433 DestTy->castAs<ComplexType>()->getElementType(), 5434 CK_FloatingCast); 5435 return CK_FloatingRealToComplex; 5436 case Type::STK_IntegralComplex: 5437 Src = ImpCastExprToType(Src.get(), 5438 DestTy->castAs<ComplexType>()->getElementType(), 5439 CK_FloatingToIntegral); 5440 return CK_IntegralRealToComplex; 5441 case Type::STK_CPointer: 5442 case Type::STK_ObjCObjectPointer: 5443 case Type::STK_BlockPointer: 5444 llvm_unreachable("valid float->pointer cast?"); 5445 case Type::STK_MemberPointer: 5446 llvm_unreachable("member pointer type in C"); 5447 } 5448 llvm_unreachable("Should have returned before this"); 5449 5450 case Type::STK_FloatingComplex: 5451 switch (DestTy->getScalarTypeKind()) { 5452 case Type::STK_FloatingComplex: 5453 return CK_FloatingComplexCast; 5454 case Type::STK_IntegralComplex: 5455 return CK_FloatingComplexToIntegralComplex; 5456 case Type::STK_Floating: { 5457 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5458 if (Context.hasSameType(ET, DestTy)) 5459 return CK_FloatingComplexToReal; 5460 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5461 return CK_FloatingCast; 5462 } 5463 case Type::STK_Bool: 5464 return CK_FloatingComplexToBoolean; 5465 case Type::STK_Integral: 5466 Src = ImpCastExprToType(Src.get(), 5467 SrcTy->castAs<ComplexType>()->getElementType(), 5468 CK_FloatingComplexToReal); 5469 return CK_FloatingToIntegral; 5470 case Type::STK_CPointer: 5471 case Type::STK_ObjCObjectPointer: 5472 case Type::STK_BlockPointer: 5473 llvm_unreachable("valid complex float->pointer cast?"); 5474 case Type::STK_MemberPointer: 5475 llvm_unreachable("member pointer type in C"); 5476 } 5477 llvm_unreachable("Should have returned before this"); 5478 5479 case Type::STK_IntegralComplex: 5480 switch (DestTy->getScalarTypeKind()) { 5481 case Type::STK_FloatingComplex: 5482 return CK_IntegralComplexToFloatingComplex; 5483 case Type::STK_IntegralComplex: 5484 return CK_IntegralComplexCast; 5485 case Type::STK_Integral: { 5486 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5487 if (Context.hasSameType(ET, DestTy)) 5488 return CK_IntegralComplexToReal; 5489 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5490 return CK_IntegralCast; 5491 } 5492 case Type::STK_Bool: 5493 return CK_IntegralComplexToBoolean; 5494 case Type::STK_Floating: 5495 Src = ImpCastExprToType(Src.get(), 5496 SrcTy->castAs<ComplexType>()->getElementType(), 5497 CK_IntegralComplexToReal); 5498 return CK_IntegralToFloating; 5499 case Type::STK_CPointer: 5500 case Type::STK_ObjCObjectPointer: 5501 case Type::STK_BlockPointer: 5502 llvm_unreachable("valid complex int->pointer cast?"); 5503 case Type::STK_MemberPointer: 5504 llvm_unreachable("member pointer type in C"); 5505 } 5506 llvm_unreachable("Should have returned before this"); 5507 } 5508 5509 llvm_unreachable("Unhandled scalar cast"); 5510 } 5511 5512 static bool breakDownVectorType(QualType type, uint64_t &len, 5513 QualType &eltType) { 5514 // Vectors are simple. 5515 if (const VectorType *vecType = type->getAs<VectorType>()) { 5516 len = vecType->getNumElements(); 5517 eltType = vecType->getElementType(); 5518 assert(eltType->isScalarType()); 5519 return true; 5520 } 5521 5522 // We allow lax conversion to and from non-vector types, but only if 5523 // they're real types (i.e. non-complex, non-pointer scalar types). 5524 if (!type->isRealType()) return false; 5525 5526 len = 1; 5527 eltType = type; 5528 return true; 5529 } 5530 5531 /// Are the two types lax-compatible vector types? That is, given 5532 /// that one of them is a vector, do they have equal storage sizes, 5533 /// where the storage size is the number of elements times the element 5534 /// size? 5535 /// 5536 /// This will also return false if either of the types is neither a 5537 /// vector nor a real type. 5538 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5539 assert(destTy->isVectorType() || srcTy->isVectorType()); 5540 5541 // Disallow lax conversions between scalars and ExtVectors (these 5542 // conversions are allowed for other vector types because common headers 5543 // depend on them). Most scalar OP ExtVector cases are handled by the 5544 // splat path anyway, which does what we want (convert, not bitcast). 5545 // What this rules out for ExtVectors is crazy things like char4*float. 5546 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5547 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5548 5549 uint64_t srcLen, destLen; 5550 QualType srcEltTy, destEltTy; 5551 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5552 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5553 5554 // ASTContext::getTypeSize will return the size rounded up to a 5555 // power of 2, so instead of using that, we need to use the raw 5556 // element size multiplied by the element count. 5557 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5558 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5559 5560 return (srcLen * srcEltSize == destLen * destEltSize); 5561 } 5562 5563 /// Is this a legal conversion between two types, one of which is 5564 /// known to be a vector type? 5565 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5566 assert(destTy->isVectorType() || srcTy->isVectorType()); 5567 5568 if (!Context.getLangOpts().LaxVectorConversions) 5569 return false; 5570 return areLaxCompatibleVectorTypes(srcTy, destTy); 5571 } 5572 5573 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5574 CastKind &Kind) { 5575 assert(VectorTy->isVectorType() && "Not a vector type!"); 5576 5577 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5578 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5579 return Diag(R.getBegin(), 5580 Ty->isVectorType() ? 5581 diag::err_invalid_conversion_between_vectors : 5582 diag::err_invalid_conversion_between_vector_and_integer) 5583 << VectorTy << Ty << R; 5584 } else 5585 return Diag(R.getBegin(), 5586 diag::err_invalid_conversion_between_vector_and_scalar) 5587 << VectorTy << Ty << R; 5588 5589 Kind = CK_BitCast; 5590 return false; 5591 } 5592 5593 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5594 Expr *CastExpr, CastKind &Kind) { 5595 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5596 5597 QualType SrcTy = CastExpr->getType(); 5598 5599 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5600 // an ExtVectorType. 5601 // In OpenCL, casts between vectors of different types are not allowed. 5602 // (See OpenCL 6.2). 5603 if (SrcTy->isVectorType()) { 5604 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5605 || (getLangOpts().OpenCL && 5606 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5607 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5608 << DestTy << SrcTy << R; 5609 return ExprError(); 5610 } 5611 Kind = CK_BitCast; 5612 return CastExpr; 5613 } 5614 5615 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5616 // conversion will take place first from scalar to elt type, and then 5617 // splat from elt type to vector. 5618 if (SrcTy->isPointerType()) 5619 return Diag(R.getBegin(), 5620 diag::err_invalid_conversion_between_vector_and_scalar) 5621 << DestTy << SrcTy << R; 5622 5623 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5624 ExprResult CastExprRes = CastExpr; 5625 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5626 if (CastExprRes.isInvalid()) 5627 return ExprError(); 5628 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5629 5630 Kind = CK_VectorSplat; 5631 return CastExpr; 5632 } 5633 5634 ExprResult 5635 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5636 Declarator &D, ParsedType &Ty, 5637 SourceLocation RParenLoc, Expr *CastExpr) { 5638 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5639 "ActOnCastExpr(): missing type or expr"); 5640 5641 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5642 if (D.isInvalidType()) 5643 return ExprError(); 5644 5645 if (getLangOpts().CPlusPlus) { 5646 // Check that there are no default arguments (C++ only). 5647 CheckExtraCXXDefaultArguments(D); 5648 } else { 5649 // Make sure any TypoExprs have been dealt with. 5650 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5651 if (!Res.isUsable()) 5652 return ExprError(); 5653 CastExpr = Res.get(); 5654 } 5655 5656 checkUnusedDeclAttributes(D); 5657 5658 QualType castType = castTInfo->getType(); 5659 Ty = CreateParsedType(castType, castTInfo); 5660 5661 bool isVectorLiteral = false; 5662 5663 // Check for an altivec or OpenCL literal, 5664 // i.e. all the elements are integer constants. 5665 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5666 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5667 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5668 && castType->isVectorType() && (PE || PLE)) { 5669 if (PLE && PLE->getNumExprs() == 0) { 5670 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5671 return ExprError(); 5672 } 5673 if (PE || PLE->getNumExprs() == 1) { 5674 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5675 if (!E->getType()->isVectorType()) 5676 isVectorLiteral = true; 5677 } 5678 else 5679 isVectorLiteral = true; 5680 } 5681 5682 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5683 // then handle it as such. 5684 if (isVectorLiteral) 5685 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5686 5687 // If the Expr being casted is a ParenListExpr, handle it specially. 5688 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5689 // sequence of BinOp comma operators. 5690 if (isa<ParenListExpr>(CastExpr)) { 5691 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5692 if (Result.isInvalid()) return ExprError(); 5693 CastExpr = Result.get(); 5694 } 5695 5696 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5697 !getSourceManager().isInSystemMacro(LParenLoc)) 5698 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5699 5700 CheckTollFreeBridgeCast(castType, CastExpr); 5701 5702 CheckObjCBridgeRelatedCast(castType, CastExpr); 5703 5704 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5705 } 5706 5707 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5708 SourceLocation RParenLoc, Expr *E, 5709 TypeSourceInfo *TInfo) { 5710 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5711 "Expected paren or paren list expression"); 5712 5713 Expr **exprs; 5714 unsigned numExprs; 5715 Expr *subExpr; 5716 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5717 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5718 LiteralLParenLoc = PE->getLParenLoc(); 5719 LiteralRParenLoc = PE->getRParenLoc(); 5720 exprs = PE->getExprs(); 5721 numExprs = PE->getNumExprs(); 5722 } else { // isa<ParenExpr> by assertion at function entrance 5723 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5724 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5725 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5726 exprs = &subExpr; 5727 numExprs = 1; 5728 } 5729 5730 QualType Ty = TInfo->getType(); 5731 assert(Ty->isVectorType() && "Expected vector type"); 5732 5733 SmallVector<Expr *, 8> initExprs; 5734 const VectorType *VTy = Ty->getAs<VectorType>(); 5735 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5736 5737 // '(...)' form of vector initialization in AltiVec: the number of 5738 // initializers must be one or must match the size of the vector. 5739 // If a single value is specified in the initializer then it will be 5740 // replicated to all the components of the vector 5741 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5742 // The number of initializers must be one or must match the size of the 5743 // vector. If a single value is specified in the initializer then it will 5744 // be replicated to all the components of the vector 5745 if (numExprs == 1) { 5746 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5747 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5748 if (Literal.isInvalid()) 5749 return ExprError(); 5750 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5751 PrepareScalarCast(Literal, ElemTy)); 5752 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5753 } 5754 else if (numExprs < numElems) { 5755 Diag(E->getExprLoc(), 5756 diag::err_incorrect_number_of_vector_initializers); 5757 return ExprError(); 5758 } 5759 else 5760 initExprs.append(exprs, exprs + numExprs); 5761 } 5762 else { 5763 // For OpenCL, when the number of initializers is a single value, 5764 // it will be replicated to all components of the vector. 5765 if (getLangOpts().OpenCL && 5766 VTy->getVectorKind() == VectorType::GenericVector && 5767 numExprs == 1) { 5768 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5769 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5770 if (Literal.isInvalid()) 5771 return ExprError(); 5772 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5773 PrepareScalarCast(Literal, ElemTy)); 5774 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5775 } 5776 5777 initExprs.append(exprs, exprs + numExprs); 5778 } 5779 // FIXME: This means that pretty-printing the final AST will produce curly 5780 // braces instead of the original commas. 5781 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5782 initExprs, LiteralRParenLoc); 5783 initE->setType(Ty); 5784 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5785 } 5786 5787 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5788 /// the ParenListExpr into a sequence of comma binary operators. 5789 ExprResult 5790 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5791 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5792 if (!E) 5793 return OrigExpr; 5794 5795 ExprResult Result(E->getExpr(0)); 5796 5797 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5798 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5799 E->getExpr(i)); 5800 5801 if (Result.isInvalid()) return ExprError(); 5802 5803 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5804 } 5805 5806 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5807 SourceLocation R, 5808 MultiExprArg Val) { 5809 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5810 return expr; 5811 } 5812 5813 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5814 /// constant and the other is not a pointer. Returns true if a diagnostic is 5815 /// emitted. 5816 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5817 SourceLocation QuestionLoc) { 5818 Expr *NullExpr = LHSExpr; 5819 Expr *NonPointerExpr = RHSExpr; 5820 Expr::NullPointerConstantKind NullKind = 5821 NullExpr->isNullPointerConstant(Context, 5822 Expr::NPC_ValueDependentIsNotNull); 5823 5824 if (NullKind == Expr::NPCK_NotNull) { 5825 NullExpr = RHSExpr; 5826 NonPointerExpr = LHSExpr; 5827 NullKind = 5828 NullExpr->isNullPointerConstant(Context, 5829 Expr::NPC_ValueDependentIsNotNull); 5830 } 5831 5832 if (NullKind == Expr::NPCK_NotNull) 5833 return false; 5834 5835 if (NullKind == Expr::NPCK_ZeroExpression) 5836 return false; 5837 5838 if (NullKind == Expr::NPCK_ZeroLiteral) { 5839 // In this case, check to make sure that we got here from a "NULL" 5840 // string in the source code. 5841 NullExpr = NullExpr->IgnoreParenImpCasts(); 5842 SourceLocation loc = NullExpr->getExprLoc(); 5843 if (!findMacroSpelling(loc, "NULL")) 5844 return false; 5845 } 5846 5847 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5848 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5849 << NonPointerExpr->getType() << DiagType 5850 << NonPointerExpr->getSourceRange(); 5851 return true; 5852 } 5853 5854 /// \brief Return false if the condition expression is valid, true otherwise. 5855 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 5856 QualType CondTy = Cond->getType(); 5857 5858 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 5859 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 5860 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 5861 << CondTy << Cond->getSourceRange(); 5862 return true; 5863 } 5864 5865 // C99 6.5.15p2 5866 if (CondTy->isScalarType()) return false; 5867 5868 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 5869 << CondTy << Cond->getSourceRange(); 5870 return true; 5871 } 5872 5873 /// \brief Handle when one or both operands are void type. 5874 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5875 ExprResult &RHS) { 5876 Expr *LHSExpr = LHS.get(); 5877 Expr *RHSExpr = RHS.get(); 5878 5879 if (!LHSExpr->getType()->isVoidType()) 5880 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5881 << RHSExpr->getSourceRange(); 5882 if (!RHSExpr->getType()->isVoidType()) 5883 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5884 << LHSExpr->getSourceRange(); 5885 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5886 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5887 return S.Context.VoidTy; 5888 } 5889 5890 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5891 /// true otherwise. 5892 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5893 QualType PointerTy) { 5894 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5895 !NullExpr.get()->isNullPointerConstant(S.Context, 5896 Expr::NPC_ValueDependentIsNull)) 5897 return true; 5898 5899 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5900 return false; 5901 } 5902 5903 /// \brief Checks compatibility between two pointers and return the resulting 5904 /// type. 5905 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5906 ExprResult &RHS, 5907 SourceLocation Loc) { 5908 QualType LHSTy = LHS.get()->getType(); 5909 QualType RHSTy = RHS.get()->getType(); 5910 5911 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5912 // Two identical pointers types are always compatible. 5913 return LHSTy; 5914 } 5915 5916 QualType lhptee, rhptee; 5917 5918 // Get the pointee types. 5919 bool IsBlockPointer = false; 5920 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5921 lhptee = LHSBTy->getPointeeType(); 5922 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5923 IsBlockPointer = true; 5924 } else { 5925 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5926 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5927 } 5928 5929 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5930 // differently qualified versions of compatible types, the result type is 5931 // a pointer to an appropriately qualified version of the composite 5932 // type. 5933 5934 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5935 // clause doesn't make sense for our extensions. E.g. address space 2 should 5936 // be incompatible with address space 3: they may live on different devices or 5937 // anything. 5938 Qualifiers lhQual = lhptee.getQualifiers(); 5939 Qualifiers rhQual = rhptee.getQualifiers(); 5940 5941 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5942 lhQual.removeCVRQualifiers(); 5943 rhQual.removeCVRQualifiers(); 5944 5945 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5946 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5947 5948 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5949 5950 if (CompositeTy.isNull()) { 5951 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 5952 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5953 << RHS.get()->getSourceRange(); 5954 // In this situation, we assume void* type. No especially good 5955 // reason, but this is what gcc does, and we do have to pick 5956 // to get a consistent AST. 5957 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5958 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5959 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5960 return incompatTy; 5961 } 5962 5963 // The pointer types are compatible. 5964 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5965 if (IsBlockPointer) 5966 ResultTy = S.Context.getBlockPointerType(ResultTy); 5967 else 5968 ResultTy = S.Context.getPointerType(ResultTy); 5969 5970 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5971 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5972 return ResultTy; 5973 } 5974 5975 /// \brief Return the resulting type when the operands are both block pointers. 5976 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5977 ExprResult &LHS, 5978 ExprResult &RHS, 5979 SourceLocation Loc) { 5980 QualType LHSTy = LHS.get()->getType(); 5981 QualType RHSTy = RHS.get()->getType(); 5982 5983 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5984 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5985 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5986 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5987 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5988 return destType; 5989 } 5990 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5991 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5992 << RHS.get()->getSourceRange(); 5993 return QualType(); 5994 } 5995 5996 // We have 2 block pointer types. 5997 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5998 } 5999 6000 /// \brief Return the resulting type when the operands are both pointers. 6001 static QualType 6002 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6003 ExprResult &RHS, 6004 SourceLocation Loc) { 6005 // get the pointer types 6006 QualType LHSTy = LHS.get()->getType(); 6007 QualType RHSTy = RHS.get()->getType(); 6008 6009 // get the "pointed to" types 6010 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6011 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6012 6013 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6014 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6015 // Figure out necessary qualifiers (C99 6.5.15p6) 6016 QualType destPointee 6017 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6018 QualType destType = S.Context.getPointerType(destPointee); 6019 // Add qualifiers if necessary. 6020 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6021 // Promote to void*. 6022 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6023 return destType; 6024 } 6025 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6026 QualType destPointee 6027 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6028 QualType destType = S.Context.getPointerType(destPointee); 6029 // Add qualifiers if necessary. 6030 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6031 // Promote to void*. 6032 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6033 return destType; 6034 } 6035 6036 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6037 } 6038 6039 /// \brief Return false if the first expression is not an integer and the second 6040 /// expression is not a pointer, true otherwise. 6041 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6042 Expr* PointerExpr, SourceLocation Loc, 6043 bool IsIntFirstExpr) { 6044 if (!PointerExpr->getType()->isPointerType() || 6045 !Int.get()->getType()->isIntegerType()) 6046 return false; 6047 6048 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6049 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6050 6051 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6052 << Expr1->getType() << Expr2->getType() 6053 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6054 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6055 CK_IntegralToPointer); 6056 return true; 6057 } 6058 6059 /// \brief Simple conversion between integer and floating point types. 6060 /// 6061 /// Used when handling the OpenCL conditional operator where the 6062 /// condition is a vector while the other operands are scalar. 6063 /// 6064 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6065 /// types are either integer or floating type. Between the two 6066 /// operands, the type with the higher rank is defined as the "result 6067 /// type". The other operand needs to be promoted to the same type. No 6068 /// other type promotion is allowed. We cannot use 6069 /// UsualArithmeticConversions() for this purpose, since it always 6070 /// promotes promotable types. 6071 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6072 ExprResult &RHS, 6073 SourceLocation QuestionLoc) { 6074 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6075 if (LHS.isInvalid()) 6076 return QualType(); 6077 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6078 if (RHS.isInvalid()) 6079 return QualType(); 6080 6081 // For conversion purposes, we ignore any qualifiers. 6082 // For example, "const float" and "float" are equivalent. 6083 QualType LHSType = 6084 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6085 QualType RHSType = 6086 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6087 6088 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6089 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6090 << LHSType << LHS.get()->getSourceRange(); 6091 return QualType(); 6092 } 6093 6094 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6095 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6096 << RHSType << RHS.get()->getSourceRange(); 6097 return QualType(); 6098 } 6099 6100 // If both types are identical, no conversion is needed. 6101 if (LHSType == RHSType) 6102 return LHSType; 6103 6104 // Now handle "real" floating types (i.e. float, double, long double). 6105 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6106 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6107 /*IsCompAssign = */ false); 6108 6109 // Finally, we have two differing integer types. 6110 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6111 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6112 } 6113 6114 /// \brief Convert scalar operands to a vector that matches the 6115 /// condition in length. 6116 /// 6117 /// Used when handling the OpenCL conditional operator where the 6118 /// condition is a vector while the other operands are scalar. 6119 /// 6120 /// We first compute the "result type" for the scalar operands 6121 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6122 /// into a vector of that type where the length matches the condition 6123 /// vector type. s6.11.6 requires that the element types of the result 6124 /// and the condition must have the same number of bits. 6125 static QualType 6126 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6127 QualType CondTy, SourceLocation QuestionLoc) { 6128 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6129 if (ResTy.isNull()) return QualType(); 6130 6131 const VectorType *CV = CondTy->getAs<VectorType>(); 6132 assert(CV); 6133 6134 // Determine the vector result type 6135 unsigned NumElements = CV->getNumElements(); 6136 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6137 6138 // Ensure that all types have the same number of bits 6139 if (S.Context.getTypeSize(CV->getElementType()) 6140 != S.Context.getTypeSize(ResTy)) { 6141 // Since VectorTy is created internally, it does not pretty print 6142 // with an OpenCL name. Instead, we just print a description. 6143 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6144 SmallString<64> Str; 6145 llvm::raw_svector_ostream OS(Str); 6146 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6147 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6148 << CondTy << OS.str(); 6149 return QualType(); 6150 } 6151 6152 // Convert operands to the vector result type 6153 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6154 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6155 6156 return VectorTy; 6157 } 6158 6159 /// \brief Return false if this is a valid OpenCL condition vector 6160 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6161 SourceLocation QuestionLoc) { 6162 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6163 // integral type. 6164 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6165 assert(CondTy); 6166 QualType EleTy = CondTy->getElementType(); 6167 if (EleTy->isIntegerType()) return false; 6168 6169 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6170 << Cond->getType() << Cond->getSourceRange(); 6171 return true; 6172 } 6173 6174 /// \brief Return false if the vector condition type and the vector 6175 /// result type are compatible. 6176 /// 6177 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6178 /// number of elements, and their element types have the same number 6179 /// of bits. 6180 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6181 SourceLocation QuestionLoc) { 6182 const VectorType *CV = CondTy->getAs<VectorType>(); 6183 const VectorType *RV = VecResTy->getAs<VectorType>(); 6184 assert(CV && RV); 6185 6186 if (CV->getNumElements() != RV->getNumElements()) { 6187 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6188 << CondTy << VecResTy; 6189 return true; 6190 } 6191 6192 QualType CVE = CV->getElementType(); 6193 QualType RVE = RV->getElementType(); 6194 6195 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6196 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6197 << CondTy << VecResTy; 6198 return true; 6199 } 6200 6201 return false; 6202 } 6203 6204 /// \brief Return the resulting type for the conditional operator in 6205 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6206 /// s6.3.i) when the condition is a vector type. 6207 static QualType 6208 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6209 ExprResult &LHS, ExprResult &RHS, 6210 SourceLocation QuestionLoc) { 6211 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6212 if (Cond.isInvalid()) 6213 return QualType(); 6214 QualType CondTy = Cond.get()->getType(); 6215 6216 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6217 return QualType(); 6218 6219 // If either operand is a vector then find the vector type of the 6220 // result as specified in OpenCL v1.1 s6.3.i. 6221 if (LHS.get()->getType()->isVectorType() || 6222 RHS.get()->getType()->isVectorType()) { 6223 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6224 /*isCompAssign*/false, 6225 /*AllowBothBool*/true, 6226 /*AllowBoolConversions*/false); 6227 if (VecResTy.isNull()) return QualType(); 6228 // The result type must match the condition type as specified in 6229 // OpenCL v1.1 s6.11.6. 6230 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6231 return QualType(); 6232 return VecResTy; 6233 } 6234 6235 // Both operands are scalar. 6236 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6237 } 6238 6239 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6240 /// In that case, LHS = cond. 6241 /// C99 6.5.15 6242 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6243 ExprResult &RHS, ExprValueKind &VK, 6244 ExprObjectKind &OK, 6245 SourceLocation QuestionLoc) { 6246 6247 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6248 if (!LHSResult.isUsable()) return QualType(); 6249 LHS = LHSResult; 6250 6251 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6252 if (!RHSResult.isUsable()) return QualType(); 6253 RHS = RHSResult; 6254 6255 // C++ is sufficiently different to merit its own checker. 6256 if (getLangOpts().CPlusPlus) 6257 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6258 6259 VK = VK_RValue; 6260 OK = OK_Ordinary; 6261 6262 // The OpenCL operator with a vector condition is sufficiently 6263 // different to merit its own checker. 6264 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6265 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6266 6267 // First, check the condition. 6268 Cond = UsualUnaryConversions(Cond.get()); 6269 if (Cond.isInvalid()) 6270 return QualType(); 6271 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6272 return QualType(); 6273 6274 // Now check the two expressions. 6275 if (LHS.get()->getType()->isVectorType() || 6276 RHS.get()->getType()->isVectorType()) 6277 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6278 /*AllowBothBool*/true, 6279 /*AllowBoolConversions*/false); 6280 6281 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6282 if (LHS.isInvalid() || RHS.isInvalid()) 6283 return QualType(); 6284 6285 QualType LHSTy = LHS.get()->getType(); 6286 QualType RHSTy = RHS.get()->getType(); 6287 6288 // If both operands have arithmetic type, do the usual arithmetic conversions 6289 // to find a common type: C99 6.5.15p3,5. 6290 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6291 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6292 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6293 6294 return ResTy; 6295 } 6296 6297 // If both operands are the same structure or union type, the result is that 6298 // type. 6299 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6300 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6301 if (LHSRT->getDecl() == RHSRT->getDecl()) 6302 // "If both the operands have structure or union type, the result has 6303 // that type." This implies that CV qualifiers are dropped. 6304 return LHSTy.getUnqualifiedType(); 6305 // FIXME: Type of conditional expression must be complete in C mode. 6306 } 6307 6308 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6309 // The following || allows only one side to be void (a GCC-ism). 6310 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6311 return checkConditionalVoidType(*this, LHS, RHS); 6312 } 6313 6314 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6315 // the type of the other operand." 6316 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6317 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6318 6319 // All objective-c pointer type analysis is done here. 6320 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6321 QuestionLoc); 6322 if (LHS.isInvalid() || RHS.isInvalid()) 6323 return QualType(); 6324 if (!compositeType.isNull()) 6325 return compositeType; 6326 6327 6328 // Handle block pointer types. 6329 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6330 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6331 QuestionLoc); 6332 6333 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6334 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6335 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6336 QuestionLoc); 6337 6338 // GCC compatibility: soften pointer/integer mismatch. Note that 6339 // null pointers have been filtered out by this point. 6340 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6341 /*isIntFirstExpr=*/true)) 6342 return RHSTy; 6343 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6344 /*isIntFirstExpr=*/false)) 6345 return LHSTy; 6346 6347 // Emit a better diagnostic if one of the expressions is a null pointer 6348 // constant and the other is not a pointer type. In this case, the user most 6349 // likely forgot to take the address of the other expression. 6350 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6351 return QualType(); 6352 6353 // Otherwise, the operands are not compatible. 6354 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6355 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6356 << RHS.get()->getSourceRange(); 6357 return QualType(); 6358 } 6359 6360 /// FindCompositeObjCPointerType - Helper method to find composite type of 6361 /// two objective-c pointer types of the two input expressions. 6362 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6363 SourceLocation QuestionLoc) { 6364 QualType LHSTy = LHS.get()->getType(); 6365 QualType RHSTy = RHS.get()->getType(); 6366 6367 // Handle things like Class and struct objc_class*. Here we case the result 6368 // to the pseudo-builtin, because that will be implicitly cast back to the 6369 // redefinition type if an attempt is made to access its fields. 6370 if (LHSTy->isObjCClassType() && 6371 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6372 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6373 return LHSTy; 6374 } 6375 if (RHSTy->isObjCClassType() && 6376 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6377 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6378 return RHSTy; 6379 } 6380 // And the same for struct objc_object* / id 6381 if (LHSTy->isObjCIdType() && 6382 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6383 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6384 return LHSTy; 6385 } 6386 if (RHSTy->isObjCIdType() && 6387 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6388 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6389 return RHSTy; 6390 } 6391 // And the same for struct objc_selector* / SEL 6392 if (Context.isObjCSelType(LHSTy) && 6393 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6394 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6395 return LHSTy; 6396 } 6397 if (Context.isObjCSelType(RHSTy) && 6398 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6399 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6400 return RHSTy; 6401 } 6402 // Check constraints for Objective-C object pointers types. 6403 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6404 6405 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6406 // Two identical object pointer types are always compatible. 6407 return LHSTy; 6408 } 6409 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6410 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6411 QualType compositeType = LHSTy; 6412 6413 // If both operands are interfaces and either operand can be 6414 // assigned to the other, use that type as the composite 6415 // type. This allows 6416 // xxx ? (A*) a : (B*) b 6417 // where B is a subclass of A. 6418 // 6419 // Additionally, as for assignment, if either type is 'id' 6420 // allow silent coercion. Finally, if the types are 6421 // incompatible then make sure to use 'id' as the composite 6422 // type so the result is acceptable for sending messages to. 6423 6424 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6425 // It could return the composite type. 6426 if (!(compositeType = 6427 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6428 // Nothing more to do. 6429 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6430 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6431 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6432 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6433 } else if ((LHSTy->isObjCQualifiedIdType() || 6434 RHSTy->isObjCQualifiedIdType()) && 6435 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6436 // Need to handle "id<xx>" explicitly. 6437 // GCC allows qualified id and any Objective-C type to devolve to 6438 // id. Currently localizing to here until clear this should be 6439 // part of ObjCQualifiedIdTypesAreCompatible. 6440 compositeType = Context.getObjCIdType(); 6441 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6442 compositeType = Context.getObjCIdType(); 6443 } else { 6444 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6445 << LHSTy << RHSTy 6446 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6447 QualType incompatTy = Context.getObjCIdType(); 6448 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6449 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6450 return incompatTy; 6451 } 6452 // The object pointer types are compatible. 6453 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6454 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6455 return compositeType; 6456 } 6457 // Check Objective-C object pointer types and 'void *' 6458 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6459 if (getLangOpts().ObjCAutoRefCount) { 6460 // ARC forbids the implicit conversion of object pointers to 'void *', 6461 // so these types are not compatible. 6462 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6463 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6464 LHS = RHS = true; 6465 return QualType(); 6466 } 6467 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6468 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6469 QualType destPointee 6470 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6471 QualType destType = Context.getPointerType(destPointee); 6472 // Add qualifiers if necessary. 6473 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6474 // Promote to void*. 6475 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6476 return destType; 6477 } 6478 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6479 if (getLangOpts().ObjCAutoRefCount) { 6480 // ARC forbids the implicit conversion of object pointers to 'void *', 6481 // so these types are not compatible. 6482 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6483 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6484 LHS = RHS = true; 6485 return QualType(); 6486 } 6487 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6488 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6489 QualType destPointee 6490 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6491 QualType destType = Context.getPointerType(destPointee); 6492 // Add qualifiers if necessary. 6493 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6494 // Promote to void*. 6495 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6496 return destType; 6497 } 6498 return QualType(); 6499 } 6500 6501 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6502 /// ParenRange in parentheses. 6503 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6504 const PartialDiagnostic &Note, 6505 SourceRange ParenRange) { 6506 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6507 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6508 EndLoc.isValid()) { 6509 Self.Diag(Loc, Note) 6510 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6511 << FixItHint::CreateInsertion(EndLoc, ")"); 6512 } else { 6513 // We can't display the parentheses, so just show the bare note. 6514 Self.Diag(Loc, Note) << ParenRange; 6515 } 6516 } 6517 6518 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6519 return Opc >= BO_Mul && Opc <= BO_Shr; 6520 } 6521 6522 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6523 /// expression, either using a built-in or overloaded operator, 6524 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6525 /// expression. 6526 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6527 Expr **RHSExprs) { 6528 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6529 E = E->IgnoreImpCasts(); 6530 E = E->IgnoreConversionOperator(); 6531 E = E->IgnoreImpCasts(); 6532 6533 // Built-in binary operator. 6534 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6535 if (IsArithmeticOp(OP->getOpcode())) { 6536 *Opcode = OP->getOpcode(); 6537 *RHSExprs = OP->getRHS(); 6538 return true; 6539 } 6540 } 6541 6542 // Overloaded operator. 6543 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6544 if (Call->getNumArgs() != 2) 6545 return false; 6546 6547 // Make sure this is really a binary operator that is safe to pass into 6548 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6549 OverloadedOperatorKind OO = Call->getOperator(); 6550 if (OO < OO_Plus || OO > OO_Arrow || 6551 OO == OO_PlusPlus || OO == OO_MinusMinus) 6552 return false; 6553 6554 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6555 if (IsArithmeticOp(OpKind)) { 6556 *Opcode = OpKind; 6557 *RHSExprs = Call->getArg(1); 6558 return true; 6559 } 6560 } 6561 6562 return false; 6563 } 6564 6565 static bool IsLogicOp(BinaryOperatorKind Opc) { 6566 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 6567 } 6568 6569 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6570 /// or is a logical expression such as (x==y) which has int type, but is 6571 /// commonly interpreted as boolean. 6572 static bool ExprLooksBoolean(Expr *E) { 6573 E = E->IgnoreParenImpCasts(); 6574 6575 if (E->getType()->isBooleanType()) 6576 return true; 6577 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6578 return IsLogicOp(OP->getOpcode()); 6579 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6580 return OP->getOpcode() == UO_LNot; 6581 if (E->getType()->isPointerType()) 6582 return true; 6583 6584 return false; 6585 } 6586 6587 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6588 /// and binary operator are mixed in a way that suggests the programmer assumed 6589 /// the conditional operator has higher precedence, for example: 6590 /// "int x = a + someBinaryCondition ? 1 : 2". 6591 static void DiagnoseConditionalPrecedence(Sema &Self, 6592 SourceLocation OpLoc, 6593 Expr *Condition, 6594 Expr *LHSExpr, 6595 Expr *RHSExpr) { 6596 BinaryOperatorKind CondOpcode; 6597 Expr *CondRHS; 6598 6599 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6600 return; 6601 if (!ExprLooksBoolean(CondRHS)) 6602 return; 6603 6604 // The condition is an arithmetic binary expression, with a right- 6605 // hand side that looks boolean, so warn. 6606 6607 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6608 << Condition->getSourceRange() 6609 << BinaryOperator::getOpcodeStr(CondOpcode); 6610 6611 SuggestParentheses(Self, OpLoc, 6612 Self.PDiag(diag::note_precedence_silence) 6613 << BinaryOperator::getOpcodeStr(CondOpcode), 6614 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6615 6616 SuggestParentheses(Self, OpLoc, 6617 Self.PDiag(diag::note_precedence_conditional_first), 6618 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6619 } 6620 6621 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6622 /// in the case of a the GNU conditional expr extension. 6623 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6624 SourceLocation ColonLoc, 6625 Expr *CondExpr, Expr *LHSExpr, 6626 Expr *RHSExpr) { 6627 if (!getLangOpts().CPlusPlus) { 6628 // C cannot handle TypoExpr nodes in the condition because it 6629 // doesn't handle dependent types properly, so make sure any TypoExprs have 6630 // been dealt with before checking the operands. 6631 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6632 if (!CondResult.isUsable()) return ExprError(); 6633 CondExpr = CondResult.get(); 6634 } 6635 6636 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6637 // was the condition. 6638 OpaqueValueExpr *opaqueValue = nullptr; 6639 Expr *commonExpr = nullptr; 6640 if (!LHSExpr) { 6641 commonExpr = CondExpr; 6642 // Lower out placeholder types first. This is important so that we don't 6643 // try to capture a placeholder. This happens in few cases in C++; such 6644 // as Objective-C++'s dictionary subscripting syntax. 6645 if (commonExpr->hasPlaceholderType()) { 6646 ExprResult result = CheckPlaceholderExpr(commonExpr); 6647 if (!result.isUsable()) return ExprError(); 6648 commonExpr = result.get(); 6649 } 6650 // We usually want to apply unary conversions *before* saving, except 6651 // in the special case of a C++ l-value conditional. 6652 if (!(getLangOpts().CPlusPlus 6653 && !commonExpr->isTypeDependent() 6654 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6655 && commonExpr->isGLValue() 6656 && commonExpr->isOrdinaryOrBitFieldObject() 6657 && RHSExpr->isOrdinaryOrBitFieldObject() 6658 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6659 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6660 if (commonRes.isInvalid()) 6661 return ExprError(); 6662 commonExpr = commonRes.get(); 6663 } 6664 6665 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6666 commonExpr->getType(), 6667 commonExpr->getValueKind(), 6668 commonExpr->getObjectKind(), 6669 commonExpr); 6670 LHSExpr = CondExpr = opaqueValue; 6671 } 6672 6673 ExprValueKind VK = VK_RValue; 6674 ExprObjectKind OK = OK_Ordinary; 6675 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6676 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6677 VK, OK, QuestionLoc); 6678 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6679 RHS.isInvalid()) 6680 return ExprError(); 6681 6682 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6683 RHS.get()); 6684 6685 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6686 6687 if (!commonExpr) 6688 return new (Context) 6689 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6690 RHS.get(), result, VK, OK); 6691 6692 return new (Context) BinaryConditionalOperator( 6693 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6694 ColonLoc, result, VK, OK); 6695 } 6696 6697 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6698 // being closely modeled after the C99 spec:-). The odd characteristic of this 6699 // routine is it effectively iqnores the qualifiers on the top level pointee. 6700 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6701 // FIXME: add a couple examples in this comment. 6702 static Sema::AssignConvertType 6703 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6704 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6705 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6706 6707 // get the "pointed to" type (ignoring qualifiers at the top level) 6708 const Type *lhptee, *rhptee; 6709 Qualifiers lhq, rhq; 6710 std::tie(lhptee, lhq) = 6711 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6712 std::tie(rhptee, rhq) = 6713 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6714 6715 Sema::AssignConvertType ConvTy = Sema::Compatible; 6716 6717 // C99 6.5.16.1p1: This following citation is common to constraints 6718 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6719 // qualifiers of the type *pointed to* by the right; 6720 6721 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6722 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6723 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6724 // Ignore lifetime for further calculation. 6725 lhq.removeObjCLifetime(); 6726 rhq.removeObjCLifetime(); 6727 } 6728 6729 if (!lhq.compatiblyIncludes(rhq)) { 6730 // Treat address-space mismatches as fatal. TODO: address subspaces 6731 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6732 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6733 6734 // It's okay to add or remove GC or lifetime qualifiers when converting to 6735 // and from void*. 6736 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6737 .compatiblyIncludes( 6738 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6739 && (lhptee->isVoidType() || rhptee->isVoidType())) 6740 ; // keep old 6741 6742 // Treat lifetime mismatches as fatal. 6743 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6744 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6745 6746 // For GCC compatibility, other qualifier mismatches are treated 6747 // as still compatible in C. 6748 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6749 } 6750 6751 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6752 // incomplete type and the other is a pointer to a qualified or unqualified 6753 // version of void... 6754 if (lhptee->isVoidType()) { 6755 if (rhptee->isIncompleteOrObjectType()) 6756 return ConvTy; 6757 6758 // As an extension, we allow cast to/from void* to function pointer. 6759 assert(rhptee->isFunctionType()); 6760 return Sema::FunctionVoidPointer; 6761 } 6762 6763 if (rhptee->isVoidType()) { 6764 if (lhptee->isIncompleteOrObjectType()) 6765 return ConvTy; 6766 6767 // As an extension, we allow cast to/from void* to function pointer. 6768 assert(lhptee->isFunctionType()); 6769 return Sema::FunctionVoidPointer; 6770 } 6771 6772 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6773 // unqualified versions of compatible types, ... 6774 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6775 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6776 // Check if the pointee types are compatible ignoring the sign. 6777 // We explicitly check for char so that we catch "char" vs 6778 // "unsigned char" on systems where "char" is unsigned. 6779 if (lhptee->isCharType()) 6780 ltrans = S.Context.UnsignedCharTy; 6781 else if (lhptee->hasSignedIntegerRepresentation()) 6782 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6783 6784 if (rhptee->isCharType()) 6785 rtrans = S.Context.UnsignedCharTy; 6786 else if (rhptee->hasSignedIntegerRepresentation()) 6787 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6788 6789 if (ltrans == rtrans) { 6790 // Types are compatible ignoring the sign. Qualifier incompatibility 6791 // takes priority over sign incompatibility because the sign 6792 // warning can be disabled. 6793 if (ConvTy != Sema::Compatible) 6794 return ConvTy; 6795 6796 return Sema::IncompatiblePointerSign; 6797 } 6798 6799 // If we are a multi-level pointer, it's possible that our issue is simply 6800 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6801 // the eventual target type is the same and the pointers have the same 6802 // level of indirection, this must be the issue. 6803 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6804 do { 6805 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6806 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6807 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6808 6809 if (lhptee == rhptee) 6810 return Sema::IncompatibleNestedPointerQualifiers; 6811 } 6812 6813 // General pointer incompatibility takes priority over qualifiers. 6814 return Sema::IncompatiblePointer; 6815 } 6816 if (!S.getLangOpts().CPlusPlus && 6817 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6818 return Sema::IncompatiblePointer; 6819 return ConvTy; 6820 } 6821 6822 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6823 /// block pointer types are compatible or whether a block and normal pointer 6824 /// are compatible. It is more restrict than comparing two function pointer 6825 // types. 6826 static Sema::AssignConvertType 6827 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6828 QualType RHSType) { 6829 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6830 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6831 6832 QualType lhptee, rhptee; 6833 6834 // get the "pointed to" type (ignoring qualifiers at the top level) 6835 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6836 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6837 6838 // In C++, the types have to match exactly. 6839 if (S.getLangOpts().CPlusPlus) 6840 return Sema::IncompatibleBlockPointer; 6841 6842 Sema::AssignConvertType ConvTy = Sema::Compatible; 6843 6844 // For blocks we enforce that qualifiers are identical. 6845 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6846 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6847 6848 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6849 return Sema::IncompatibleBlockPointer; 6850 6851 return ConvTy; 6852 } 6853 6854 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6855 /// for assignment compatibility. 6856 static Sema::AssignConvertType 6857 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6858 QualType RHSType) { 6859 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6860 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6861 6862 if (LHSType->isObjCBuiltinType()) { 6863 // Class is not compatible with ObjC object pointers. 6864 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6865 !RHSType->isObjCQualifiedClassType()) 6866 return Sema::IncompatiblePointer; 6867 return Sema::Compatible; 6868 } 6869 if (RHSType->isObjCBuiltinType()) { 6870 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6871 !LHSType->isObjCQualifiedClassType()) 6872 return Sema::IncompatiblePointer; 6873 return Sema::Compatible; 6874 } 6875 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6876 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6877 6878 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6879 // make an exception for id<P> 6880 !LHSType->isObjCQualifiedIdType()) 6881 return Sema::CompatiblePointerDiscardsQualifiers; 6882 6883 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6884 return Sema::Compatible; 6885 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6886 return Sema::IncompatibleObjCQualifiedId; 6887 return Sema::IncompatiblePointer; 6888 } 6889 6890 Sema::AssignConvertType 6891 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6892 QualType LHSType, QualType RHSType) { 6893 // Fake up an opaque expression. We don't actually care about what 6894 // cast operations are required, so if CheckAssignmentConstraints 6895 // adds casts to this they'll be wasted, but fortunately that doesn't 6896 // usually happen on valid code. 6897 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6898 ExprResult RHSPtr = &RHSExpr; 6899 CastKind K = CK_Invalid; 6900 6901 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 6902 } 6903 6904 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6905 /// has code to accommodate several GCC extensions when type checking 6906 /// pointers. Here are some objectionable examples that GCC considers warnings: 6907 /// 6908 /// int a, *pint; 6909 /// short *pshort; 6910 /// struct foo *pfoo; 6911 /// 6912 /// pint = pshort; // warning: assignment from incompatible pointer type 6913 /// a = pint; // warning: assignment makes integer from pointer without a cast 6914 /// pint = a; // warning: assignment makes pointer from integer without a cast 6915 /// pint = pfoo; // warning: assignment from incompatible pointer type 6916 /// 6917 /// As a result, the code for dealing with pointers is more complex than the 6918 /// C99 spec dictates. 6919 /// 6920 /// Sets 'Kind' for any result kind except Incompatible. 6921 Sema::AssignConvertType 6922 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6923 CastKind &Kind, bool ConvertRHS) { 6924 QualType RHSType = RHS.get()->getType(); 6925 QualType OrigLHSType = LHSType; 6926 6927 // Get canonical types. We're not formatting these types, just comparing 6928 // them. 6929 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6930 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6931 6932 // Common case: no conversion required. 6933 if (LHSType == RHSType) { 6934 Kind = CK_NoOp; 6935 return Compatible; 6936 } 6937 6938 // If we have an atomic type, try a non-atomic assignment, then just add an 6939 // atomic qualification step. 6940 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6941 Sema::AssignConvertType result = 6942 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6943 if (result != Compatible) 6944 return result; 6945 if (Kind != CK_NoOp && ConvertRHS) 6946 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 6947 Kind = CK_NonAtomicToAtomic; 6948 return Compatible; 6949 } 6950 6951 // If the left-hand side is a reference type, then we are in a 6952 // (rare!) case where we've allowed the use of references in C, 6953 // e.g., as a parameter type in a built-in function. In this case, 6954 // just make sure that the type referenced is compatible with the 6955 // right-hand side type. The caller is responsible for adjusting 6956 // LHSType so that the resulting expression does not have reference 6957 // type. 6958 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6959 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6960 Kind = CK_LValueBitCast; 6961 return Compatible; 6962 } 6963 return Incompatible; 6964 } 6965 6966 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6967 // to the same ExtVector type. 6968 if (LHSType->isExtVectorType()) { 6969 if (RHSType->isExtVectorType()) 6970 return Incompatible; 6971 if (RHSType->isArithmeticType()) { 6972 // CK_VectorSplat does T -> vector T, so first cast to the 6973 // element type. 6974 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6975 if (elType != RHSType && ConvertRHS) { 6976 Kind = PrepareScalarCast(RHS, elType); 6977 RHS = ImpCastExprToType(RHS.get(), elType, Kind); 6978 } 6979 Kind = CK_VectorSplat; 6980 return Compatible; 6981 } 6982 } 6983 6984 // Conversions to or from vector type. 6985 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6986 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6987 // Allow assignments of an AltiVec vector type to an equivalent GCC 6988 // vector type and vice versa 6989 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6990 Kind = CK_BitCast; 6991 return Compatible; 6992 } 6993 6994 // If we are allowing lax vector conversions, and LHS and RHS are both 6995 // vectors, the total size only needs to be the same. This is a bitcast; 6996 // no bits are changed but the result type is different. 6997 if (isLaxVectorConversion(RHSType, LHSType)) { 6998 Kind = CK_BitCast; 6999 return IncompatibleVectors; 7000 } 7001 } 7002 return Incompatible; 7003 } 7004 7005 // Arithmetic conversions. 7006 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7007 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7008 if (ConvertRHS) 7009 Kind = PrepareScalarCast(RHS, LHSType); 7010 return Compatible; 7011 } 7012 7013 // Conversions to normal pointers. 7014 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7015 // U* -> T* 7016 if (isa<PointerType>(RHSType)) { 7017 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7018 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7019 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7020 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7021 } 7022 7023 // int -> T* 7024 if (RHSType->isIntegerType()) { 7025 Kind = CK_IntegralToPointer; // FIXME: null? 7026 return IntToPointer; 7027 } 7028 7029 // C pointers are not compatible with ObjC object pointers, 7030 // with two exceptions: 7031 if (isa<ObjCObjectPointerType>(RHSType)) { 7032 // - conversions to void* 7033 if (LHSPointer->getPointeeType()->isVoidType()) { 7034 Kind = CK_BitCast; 7035 return Compatible; 7036 } 7037 7038 // - conversions from 'Class' to the redefinition type 7039 if (RHSType->isObjCClassType() && 7040 Context.hasSameType(LHSType, 7041 Context.getObjCClassRedefinitionType())) { 7042 Kind = CK_BitCast; 7043 return Compatible; 7044 } 7045 7046 Kind = CK_BitCast; 7047 return IncompatiblePointer; 7048 } 7049 7050 // U^ -> void* 7051 if (RHSType->getAs<BlockPointerType>()) { 7052 if (LHSPointer->getPointeeType()->isVoidType()) { 7053 Kind = CK_BitCast; 7054 return Compatible; 7055 } 7056 } 7057 7058 return Incompatible; 7059 } 7060 7061 // Conversions to block pointers. 7062 if (isa<BlockPointerType>(LHSType)) { 7063 // U^ -> T^ 7064 if (RHSType->isBlockPointerType()) { 7065 Kind = CK_BitCast; 7066 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7067 } 7068 7069 // int or null -> T^ 7070 if (RHSType->isIntegerType()) { 7071 Kind = CK_IntegralToPointer; // FIXME: null 7072 return IntToBlockPointer; 7073 } 7074 7075 // id -> T^ 7076 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7077 Kind = CK_AnyPointerToBlockPointerCast; 7078 return Compatible; 7079 } 7080 7081 // void* -> T^ 7082 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7083 if (RHSPT->getPointeeType()->isVoidType()) { 7084 Kind = CK_AnyPointerToBlockPointerCast; 7085 return Compatible; 7086 } 7087 7088 return Incompatible; 7089 } 7090 7091 // Conversions to Objective-C pointers. 7092 if (isa<ObjCObjectPointerType>(LHSType)) { 7093 // A* -> B* 7094 if (RHSType->isObjCObjectPointerType()) { 7095 Kind = CK_BitCast; 7096 Sema::AssignConvertType result = 7097 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7098 if (getLangOpts().ObjCAutoRefCount && 7099 result == Compatible && 7100 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7101 result = IncompatibleObjCWeakRef; 7102 return result; 7103 } 7104 7105 // int or null -> A* 7106 if (RHSType->isIntegerType()) { 7107 Kind = CK_IntegralToPointer; // FIXME: null 7108 return IntToPointer; 7109 } 7110 7111 // In general, C pointers are not compatible with ObjC object pointers, 7112 // with two exceptions: 7113 if (isa<PointerType>(RHSType)) { 7114 Kind = CK_CPointerToObjCPointerCast; 7115 7116 // - conversions from 'void*' 7117 if (RHSType->isVoidPointerType()) { 7118 return Compatible; 7119 } 7120 7121 // - conversions to 'Class' from its redefinition type 7122 if (LHSType->isObjCClassType() && 7123 Context.hasSameType(RHSType, 7124 Context.getObjCClassRedefinitionType())) { 7125 return Compatible; 7126 } 7127 7128 return IncompatiblePointer; 7129 } 7130 7131 // Only under strict condition T^ is compatible with an Objective-C pointer. 7132 if (RHSType->isBlockPointerType() && 7133 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7134 if (ConvertRHS) 7135 maybeExtendBlockObject(RHS); 7136 Kind = CK_BlockPointerToObjCPointerCast; 7137 return Compatible; 7138 } 7139 7140 return Incompatible; 7141 } 7142 7143 // Conversions from pointers that are not covered by the above. 7144 if (isa<PointerType>(RHSType)) { 7145 // T* -> _Bool 7146 if (LHSType == Context.BoolTy) { 7147 Kind = CK_PointerToBoolean; 7148 return Compatible; 7149 } 7150 7151 // T* -> int 7152 if (LHSType->isIntegerType()) { 7153 Kind = CK_PointerToIntegral; 7154 return PointerToInt; 7155 } 7156 7157 return Incompatible; 7158 } 7159 7160 // Conversions from Objective-C pointers that are not covered by the above. 7161 if (isa<ObjCObjectPointerType>(RHSType)) { 7162 // T* -> _Bool 7163 if (LHSType == Context.BoolTy) { 7164 Kind = CK_PointerToBoolean; 7165 return Compatible; 7166 } 7167 7168 // T* -> int 7169 if (LHSType->isIntegerType()) { 7170 Kind = CK_PointerToIntegral; 7171 return PointerToInt; 7172 } 7173 7174 return Incompatible; 7175 } 7176 7177 // struct A -> struct B 7178 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7179 if (Context.typesAreCompatible(LHSType, RHSType)) { 7180 Kind = CK_NoOp; 7181 return Compatible; 7182 } 7183 } 7184 7185 return Incompatible; 7186 } 7187 7188 /// \brief Constructs a transparent union from an expression that is 7189 /// used to initialize the transparent union. 7190 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7191 ExprResult &EResult, QualType UnionType, 7192 FieldDecl *Field) { 7193 // Build an initializer list that designates the appropriate member 7194 // of the transparent union. 7195 Expr *E = EResult.get(); 7196 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7197 E, SourceLocation()); 7198 Initializer->setType(UnionType); 7199 Initializer->setInitializedFieldInUnion(Field); 7200 7201 // Build a compound literal constructing a value of the transparent 7202 // union type from this initializer list. 7203 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7204 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7205 VK_RValue, Initializer, false); 7206 } 7207 7208 Sema::AssignConvertType 7209 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7210 ExprResult &RHS) { 7211 QualType RHSType = RHS.get()->getType(); 7212 7213 // If the ArgType is a Union type, we want to handle a potential 7214 // transparent_union GCC extension. 7215 const RecordType *UT = ArgType->getAsUnionType(); 7216 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7217 return Incompatible; 7218 7219 // The field to initialize within the transparent union. 7220 RecordDecl *UD = UT->getDecl(); 7221 FieldDecl *InitField = nullptr; 7222 // It's compatible if the expression matches any of the fields. 7223 for (auto *it : UD->fields()) { 7224 if (it->getType()->isPointerType()) { 7225 // If the transparent union contains a pointer type, we allow: 7226 // 1) void pointer 7227 // 2) null pointer constant 7228 if (RHSType->isPointerType()) 7229 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7230 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7231 InitField = it; 7232 break; 7233 } 7234 7235 if (RHS.get()->isNullPointerConstant(Context, 7236 Expr::NPC_ValueDependentIsNull)) { 7237 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7238 CK_NullToPointer); 7239 InitField = it; 7240 break; 7241 } 7242 } 7243 7244 CastKind Kind = CK_Invalid; 7245 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7246 == Compatible) { 7247 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7248 InitField = it; 7249 break; 7250 } 7251 } 7252 7253 if (!InitField) 7254 return Incompatible; 7255 7256 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7257 return Compatible; 7258 } 7259 7260 Sema::AssignConvertType 7261 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7262 bool Diagnose, 7263 bool DiagnoseCFAudited, 7264 bool ConvertRHS) { 7265 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7266 // we can't avoid *all* modifications at the moment, so we need some somewhere 7267 // to put the updated value. 7268 ExprResult LocalRHS = CallerRHS; 7269 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7270 7271 if (getLangOpts().CPlusPlus) { 7272 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7273 // C++ 5.17p3: If the left operand is not of class type, the 7274 // expression is implicitly converted (C++ 4) to the 7275 // cv-unqualified type of the left operand. 7276 ExprResult Res; 7277 if (Diagnose) { 7278 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7279 AA_Assigning); 7280 } else { 7281 ImplicitConversionSequence ICS = 7282 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7283 /*SuppressUserConversions=*/false, 7284 /*AllowExplicit=*/false, 7285 /*InOverloadResolution=*/false, 7286 /*CStyle=*/false, 7287 /*AllowObjCWritebackConversion=*/false); 7288 if (ICS.isFailure()) 7289 return Incompatible; 7290 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7291 ICS, AA_Assigning); 7292 } 7293 if (Res.isInvalid()) 7294 return Incompatible; 7295 Sema::AssignConvertType result = Compatible; 7296 if (getLangOpts().ObjCAutoRefCount && 7297 !CheckObjCARCUnavailableWeakConversion(LHSType, 7298 RHS.get()->getType())) 7299 result = IncompatibleObjCWeakRef; 7300 RHS = Res; 7301 return result; 7302 } 7303 7304 // FIXME: Currently, we fall through and treat C++ classes like C 7305 // structures. 7306 // FIXME: We also fall through for atomics; not sure what should 7307 // happen there, though. 7308 } else if (RHS.get()->getType() == Context.OverloadTy) { 7309 // As a set of extensions to C, we support overloading on functions. These 7310 // functions need to be resolved here. 7311 DeclAccessPair DAP; 7312 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7313 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7314 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7315 else 7316 return Incompatible; 7317 } 7318 7319 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7320 // a null pointer constant. 7321 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7322 LHSType->isBlockPointerType()) && 7323 RHS.get()->isNullPointerConstant(Context, 7324 Expr::NPC_ValueDependentIsNull)) { 7325 CastKind Kind; 7326 CXXCastPath Path; 7327 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 7328 if (ConvertRHS) 7329 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7330 return Compatible; 7331 } 7332 7333 // This check seems unnatural, however it is necessary to ensure the proper 7334 // conversion of functions/arrays. If the conversion were done for all 7335 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7336 // expressions that suppress this implicit conversion (&, sizeof). 7337 // 7338 // Suppress this for references: C++ 8.5.3p5. 7339 if (!LHSType->isReferenceType()) { 7340 // FIXME: We potentially allocate here even if ConvertRHS is false. 7341 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7342 if (RHS.isInvalid()) 7343 return Incompatible; 7344 } 7345 7346 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7347 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) { 7348 ObjCProtocolDecl *PDecl = OPE->getProtocol(); 7349 if (PDecl && !PDecl->hasDefinition()) { 7350 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7351 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7352 } 7353 } 7354 7355 CastKind Kind = CK_Invalid; 7356 Sema::AssignConvertType result = 7357 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7358 7359 // C99 6.5.16.1p2: The value of the right operand is converted to the 7360 // type of the assignment expression. 7361 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7362 // so that we can use references in built-in functions even in C. 7363 // The getNonReferenceType() call makes sure that the resulting expression 7364 // does not have reference type. 7365 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7366 QualType Ty = LHSType.getNonLValueExprType(Context); 7367 Expr *E = RHS.get(); 7368 if (getLangOpts().ObjCAutoRefCount) 7369 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7370 DiagnoseCFAudited); 7371 if (getLangOpts().ObjC1 && 7372 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 7373 LHSType, E->getType(), E) || 7374 ConversionToObjCStringLiteralCheck(LHSType, E))) { 7375 RHS = E; 7376 return Compatible; 7377 } 7378 7379 if (ConvertRHS) 7380 RHS = ImpCastExprToType(E, Ty, Kind); 7381 } 7382 return result; 7383 } 7384 7385 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7386 ExprResult &RHS) { 7387 Diag(Loc, diag::err_typecheck_invalid_operands) 7388 << LHS.get()->getType() << RHS.get()->getType() 7389 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7390 return QualType(); 7391 } 7392 7393 /// Try to convert a value of non-vector type to a vector type by converting 7394 /// the type to the element type of the vector and then performing a splat. 7395 /// If the language is OpenCL, we only use conversions that promote scalar 7396 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7397 /// for float->int. 7398 /// 7399 /// \param scalar - if non-null, actually perform the conversions 7400 /// \return true if the operation fails (but without diagnosing the failure) 7401 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7402 QualType scalarTy, 7403 QualType vectorEltTy, 7404 QualType vectorTy) { 7405 // The conversion to apply to the scalar before splatting it, 7406 // if necessary. 7407 CastKind scalarCast = CK_Invalid; 7408 7409 if (vectorEltTy->isIntegralType(S.Context)) { 7410 if (!scalarTy->isIntegralType(S.Context)) 7411 return true; 7412 if (S.getLangOpts().OpenCL && 7413 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7414 return true; 7415 scalarCast = CK_IntegralCast; 7416 } else if (vectorEltTy->isRealFloatingType()) { 7417 if (scalarTy->isRealFloatingType()) { 7418 if (S.getLangOpts().OpenCL && 7419 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7420 return true; 7421 scalarCast = CK_FloatingCast; 7422 } 7423 else if (scalarTy->isIntegralType(S.Context)) 7424 scalarCast = CK_IntegralToFloating; 7425 else 7426 return true; 7427 } else { 7428 return true; 7429 } 7430 7431 // Adjust scalar if desired. 7432 if (scalar) { 7433 if (scalarCast != CK_Invalid) 7434 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7435 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7436 } 7437 return false; 7438 } 7439 7440 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7441 SourceLocation Loc, bool IsCompAssign, 7442 bool AllowBothBool, 7443 bool AllowBoolConversions) { 7444 if (!IsCompAssign) { 7445 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7446 if (LHS.isInvalid()) 7447 return QualType(); 7448 } 7449 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7450 if (RHS.isInvalid()) 7451 return QualType(); 7452 7453 // For conversion purposes, we ignore any qualifiers. 7454 // For example, "const float" and "float" are equivalent. 7455 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7456 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7457 7458 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7459 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7460 assert(LHSVecType || RHSVecType); 7461 7462 // AltiVec-style "vector bool op vector bool" combinations are allowed 7463 // for some operators but not others. 7464 if (!AllowBothBool && 7465 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7466 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7467 return InvalidOperands(Loc, LHS, RHS); 7468 7469 // If the vector types are identical, return. 7470 if (Context.hasSameType(LHSType, RHSType)) 7471 return LHSType; 7472 7473 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7474 if (LHSVecType && RHSVecType && 7475 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7476 if (isa<ExtVectorType>(LHSVecType)) { 7477 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7478 return LHSType; 7479 } 7480 7481 if (!IsCompAssign) 7482 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7483 return RHSType; 7484 } 7485 7486 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7487 // can be mixed, with the result being the non-bool type. The non-bool 7488 // operand must have integer element type. 7489 if (AllowBoolConversions && LHSVecType && RHSVecType && 7490 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7491 (Context.getTypeSize(LHSVecType->getElementType()) == 7492 Context.getTypeSize(RHSVecType->getElementType()))) { 7493 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7494 LHSVecType->getElementType()->isIntegerType() && 7495 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7496 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7497 return LHSType; 7498 } 7499 if (!IsCompAssign && 7500 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7501 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7502 RHSVecType->getElementType()->isIntegerType()) { 7503 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7504 return RHSType; 7505 } 7506 } 7507 7508 // If there's an ext-vector type and a scalar, try to convert the scalar to 7509 // the vector element type and splat. 7510 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7511 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7512 LHSVecType->getElementType(), LHSType)) 7513 return LHSType; 7514 } 7515 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7516 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7517 LHSType, RHSVecType->getElementType(), 7518 RHSType)) 7519 return RHSType; 7520 } 7521 7522 // If we're allowing lax vector conversions, only the total (data) size 7523 // needs to be the same. 7524 // FIXME: Should we really be allowing this? 7525 // FIXME: We really just pick the LHS type arbitrarily? 7526 if (isLaxVectorConversion(RHSType, LHSType)) { 7527 QualType resultType = LHSType; 7528 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7529 return resultType; 7530 } 7531 7532 // Okay, the expression is invalid. 7533 7534 // If there's a non-vector, non-real operand, diagnose that. 7535 if ((!RHSVecType && !RHSType->isRealType()) || 7536 (!LHSVecType && !LHSType->isRealType())) { 7537 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7538 << LHSType << RHSType 7539 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7540 return QualType(); 7541 } 7542 7543 // OpenCL V1.1 6.2.6.p1: 7544 // If the operands are of more than one vector type, then an error shall 7545 // occur. Implicit conversions between vector types are not permitted, per 7546 // section 6.2.1. 7547 if (getLangOpts().OpenCL && 7548 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7549 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7550 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7551 << RHSType; 7552 return QualType(); 7553 } 7554 7555 // Otherwise, use the generic diagnostic. 7556 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7557 << LHSType << RHSType 7558 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7559 return QualType(); 7560 } 7561 7562 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7563 // expression. These are mainly cases where the null pointer is used as an 7564 // integer instead of a pointer. 7565 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7566 SourceLocation Loc, bool IsCompare) { 7567 // The canonical way to check for a GNU null is with isNullPointerConstant, 7568 // but we use a bit of a hack here for speed; this is a relatively 7569 // hot path, and isNullPointerConstant is slow. 7570 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7571 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7572 7573 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7574 7575 // Avoid analyzing cases where the result will either be invalid (and 7576 // diagnosed as such) or entirely valid and not something to warn about. 7577 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7578 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7579 return; 7580 7581 // Comparison operations would not make sense with a null pointer no matter 7582 // what the other expression is. 7583 if (!IsCompare) { 7584 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7585 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7586 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7587 return; 7588 } 7589 7590 // The rest of the operations only make sense with a null pointer 7591 // if the other expression is a pointer. 7592 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7593 NonNullType->canDecayToPointerType()) 7594 return; 7595 7596 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7597 << LHSNull /* LHS is NULL */ << NonNullType 7598 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7599 } 7600 7601 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7602 ExprResult &RHS, 7603 SourceLocation Loc, bool IsDiv) { 7604 // Check for division/remainder by zero. 7605 llvm::APSInt RHSValue; 7606 if (!RHS.get()->isValueDependent() && 7607 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7608 S.DiagRuntimeBehavior(Loc, RHS.get(), 7609 S.PDiag(diag::warn_remainder_division_by_zero) 7610 << IsDiv << RHS.get()->getSourceRange()); 7611 } 7612 7613 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7614 SourceLocation Loc, 7615 bool IsCompAssign, bool IsDiv) { 7616 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7617 7618 if (LHS.get()->getType()->isVectorType() || 7619 RHS.get()->getType()->isVectorType()) 7620 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7621 /*AllowBothBool*/getLangOpts().AltiVec, 7622 /*AllowBoolConversions*/false); 7623 7624 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7625 if (LHS.isInvalid() || RHS.isInvalid()) 7626 return QualType(); 7627 7628 7629 if (compType.isNull() || !compType->isArithmeticType()) 7630 return InvalidOperands(Loc, LHS, RHS); 7631 if (IsDiv) 7632 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7633 return compType; 7634 } 7635 7636 QualType Sema::CheckRemainderOperands( 7637 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7638 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7639 7640 if (LHS.get()->getType()->isVectorType() || 7641 RHS.get()->getType()->isVectorType()) { 7642 if (LHS.get()->getType()->hasIntegerRepresentation() && 7643 RHS.get()->getType()->hasIntegerRepresentation()) 7644 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7645 /*AllowBothBool*/getLangOpts().AltiVec, 7646 /*AllowBoolConversions*/false); 7647 return InvalidOperands(Loc, LHS, RHS); 7648 } 7649 7650 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7651 if (LHS.isInvalid() || RHS.isInvalid()) 7652 return QualType(); 7653 7654 if (compType.isNull() || !compType->isIntegerType()) 7655 return InvalidOperands(Loc, LHS, RHS); 7656 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 7657 return compType; 7658 } 7659 7660 /// \brief Diagnose invalid arithmetic on two void pointers. 7661 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7662 Expr *LHSExpr, Expr *RHSExpr) { 7663 S.Diag(Loc, S.getLangOpts().CPlusPlus 7664 ? diag::err_typecheck_pointer_arith_void_type 7665 : diag::ext_gnu_void_ptr) 7666 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7667 << RHSExpr->getSourceRange(); 7668 } 7669 7670 /// \brief Diagnose invalid arithmetic on a void pointer. 7671 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7672 Expr *Pointer) { 7673 S.Diag(Loc, S.getLangOpts().CPlusPlus 7674 ? diag::err_typecheck_pointer_arith_void_type 7675 : diag::ext_gnu_void_ptr) 7676 << 0 /* one pointer */ << Pointer->getSourceRange(); 7677 } 7678 7679 /// \brief Diagnose invalid arithmetic on two function pointers. 7680 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7681 Expr *LHS, Expr *RHS) { 7682 assert(LHS->getType()->isAnyPointerType()); 7683 assert(RHS->getType()->isAnyPointerType()); 7684 S.Diag(Loc, S.getLangOpts().CPlusPlus 7685 ? diag::err_typecheck_pointer_arith_function_type 7686 : diag::ext_gnu_ptr_func_arith) 7687 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7688 // We only show the second type if it differs from the first. 7689 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7690 RHS->getType()) 7691 << RHS->getType()->getPointeeType() 7692 << LHS->getSourceRange() << RHS->getSourceRange(); 7693 } 7694 7695 /// \brief Diagnose invalid arithmetic on a function pointer. 7696 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7697 Expr *Pointer) { 7698 assert(Pointer->getType()->isAnyPointerType()); 7699 S.Diag(Loc, S.getLangOpts().CPlusPlus 7700 ? diag::err_typecheck_pointer_arith_function_type 7701 : diag::ext_gnu_ptr_func_arith) 7702 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7703 << 0 /* one pointer, so only one type */ 7704 << Pointer->getSourceRange(); 7705 } 7706 7707 /// \brief Emit error if Operand is incomplete pointer type 7708 /// 7709 /// \returns True if pointer has incomplete type 7710 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7711 Expr *Operand) { 7712 QualType ResType = Operand->getType(); 7713 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7714 ResType = ResAtomicType->getValueType(); 7715 7716 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7717 QualType PointeeTy = ResType->getPointeeType(); 7718 return S.RequireCompleteType(Loc, PointeeTy, 7719 diag::err_typecheck_arithmetic_incomplete_type, 7720 PointeeTy, Operand->getSourceRange()); 7721 } 7722 7723 /// \brief Check the validity of an arithmetic pointer operand. 7724 /// 7725 /// If the operand has pointer type, this code will check for pointer types 7726 /// which are invalid in arithmetic operations. These will be diagnosed 7727 /// appropriately, including whether or not the use is supported as an 7728 /// extension. 7729 /// 7730 /// \returns True when the operand is valid to use (even if as an extension). 7731 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7732 Expr *Operand) { 7733 QualType ResType = Operand->getType(); 7734 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7735 ResType = ResAtomicType->getValueType(); 7736 7737 if (!ResType->isAnyPointerType()) return true; 7738 7739 QualType PointeeTy = ResType->getPointeeType(); 7740 if (PointeeTy->isVoidType()) { 7741 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7742 return !S.getLangOpts().CPlusPlus; 7743 } 7744 if (PointeeTy->isFunctionType()) { 7745 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7746 return !S.getLangOpts().CPlusPlus; 7747 } 7748 7749 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7750 7751 return true; 7752 } 7753 7754 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7755 /// operands. 7756 /// 7757 /// This routine will diagnose any invalid arithmetic on pointer operands much 7758 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7759 /// for emitting a single diagnostic even for operations where both LHS and RHS 7760 /// are (potentially problematic) pointers. 7761 /// 7762 /// \returns True when the operand is valid to use (even if as an extension). 7763 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7764 Expr *LHSExpr, Expr *RHSExpr) { 7765 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7766 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7767 if (!isLHSPointer && !isRHSPointer) return true; 7768 7769 QualType LHSPointeeTy, RHSPointeeTy; 7770 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7771 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7772 7773 // if both are pointers check if operation is valid wrt address spaces 7774 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 7775 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 7776 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 7777 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 7778 S.Diag(Loc, 7779 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7780 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 7781 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7782 return false; 7783 } 7784 } 7785 7786 // Check for arithmetic on pointers to incomplete types. 7787 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7788 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7789 if (isLHSVoidPtr || isRHSVoidPtr) { 7790 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7791 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7792 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7793 7794 return !S.getLangOpts().CPlusPlus; 7795 } 7796 7797 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7798 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7799 if (isLHSFuncPtr || isRHSFuncPtr) { 7800 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7801 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7802 RHSExpr); 7803 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7804 7805 return !S.getLangOpts().CPlusPlus; 7806 } 7807 7808 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7809 return false; 7810 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7811 return false; 7812 7813 return true; 7814 } 7815 7816 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7817 /// literal. 7818 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7819 Expr *LHSExpr, Expr *RHSExpr) { 7820 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7821 Expr* IndexExpr = RHSExpr; 7822 if (!StrExpr) { 7823 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7824 IndexExpr = LHSExpr; 7825 } 7826 7827 bool IsStringPlusInt = StrExpr && 7828 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7829 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 7830 return; 7831 7832 llvm::APSInt index; 7833 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7834 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7835 if (index.isNonNegative() && 7836 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7837 index.isUnsigned())) 7838 return; 7839 } 7840 7841 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7842 Self.Diag(OpLoc, diag::warn_string_plus_int) 7843 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7844 7845 // Only print a fixit for "str" + int, not for int + "str". 7846 if (IndexExpr == RHSExpr) { 7847 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 7848 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7849 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7850 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7851 << FixItHint::CreateInsertion(EndLoc, "]"); 7852 } else 7853 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7854 } 7855 7856 /// \brief Emit a warning when adding a char literal to a string. 7857 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7858 Expr *LHSExpr, Expr *RHSExpr) { 7859 const Expr *StringRefExpr = LHSExpr; 7860 const CharacterLiteral *CharExpr = 7861 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7862 7863 if (!CharExpr) { 7864 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7865 StringRefExpr = RHSExpr; 7866 } 7867 7868 if (!CharExpr || !StringRefExpr) 7869 return; 7870 7871 const QualType StringType = StringRefExpr->getType(); 7872 7873 // Return if not a PointerType. 7874 if (!StringType->isAnyPointerType()) 7875 return; 7876 7877 // Return if not a CharacterType. 7878 if (!StringType->getPointeeType()->isAnyCharacterType()) 7879 return; 7880 7881 ASTContext &Ctx = Self.getASTContext(); 7882 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7883 7884 const QualType CharType = CharExpr->getType(); 7885 if (!CharType->isAnyCharacterType() && 7886 CharType->isIntegerType() && 7887 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7888 Self.Diag(OpLoc, diag::warn_string_plus_char) 7889 << DiagRange << Ctx.CharTy; 7890 } else { 7891 Self.Diag(OpLoc, diag::warn_string_plus_char) 7892 << DiagRange << CharExpr->getType(); 7893 } 7894 7895 // Only print a fixit for str + char, not for char + str. 7896 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7897 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 7898 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7899 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7900 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7901 << FixItHint::CreateInsertion(EndLoc, "]"); 7902 } else { 7903 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7904 } 7905 } 7906 7907 /// \brief Emit error when two pointers are incompatible. 7908 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7909 Expr *LHSExpr, Expr *RHSExpr) { 7910 assert(LHSExpr->getType()->isAnyPointerType()); 7911 assert(RHSExpr->getType()->isAnyPointerType()); 7912 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7913 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7914 << RHSExpr->getSourceRange(); 7915 } 7916 7917 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7918 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7919 QualType* CompLHSTy) { 7920 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7921 7922 if (LHS.get()->getType()->isVectorType() || 7923 RHS.get()->getType()->isVectorType()) { 7924 QualType compType = CheckVectorOperands( 7925 LHS, RHS, Loc, CompLHSTy, 7926 /*AllowBothBool*/getLangOpts().AltiVec, 7927 /*AllowBoolConversions*/getLangOpts().ZVector); 7928 if (CompLHSTy) *CompLHSTy = compType; 7929 return compType; 7930 } 7931 7932 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7933 if (LHS.isInvalid() || RHS.isInvalid()) 7934 return QualType(); 7935 7936 // Diagnose "string literal" '+' int and string '+' "char literal". 7937 if (Opc == BO_Add) { 7938 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7939 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7940 } 7941 7942 // handle the common case first (both operands are arithmetic). 7943 if (!compType.isNull() && compType->isArithmeticType()) { 7944 if (CompLHSTy) *CompLHSTy = compType; 7945 return compType; 7946 } 7947 7948 // Type-checking. Ultimately the pointer's going to be in PExp; 7949 // note that we bias towards the LHS being the pointer. 7950 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7951 7952 bool isObjCPointer; 7953 if (PExp->getType()->isPointerType()) { 7954 isObjCPointer = false; 7955 } else if (PExp->getType()->isObjCObjectPointerType()) { 7956 isObjCPointer = true; 7957 } else { 7958 std::swap(PExp, IExp); 7959 if (PExp->getType()->isPointerType()) { 7960 isObjCPointer = false; 7961 } else if (PExp->getType()->isObjCObjectPointerType()) { 7962 isObjCPointer = true; 7963 } else { 7964 return InvalidOperands(Loc, LHS, RHS); 7965 } 7966 } 7967 assert(PExp->getType()->isAnyPointerType()); 7968 7969 if (!IExp->getType()->isIntegerType()) 7970 return InvalidOperands(Loc, LHS, RHS); 7971 7972 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7973 return QualType(); 7974 7975 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7976 return QualType(); 7977 7978 // Check array bounds for pointer arithemtic 7979 CheckArrayAccess(PExp, IExp); 7980 7981 if (CompLHSTy) { 7982 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7983 if (LHSTy.isNull()) { 7984 LHSTy = LHS.get()->getType(); 7985 if (LHSTy->isPromotableIntegerType()) 7986 LHSTy = Context.getPromotedIntegerType(LHSTy); 7987 } 7988 *CompLHSTy = LHSTy; 7989 } 7990 7991 return PExp->getType(); 7992 } 7993 7994 // C99 6.5.6 7995 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7996 SourceLocation Loc, 7997 QualType* CompLHSTy) { 7998 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7999 8000 if (LHS.get()->getType()->isVectorType() || 8001 RHS.get()->getType()->isVectorType()) { 8002 QualType compType = CheckVectorOperands( 8003 LHS, RHS, Loc, CompLHSTy, 8004 /*AllowBothBool*/getLangOpts().AltiVec, 8005 /*AllowBoolConversions*/getLangOpts().ZVector); 8006 if (CompLHSTy) *CompLHSTy = compType; 8007 return compType; 8008 } 8009 8010 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8011 if (LHS.isInvalid() || RHS.isInvalid()) 8012 return QualType(); 8013 8014 // Enforce type constraints: C99 6.5.6p3. 8015 8016 // Handle the common case first (both operands are arithmetic). 8017 if (!compType.isNull() && compType->isArithmeticType()) { 8018 if (CompLHSTy) *CompLHSTy = compType; 8019 return compType; 8020 } 8021 8022 // Either ptr - int or ptr - ptr. 8023 if (LHS.get()->getType()->isAnyPointerType()) { 8024 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8025 8026 // Diagnose bad cases where we step over interface counts. 8027 if (LHS.get()->getType()->isObjCObjectPointerType() && 8028 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8029 return QualType(); 8030 8031 // The result type of a pointer-int computation is the pointer type. 8032 if (RHS.get()->getType()->isIntegerType()) { 8033 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8034 return QualType(); 8035 8036 // Check array bounds for pointer arithemtic 8037 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8038 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8039 8040 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8041 return LHS.get()->getType(); 8042 } 8043 8044 // Handle pointer-pointer subtractions. 8045 if (const PointerType *RHSPTy 8046 = RHS.get()->getType()->getAs<PointerType>()) { 8047 QualType rpointee = RHSPTy->getPointeeType(); 8048 8049 if (getLangOpts().CPlusPlus) { 8050 // Pointee types must be the same: C++ [expr.add] 8051 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8052 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8053 } 8054 } else { 8055 // Pointee types must be compatible C99 6.5.6p3 8056 if (!Context.typesAreCompatible( 8057 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8058 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8059 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8060 return QualType(); 8061 } 8062 } 8063 8064 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8065 LHS.get(), RHS.get())) 8066 return QualType(); 8067 8068 // The pointee type may have zero size. As an extension, a structure or 8069 // union may have zero size or an array may have zero length. In this 8070 // case subtraction does not make sense. 8071 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8072 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8073 if (ElementSize.isZero()) { 8074 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8075 << rpointee.getUnqualifiedType() 8076 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8077 } 8078 } 8079 8080 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8081 return Context.getPointerDiffType(); 8082 } 8083 } 8084 8085 return InvalidOperands(Loc, LHS, RHS); 8086 } 8087 8088 static bool isScopedEnumerationType(QualType T) { 8089 if (const EnumType *ET = T->getAs<EnumType>()) 8090 return ET->getDecl()->isScoped(); 8091 return false; 8092 } 8093 8094 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8095 SourceLocation Loc, unsigned Opc, 8096 QualType LHSType) { 8097 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8098 // so skip remaining warnings as we don't want to modify values within Sema. 8099 if (S.getLangOpts().OpenCL) 8100 return; 8101 8102 llvm::APSInt Right; 8103 // Check right/shifter operand 8104 if (RHS.get()->isValueDependent() || 8105 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8106 return; 8107 8108 if (Right.isNegative()) { 8109 S.DiagRuntimeBehavior(Loc, RHS.get(), 8110 S.PDiag(diag::warn_shift_negative) 8111 << RHS.get()->getSourceRange()); 8112 return; 8113 } 8114 llvm::APInt LeftBits(Right.getBitWidth(), 8115 S.Context.getTypeSize(LHS.get()->getType())); 8116 if (Right.uge(LeftBits)) { 8117 S.DiagRuntimeBehavior(Loc, RHS.get(), 8118 S.PDiag(diag::warn_shift_gt_typewidth) 8119 << RHS.get()->getSourceRange()); 8120 return; 8121 } 8122 if (Opc != BO_Shl) 8123 return; 8124 8125 // When left shifting an ICE which is signed, we can check for overflow which 8126 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8127 // integers have defined behavior modulo one more than the maximum value 8128 // representable in the result type, so never warn for those. 8129 llvm::APSInt Left; 8130 if (LHS.get()->isValueDependent() || 8131 LHSType->hasUnsignedIntegerRepresentation() || 8132 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8133 return; 8134 8135 // If LHS does not have a signed type and non-negative value 8136 // then, the behavior is undefined. Warn about it. 8137 if (Left.isNegative()) { 8138 S.DiagRuntimeBehavior(Loc, LHS.get(), 8139 S.PDiag(diag::warn_shift_lhs_negative) 8140 << LHS.get()->getSourceRange()); 8141 return; 8142 } 8143 8144 llvm::APInt ResultBits = 8145 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8146 if (LeftBits.uge(ResultBits)) 8147 return; 8148 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8149 Result = Result.shl(Right); 8150 8151 // Print the bit representation of the signed integer as an unsigned 8152 // hexadecimal number. 8153 SmallString<40> HexResult; 8154 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8155 8156 // If we are only missing a sign bit, this is less likely to result in actual 8157 // bugs -- if the result is cast back to an unsigned type, it will have the 8158 // expected value. Thus we place this behind a different warning that can be 8159 // turned off separately if needed. 8160 if (LeftBits == ResultBits - 1) { 8161 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8162 << HexResult << LHSType 8163 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8164 return; 8165 } 8166 8167 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8168 << HexResult.str() << Result.getMinSignedBits() << LHSType 8169 << Left.getBitWidth() << LHS.get()->getSourceRange() 8170 << RHS.get()->getSourceRange(); 8171 } 8172 8173 /// \brief Return the resulting type when an OpenCL vector is shifted 8174 /// by a scalar or vector shift amount. 8175 static QualType checkOpenCLVectorShift(Sema &S, 8176 ExprResult &LHS, ExprResult &RHS, 8177 SourceLocation Loc, bool IsCompAssign) { 8178 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8179 if (!LHS.get()->getType()->isVectorType()) { 8180 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8181 << RHS.get()->getType() << LHS.get()->getType() 8182 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8183 return QualType(); 8184 } 8185 8186 if (!IsCompAssign) { 8187 LHS = S.UsualUnaryConversions(LHS.get()); 8188 if (LHS.isInvalid()) return QualType(); 8189 } 8190 8191 RHS = S.UsualUnaryConversions(RHS.get()); 8192 if (RHS.isInvalid()) return QualType(); 8193 8194 QualType LHSType = LHS.get()->getType(); 8195 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8196 QualType LHSEleType = LHSVecTy->getElementType(); 8197 8198 // Note that RHS might not be a vector. 8199 QualType RHSType = RHS.get()->getType(); 8200 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8201 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8202 8203 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8204 if (!LHSEleType->isIntegerType()) { 8205 S.Diag(Loc, diag::err_typecheck_expect_int) 8206 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8207 return QualType(); 8208 } 8209 8210 if (!RHSEleType->isIntegerType()) { 8211 S.Diag(Loc, diag::err_typecheck_expect_int) 8212 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8213 return QualType(); 8214 } 8215 8216 if (RHSVecTy) { 8217 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8218 // are applied component-wise. So if RHS is a vector, then ensure 8219 // that the number of elements is the same as LHS... 8220 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8221 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8222 << LHS.get()->getType() << RHS.get()->getType() 8223 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8224 return QualType(); 8225 } 8226 } else { 8227 // ...else expand RHS to match the number of elements in LHS. 8228 QualType VecTy = 8229 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8230 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8231 } 8232 8233 return LHSType; 8234 } 8235 8236 // C99 6.5.7 8237 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8238 SourceLocation Loc, unsigned Opc, 8239 bool IsCompAssign) { 8240 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8241 8242 // Vector shifts promote their scalar inputs to vector type. 8243 if (LHS.get()->getType()->isVectorType() || 8244 RHS.get()->getType()->isVectorType()) { 8245 if (LangOpts.OpenCL) 8246 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8247 if (LangOpts.ZVector) { 8248 // The shift operators for the z vector extensions work basically 8249 // like OpenCL shifts, except that neither the LHS nor the RHS is 8250 // allowed to be a "vector bool". 8251 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8252 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8253 return InvalidOperands(Loc, LHS, RHS); 8254 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8255 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8256 return InvalidOperands(Loc, LHS, RHS); 8257 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8258 } 8259 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8260 /*AllowBothBool*/true, 8261 /*AllowBoolConversions*/false); 8262 } 8263 8264 // Shifts don't perform usual arithmetic conversions, they just do integer 8265 // promotions on each operand. C99 6.5.7p3 8266 8267 // For the LHS, do usual unary conversions, but then reset them away 8268 // if this is a compound assignment. 8269 ExprResult OldLHS = LHS; 8270 LHS = UsualUnaryConversions(LHS.get()); 8271 if (LHS.isInvalid()) 8272 return QualType(); 8273 QualType LHSType = LHS.get()->getType(); 8274 if (IsCompAssign) LHS = OldLHS; 8275 8276 // The RHS is simpler. 8277 RHS = UsualUnaryConversions(RHS.get()); 8278 if (RHS.isInvalid()) 8279 return QualType(); 8280 QualType RHSType = RHS.get()->getType(); 8281 8282 // C99 6.5.7p2: Each of the operands shall have integer type. 8283 if (!LHSType->hasIntegerRepresentation() || 8284 !RHSType->hasIntegerRepresentation()) 8285 return InvalidOperands(Loc, LHS, RHS); 8286 8287 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8288 // hasIntegerRepresentation() above instead of this. 8289 if (isScopedEnumerationType(LHSType) || 8290 isScopedEnumerationType(RHSType)) { 8291 return InvalidOperands(Loc, LHS, RHS); 8292 } 8293 // Sanity-check shift operands 8294 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8295 8296 // "The type of the result is that of the promoted left operand." 8297 return LHSType; 8298 } 8299 8300 static bool IsWithinTemplateSpecialization(Decl *D) { 8301 if (DeclContext *DC = D->getDeclContext()) { 8302 if (isa<ClassTemplateSpecializationDecl>(DC)) 8303 return true; 8304 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8305 return FD->isFunctionTemplateSpecialization(); 8306 } 8307 return false; 8308 } 8309 8310 /// If two different enums are compared, raise a warning. 8311 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8312 Expr *RHS) { 8313 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8314 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8315 8316 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8317 if (!LHSEnumType) 8318 return; 8319 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8320 if (!RHSEnumType) 8321 return; 8322 8323 // Ignore anonymous enums. 8324 if (!LHSEnumType->getDecl()->getIdentifier()) 8325 return; 8326 if (!RHSEnumType->getDecl()->getIdentifier()) 8327 return; 8328 8329 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8330 return; 8331 8332 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8333 << LHSStrippedType << RHSStrippedType 8334 << LHS->getSourceRange() << RHS->getSourceRange(); 8335 } 8336 8337 /// \brief Diagnose bad pointer comparisons. 8338 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8339 ExprResult &LHS, ExprResult &RHS, 8340 bool IsError) { 8341 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8342 : diag::ext_typecheck_comparison_of_distinct_pointers) 8343 << LHS.get()->getType() << RHS.get()->getType() 8344 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8345 } 8346 8347 /// \brief Returns false if the pointers are converted to a composite type, 8348 /// true otherwise. 8349 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8350 ExprResult &LHS, ExprResult &RHS) { 8351 // C++ [expr.rel]p2: 8352 // [...] Pointer conversions (4.10) and qualification 8353 // conversions (4.4) are performed on pointer operands (or on 8354 // a pointer operand and a null pointer constant) to bring 8355 // them to their composite pointer type. [...] 8356 // 8357 // C++ [expr.eq]p1 uses the same notion for (in)equality 8358 // comparisons of pointers. 8359 8360 // C++ [expr.eq]p2: 8361 // In addition, pointers to members can be compared, or a pointer to 8362 // member and a null pointer constant. Pointer to member conversions 8363 // (4.11) and qualification conversions (4.4) are performed to bring 8364 // them to a common type. If one operand is a null pointer constant, 8365 // the common type is the type of the other operand. Otherwise, the 8366 // common type is a pointer to member type similar (4.4) to the type 8367 // of one of the operands, with a cv-qualification signature (4.4) 8368 // that is the union of the cv-qualification signatures of the operand 8369 // types. 8370 8371 QualType LHSType = LHS.get()->getType(); 8372 QualType RHSType = RHS.get()->getType(); 8373 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8374 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8375 8376 bool NonStandardCompositeType = false; 8377 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8378 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8379 if (T.isNull()) { 8380 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8381 return true; 8382 } 8383 8384 if (NonStandardCompositeType) 8385 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8386 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8387 << RHS.get()->getSourceRange(); 8388 8389 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8390 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8391 return false; 8392 } 8393 8394 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8395 ExprResult &LHS, 8396 ExprResult &RHS, 8397 bool IsError) { 8398 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8399 : diag::ext_typecheck_comparison_of_fptr_to_void) 8400 << LHS.get()->getType() << RHS.get()->getType() 8401 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8402 } 8403 8404 static bool isObjCObjectLiteral(ExprResult &E) { 8405 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8406 case Stmt::ObjCArrayLiteralClass: 8407 case Stmt::ObjCDictionaryLiteralClass: 8408 case Stmt::ObjCStringLiteralClass: 8409 case Stmt::ObjCBoxedExprClass: 8410 return true; 8411 default: 8412 // Note that ObjCBoolLiteral is NOT an object literal! 8413 return false; 8414 } 8415 } 8416 8417 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8418 const ObjCObjectPointerType *Type = 8419 LHS->getType()->getAs<ObjCObjectPointerType>(); 8420 8421 // If this is not actually an Objective-C object, bail out. 8422 if (!Type) 8423 return false; 8424 8425 // Get the LHS object's interface type. 8426 QualType InterfaceType = Type->getPointeeType(); 8427 8428 // If the RHS isn't an Objective-C object, bail out. 8429 if (!RHS->getType()->isObjCObjectPointerType()) 8430 return false; 8431 8432 // Try to find the -isEqual: method. 8433 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8434 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8435 InterfaceType, 8436 /*instance=*/true); 8437 if (!Method) { 8438 if (Type->isObjCIdType()) { 8439 // For 'id', just check the global pool. 8440 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8441 /*receiverId=*/true); 8442 } else { 8443 // Check protocols. 8444 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8445 /*instance=*/true); 8446 } 8447 } 8448 8449 if (!Method) 8450 return false; 8451 8452 QualType T = Method->parameters()[0]->getType(); 8453 if (!T->isObjCObjectPointerType()) 8454 return false; 8455 8456 QualType R = Method->getReturnType(); 8457 if (!R->isScalarType()) 8458 return false; 8459 8460 return true; 8461 } 8462 8463 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8464 FromE = FromE->IgnoreParenImpCasts(); 8465 switch (FromE->getStmtClass()) { 8466 default: 8467 break; 8468 case Stmt::ObjCStringLiteralClass: 8469 // "string literal" 8470 return LK_String; 8471 case Stmt::ObjCArrayLiteralClass: 8472 // "array literal" 8473 return LK_Array; 8474 case Stmt::ObjCDictionaryLiteralClass: 8475 // "dictionary literal" 8476 return LK_Dictionary; 8477 case Stmt::BlockExprClass: 8478 return LK_Block; 8479 case Stmt::ObjCBoxedExprClass: { 8480 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8481 switch (Inner->getStmtClass()) { 8482 case Stmt::IntegerLiteralClass: 8483 case Stmt::FloatingLiteralClass: 8484 case Stmt::CharacterLiteralClass: 8485 case Stmt::ObjCBoolLiteralExprClass: 8486 case Stmt::CXXBoolLiteralExprClass: 8487 // "numeric literal" 8488 return LK_Numeric; 8489 case Stmt::ImplicitCastExprClass: { 8490 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8491 // Boolean literals can be represented by implicit casts. 8492 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8493 return LK_Numeric; 8494 break; 8495 } 8496 default: 8497 break; 8498 } 8499 return LK_Boxed; 8500 } 8501 } 8502 return LK_None; 8503 } 8504 8505 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8506 ExprResult &LHS, ExprResult &RHS, 8507 BinaryOperator::Opcode Opc){ 8508 Expr *Literal; 8509 Expr *Other; 8510 if (isObjCObjectLiteral(LHS)) { 8511 Literal = LHS.get(); 8512 Other = RHS.get(); 8513 } else { 8514 Literal = RHS.get(); 8515 Other = LHS.get(); 8516 } 8517 8518 // Don't warn on comparisons against nil. 8519 Other = Other->IgnoreParenCasts(); 8520 if (Other->isNullPointerConstant(S.getASTContext(), 8521 Expr::NPC_ValueDependentIsNotNull)) 8522 return; 8523 8524 // This should be kept in sync with warn_objc_literal_comparison. 8525 // LK_String should always be after the other literals, since it has its own 8526 // warning flag. 8527 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8528 assert(LiteralKind != Sema::LK_Block); 8529 if (LiteralKind == Sema::LK_None) { 8530 llvm_unreachable("Unknown Objective-C object literal kind"); 8531 } 8532 8533 if (LiteralKind == Sema::LK_String) 8534 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8535 << Literal->getSourceRange(); 8536 else 8537 S.Diag(Loc, diag::warn_objc_literal_comparison) 8538 << LiteralKind << Literal->getSourceRange(); 8539 8540 if (BinaryOperator::isEqualityOp(Opc) && 8541 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8542 SourceLocation Start = LHS.get()->getLocStart(); 8543 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 8544 CharSourceRange OpRange = 8545 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 8546 8547 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8548 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8549 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8550 << FixItHint::CreateInsertion(End, "]"); 8551 } 8552 } 8553 8554 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8555 ExprResult &RHS, 8556 SourceLocation Loc, 8557 unsigned OpaqueOpc) { 8558 // Check that left hand side is !something. 8559 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8560 if (!UO || UO->getOpcode() != UO_LNot) return; 8561 8562 // Only check if the right hand side is non-bool arithmetic type. 8563 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8564 8565 // Make sure that the something in !something is not bool. 8566 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8567 if (SubExpr->isKnownToHaveBooleanValue()) return; 8568 8569 // Emit warning. 8570 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8571 << Loc; 8572 8573 // First note suggest !(x < y) 8574 SourceLocation FirstOpen = SubExpr->getLocStart(); 8575 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8576 FirstClose = S.getLocForEndOfToken(FirstClose); 8577 if (FirstClose.isInvalid()) 8578 FirstOpen = SourceLocation(); 8579 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8580 << FixItHint::CreateInsertion(FirstOpen, "(") 8581 << FixItHint::CreateInsertion(FirstClose, ")"); 8582 8583 // Second note suggests (!x) < y 8584 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8585 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8586 SecondClose = S.getLocForEndOfToken(SecondClose); 8587 if (SecondClose.isInvalid()) 8588 SecondOpen = SourceLocation(); 8589 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8590 << FixItHint::CreateInsertion(SecondOpen, "(") 8591 << FixItHint::CreateInsertion(SecondClose, ")"); 8592 } 8593 8594 // Get the decl for a simple expression: a reference to a variable, 8595 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8596 static ValueDecl *getCompareDecl(Expr *E) { 8597 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8598 return DR->getDecl(); 8599 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8600 if (Ivar->isFreeIvar()) 8601 return Ivar->getDecl(); 8602 } 8603 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8604 if (Mem->isImplicitAccess()) 8605 return Mem->getMemberDecl(); 8606 } 8607 return nullptr; 8608 } 8609 8610 // C99 6.5.8, C++ [expr.rel] 8611 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8612 SourceLocation Loc, unsigned OpaqueOpc, 8613 bool IsRelational) { 8614 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8615 8616 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 8617 8618 // Handle vector comparisons separately. 8619 if (LHS.get()->getType()->isVectorType() || 8620 RHS.get()->getType()->isVectorType()) 8621 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8622 8623 QualType LHSType = LHS.get()->getType(); 8624 QualType RHSType = RHS.get()->getType(); 8625 8626 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8627 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8628 8629 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8630 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 8631 8632 if (!LHSType->hasFloatingRepresentation() && 8633 !(LHSType->isBlockPointerType() && IsRelational) && 8634 !LHS.get()->getLocStart().isMacroID() && 8635 !RHS.get()->getLocStart().isMacroID() && 8636 ActiveTemplateInstantiations.empty()) { 8637 // For non-floating point types, check for self-comparisons of the form 8638 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8639 // often indicate logic errors in the program. 8640 // 8641 // NOTE: Don't warn about comparison expressions resulting from macro 8642 // expansion. Also don't warn about comparisons which are only self 8643 // comparisons within a template specialization. The warnings should catch 8644 // obvious cases in the definition of the template anyways. The idea is to 8645 // warn when the typed comparison operator will always evaluate to the same 8646 // result. 8647 ValueDecl *DL = getCompareDecl(LHSStripped); 8648 ValueDecl *DR = getCompareDecl(RHSStripped); 8649 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8650 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8651 << 0 // self- 8652 << (Opc == BO_EQ 8653 || Opc == BO_LE 8654 || Opc == BO_GE)); 8655 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8656 !DL->getType()->isReferenceType() && 8657 !DR->getType()->isReferenceType()) { 8658 // what is it always going to eval to? 8659 char always_evals_to; 8660 switch(Opc) { 8661 case BO_EQ: // e.g. array1 == array2 8662 always_evals_to = 0; // false 8663 break; 8664 case BO_NE: // e.g. array1 != array2 8665 always_evals_to = 1; // true 8666 break; 8667 default: 8668 // best we can say is 'a constant' 8669 always_evals_to = 2; // e.g. array1 <= array2 8670 break; 8671 } 8672 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8673 << 1 // array 8674 << always_evals_to); 8675 } 8676 8677 if (isa<CastExpr>(LHSStripped)) 8678 LHSStripped = LHSStripped->IgnoreParenCasts(); 8679 if (isa<CastExpr>(RHSStripped)) 8680 RHSStripped = RHSStripped->IgnoreParenCasts(); 8681 8682 // Warn about comparisons against a string constant (unless the other 8683 // operand is null), the user probably wants strcmp. 8684 Expr *literalString = nullptr; 8685 Expr *literalStringStripped = nullptr; 8686 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8687 !RHSStripped->isNullPointerConstant(Context, 8688 Expr::NPC_ValueDependentIsNull)) { 8689 literalString = LHS.get(); 8690 literalStringStripped = LHSStripped; 8691 } else if ((isa<StringLiteral>(RHSStripped) || 8692 isa<ObjCEncodeExpr>(RHSStripped)) && 8693 !LHSStripped->isNullPointerConstant(Context, 8694 Expr::NPC_ValueDependentIsNull)) { 8695 literalString = RHS.get(); 8696 literalStringStripped = RHSStripped; 8697 } 8698 8699 if (literalString) { 8700 DiagRuntimeBehavior(Loc, nullptr, 8701 PDiag(diag::warn_stringcompare) 8702 << isa<ObjCEncodeExpr>(literalStringStripped) 8703 << literalString->getSourceRange()); 8704 } 8705 } 8706 8707 // C99 6.5.8p3 / C99 6.5.9p4 8708 UsualArithmeticConversions(LHS, RHS); 8709 if (LHS.isInvalid() || RHS.isInvalid()) 8710 return QualType(); 8711 8712 LHSType = LHS.get()->getType(); 8713 RHSType = RHS.get()->getType(); 8714 8715 // The result of comparisons is 'bool' in C++, 'int' in C. 8716 QualType ResultTy = Context.getLogicalOperationType(); 8717 8718 if (IsRelational) { 8719 if (LHSType->isRealType() && RHSType->isRealType()) 8720 return ResultTy; 8721 } else { 8722 // Check for comparisons of floating point operands using != and ==. 8723 if (LHSType->hasFloatingRepresentation()) 8724 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8725 8726 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8727 return ResultTy; 8728 } 8729 8730 const Expr::NullPointerConstantKind LHSNullKind = 8731 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8732 const Expr::NullPointerConstantKind RHSNullKind = 8733 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8734 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8735 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8736 8737 if (!IsRelational && LHSIsNull != RHSIsNull) { 8738 bool IsEquality = Opc == BO_EQ; 8739 if (RHSIsNull) 8740 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 8741 RHS.get()->getSourceRange()); 8742 else 8743 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 8744 LHS.get()->getSourceRange()); 8745 } 8746 8747 // All of the following pointer-related warnings are GCC extensions, except 8748 // when handling null pointer constants. 8749 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 8750 QualType LCanPointeeTy = 8751 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8752 QualType RCanPointeeTy = 8753 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8754 8755 if (getLangOpts().CPlusPlus) { 8756 if (LCanPointeeTy == RCanPointeeTy) 8757 return ResultTy; 8758 if (!IsRelational && 8759 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8760 // Valid unless comparison between non-null pointer and function pointer 8761 // This is a gcc extension compatibility comparison. 8762 // In a SFINAE context, we treat this as a hard error to maintain 8763 // conformance with the C++ standard. 8764 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8765 && !LHSIsNull && !RHSIsNull) { 8766 diagnoseFunctionPointerToVoidComparison( 8767 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8768 8769 if (isSFINAEContext()) 8770 return QualType(); 8771 8772 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8773 return ResultTy; 8774 } 8775 } 8776 8777 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8778 return QualType(); 8779 else 8780 return ResultTy; 8781 } 8782 // C99 6.5.9p2 and C99 6.5.8p2 8783 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8784 RCanPointeeTy.getUnqualifiedType())) { 8785 // Valid unless a relational comparison of function pointers 8786 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8787 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8788 << LHSType << RHSType << LHS.get()->getSourceRange() 8789 << RHS.get()->getSourceRange(); 8790 } 8791 } else if (!IsRelational && 8792 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8793 // Valid unless comparison between non-null pointer and function pointer 8794 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8795 && !LHSIsNull && !RHSIsNull) 8796 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8797 /*isError*/false); 8798 } else { 8799 // Invalid 8800 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8801 } 8802 if (LCanPointeeTy != RCanPointeeTy) { 8803 if (getLangOpts().OpenCL) { 8804 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 8805 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 8806 Diag(Loc, 8807 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8808 << LHSType << RHSType << 0 /* comparison */ 8809 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8810 } 8811 } 8812 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 8813 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 8814 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 8815 : CK_BitCast; 8816 if (LHSIsNull && !RHSIsNull) 8817 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 8818 else 8819 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 8820 } 8821 return ResultTy; 8822 } 8823 8824 if (getLangOpts().CPlusPlus) { 8825 // Comparison of nullptr_t with itself. 8826 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 8827 return ResultTy; 8828 8829 // Comparison of pointers with null pointer constants and equality 8830 // comparisons of member pointers to null pointer constants. 8831 if (RHSIsNull && 8832 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 8833 (!IsRelational && 8834 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 8835 RHS = ImpCastExprToType(RHS.get(), LHSType, 8836 LHSType->isMemberPointerType() 8837 ? CK_NullToMemberPointer 8838 : CK_NullToPointer); 8839 return ResultTy; 8840 } 8841 if (LHSIsNull && 8842 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 8843 (!IsRelational && 8844 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 8845 LHS = ImpCastExprToType(LHS.get(), RHSType, 8846 RHSType->isMemberPointerType() 8847 ? CK_NullToMemberPointer 8848 : CK_NullToPointer); 8849 return ResultTy; 8850 } 8851 8852 // Comparison of member pointers. 8853 if (!IsRelational && 8854 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 8855 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8856 return QualType(); 8857 else 8858 return ResultTy; 8859 } 8860 8861 // Handle scoped enumeration types specifically, since they don't promote 8862 // to integers. 8863 if (LHS.get()->getType()->isEnumeralType() && 8864 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8865 RHS.get()->getType())) 8866 return ResultTy; 8867 } 8868 8869 // Handle block pointer types. 8870 if (!IsRelational && LHSType->isBlockPointerType() && 8871 RHSType->isBlockPointerType()) { 8872 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8873 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8874 8875 if (!LHSIsNull && !RHSIsNull && 8876 !Context.typesAreCompatible(lpointee, rpointee)) { 8877 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8878 << LHSType << RHSType << LHS.get()->getSourceRange() 8879 << RHS.get()->getSourceRange(); 8880 } 8881 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8882 return ResultTy; 8883 } 8884 8885 // Allow block pointers to be compared with null pointer constants. 8886 if (!IsRelational 8887 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8888 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8889 if (!LHSIsNull && !RHSIsNull) { 8890 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8891 ->getPointeeType()->isVoidType()) 8892 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8893 ->getPointeeType()->isVoidType()))) 8894 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8895 << LHSType << RHSType << LHS.get()->getSourceRange() 8896 << RHS.get()->getSourceRange(); 8897 } 8898 if (LHSIsNull && !RHSIsNull) 8899 LHS = ImpCastExprToType(LHS.get(), RHSType, 8900 RHSType->isPointerType() ? CK_BitCast 8901 : CK_AnyPointerToBlockPointerCast); 8902 else 8903 RHS = ImpCastExprToType(RHS.get(), LHSType, 8904 LHSType->isPointerType() ? CK_BitCast 8905 : CK_AnyPointerToBlockPointerCast); 8906 return ResultTy; 8907 } 8908 8909 if (LHSType->isObjCObjectPointerType() || 8910 RHSType->isObjCObjectPointerType()) { 8911 const PointerType *LPT = LHSType->getAs<PointerType>(); 8912 const PointerType *RPT = RHSType->getAs<PointerType>(); 8913 if (LPT || RPT) { 8914 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8915 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8916 8917 if (!LPtrToVoid && !RPtrToVoid && 8918 !Context.typesAreCompatible(LHSType, RHSType)) { 8919 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8920 /*isError*/false); 8921 } 8922 if (LHSIsNull && !RHSIsNull) { 8923 Expr *E = LHS.get(); 8924 if (getLangOpts().ObjCAutoRefCount) 8925 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8926 LHS = ImpCastExprToType(E, RHSType, 8927 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8928 } 8929 else { 8930 Expr *E = RHS.get(); 8931 if (getLangOpts().ObjCAutoRefCount) 8932 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false, 8933 Opc); 8934 RHS = ImpCastExprToType(E, LHSType, 8935 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8936 } 8937 return ResultTy; 8938 } 8939 if (LHSType->isObjCObjectPointerType() && 8940 RHSType->isObjCObjectPointerType()) { 8941 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8942 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8943 /*isError*/false); 8944 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8945 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8946 8947 if (LHSIsNull && !RHSIsNull) 8948 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8949 else 8950 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8951 return ResultTy; 8952 } 8953 } 8954 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8955 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8956 unsigned DiagID = 0; 8957 bool isError = false; 8958 if (LangOpts.DebuggerSupport) { 8959 // Under a debugger, allow the comparison of pointers to integers, 8960 // since users tend to want to compare addresses. 8961 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8962 (RHSIsNull && RHSType->isIntegerType())) { 8963 if (IsRelational && !getLangOpts().CPlusPlus) 8964 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8965 } else if (IsRelational && !getLangOpts().CPlusPlus) 8966 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8967 else if (getLangOpts().CPlusPlus) { 8968 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8969 isError = true; 8970 } else 8971 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8972 8973 if (DiagID) { 8974 Diag(Loc, DiagID) 8975 << LHSType << RHSType << LHS.get()->getSourceRange() 8976 << RHS.get()->getSourceRange(); 8977 if (isError) 8978 return QualType(); 8979 } 8980 8981 if (LHSType->isIntegerType()) 8982 LHS = ImpCastExprToType(LHS.get(), RHSType, 8983 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8984 else 8985 RHS = ImpCastExprToType(RHS.get(), LHSType, 8986 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8987 return ResultTy; 8988 } 8989 8990 // Handle block pointers. 8991 if (!IsRelational && RHSIsNull 8992 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8993 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8994 return ResultTy; 8995 } 8996 if (!IsRelational && LHSIsNull 8997 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8998 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 8999 return ResultTy; 9000 } 9001 9002 return InvalidOperands(Loc, LHS, RHS); 9003 } 9004 9005 9006 // Return a signed type that is of identical size and number of elements. 9007 // For floating point vectors, return an integer type of identical size 9008 // and number of elements. 9009 QualType Sema::GetSignedVectorType(QualType V) { 9010 const VectorType *VTy = V->getAs<VectorType>(); 9011 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9012 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9013 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9014 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9015 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9016 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9017 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9018 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9019 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9020 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9021 "Unhandled vector element size in vector compare"); 9022 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9023 } 9024 9025 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9026 /// operates on extended vector types. Instead of producing an IntTy result, 9027 /// like a scalar comparison, a vector comparison produces a vector of integer 9028 /// types. 9029 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9030 SourceLocation Loc, 9031 bool IsRelational) { 9032 // Check to make sure we're operating on vectors of the same type and width, 9033 // Allowing one side to be a scalar of element type. 9034 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9035 /*AllowBothBool*/true, 9036 /*AllowBoolConversions*/getLangOpts().ZVector); 9037 if (vType.isNull()) 9038 return vType; 9039 9040 QualType LHSType = LHS.get()->getType(); 9041 9042 // If AltiVec, the comparison results in a numeric type, i.e. 9043 // bool for C++, int for C 9044 if (getLangOpts().AltiVec && 9045 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9046 return Context.getLogicalOperationType(); 9047 9048 // For non-floating point types, check for self-comparisons of the form 9049 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9050 // often indicate logic errors in the program. 9051 if (!LHSType->hasFloatingRepresentation() && 9052 ActiveTemplateInstantiations.empty()) { 9053 if (DeclRefExpr* DRL 9054 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9055 if (DeclRefExpr* DRR 9056 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9057 if (DRL->getDecl() == DRR->getDecl()) 9058 DiagRuntimeBehavior(Loc, nullptr, 9059 PDiag(diag::warn_comparison_always) 9060 << 0 // self- 9061 << 2 // "a constant" 9062 ); 9063 } 9064 9065 // Check for comparisons of floating point operands using != and ==. 9066 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9067 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9068 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9069 } 9070 9071 // Return a signed type for the vector. 9072 return GetSignedVectorType(LHSType); 9073 } 9074 9075 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9076 SourceLocation Loc) { 9077 // Ensure that either both operands are of the same vector type, or 9078 // one operand is of a vector type and the other is of its element type. 9079 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9080 /*AllowBothBool*/true, 9081 /*AllowBoolConversions*/false); 9082 if (vType.isNull()) 9083 return InvalidOperands(Loc, LHS, RHS); 9084 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9085 vType->hasFloatingRepresentation()) 9086 return InvalidOperands(Loc, LHS, RHS); 9087 9088 return GetSignedVectorType(LHS.get()->getType()); 9089 } 9090 9091 inline QualType Sema::CheckBitwiseOperands( 9092 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9093 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9094 9095 if (LHS.get()->getType()->isVectorType() || 9096 RHS.get()->getType()->isVectorType()) { 9097 if (LHS.get()->getType()->hasIntegerRepresentation() && 9098 RHS.get()->getType()->hasIntegerRepresentation()) 9099 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9100 /*AllowBothBool*/true, 9101 /*AllowBoolConversions*/getLangOpts().ZVector); 9102 return InvalidOperands(Loc, LHS, RHS); 9103 } 9104 9105 ExprResult LHSResult = LHS, RHSResult = RHS; 9106 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9107 IsCompAssign); 9108 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9109 return QualType(); 9110 LHS = LHSResult.get(); 9111 RHS = RHSResult.get(); 9112 9113 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9114 return compType; 9115 return InvalidOperands(Loc, LHS, RHS); 9116 } 9117 9118 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 9119 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 9120 9121 // Check vector operands differently. 9122 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9123 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9124 9125 // Diagnose cases where the user write a logical and/or but probably meant a 9126 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9127 // is a constant. 9128 if (LHS.get()->getType()->isIntegerType() && 9129 !LHS.get()->getType()->isBooleanType() && 9130 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9131 // Don't warn in macros or template instantiations. 9132 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9133 // If the RHS can be constant folded, and if it constant folds to something 9134 // that isn't 0 or 1 (which indicate a potential logical operation that 9135 // happened to fold to true/false) then warn. 9136 // Parens on the RHS are ignored. 9137 llvm::APSInt Result; 9138 if (RHS.get()->EvaluateAsInt(Result, Context)) 9139 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9140 !RHS.get()->getExprLoc().isMacroID()) || 9141 (Result != 0 && Result != 1)) { 9142 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9143 << RHS.get()->getSourceRange() 9144 << (Opc == BO_LAnd ? "&&" : "||"); 9145 // Suggest replacing the logical operator with the bitwise version 9146 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9147 << (Opc == BO_LAnd ? "&" : "|") 9148 << FixItHint::CreateReplacement(SourceRange( 9149 Loc, getLocForEndOfToken(Loc)), 9150 Opc == BO_LAnd ? "&" : "|"); 9151 if (Opc == BO_LAnd) 9152 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9153 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9154 << FixItHint::CreateRemoval( 9155 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9156 RHS.get()->getLocEnd())); 9157 } 9158 } 9159 9160 if (!Context.getLangOpts().CPlusPlus) { 9161 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9162 // not operate on the built-in scalar and vector float types. 9163 if (Context.getLangOpts().OpenCL && 9164 Context.getLangOpts().OpenCLVersion < 120) { 9165 if (LHS.get()->getType()->isFloatingType() || 9166 RHS.get()->getType()->isFloatingType()) 9167 return InvalidOperands(Loc, LHS, RHS); 9168 } 9169 9170 LHS = UsualUnaryConversions(LHS.get()); 9171 if (LHS.isInvalid()) 9172 return QualType(); 9173 9174 RHS = UsualUnaryConversions(RHS.get()); 9175 if (RHS.isInvalid()) 9176 return QualType(); 9177 9178 if (!LHS.get()->getType()->isScalarType() || 9179 !RHS.get()->getType()->isScalarType()) 9180 return InvalidOperands(Loc, LHS, RHS); 9181 9182 return Context.IntTy; 9183 } 9184 9185 // The following is safe because we only use this method for 9186 // non-overloadable operands. 9187 9188 // C++ [expr.log.and]p1 9189 // C++ [expr.log.or]p1 9190 // The operands are both contextually converted to type bool. 9191 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9192 if (LHSRes.isInvalid()) 9193 return InvalidOperands(Loc, LHS, RHS); 9194 LHS = LHSRes; 9195 9196 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9197 if (RHSRes.isInvalid()) 9198 return InvalidOperands(Loc, LHS, RHS); 9199 RHS = RHSRes; 9200 9201 // C++ [expr.log.and]p2 9202 // C++ [expr.log.or]p2 9203 // The result is a bool. 9204 return Context.BoolTy; 9205 } 9206 9207 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9208 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9209 if (!ME) return false; 9210 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9211 ObjCMessageExpr *Base = 9212 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9213 if (!Base) return false; 9214 return Base->getMethodDecl() != nullptr; 9215 } 9216 9217 /// Is the given expression (which must be 'const') a reference to a 9218 /// variable which was originally non-const, but which has become 9219 /// 'const' due to being captured within a block? 9220 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9221 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9222 assert(E->isLValue() && E->getType().isConstQualified()); 9223 E = E->IgnoreParens(); 9224 9225 // Must be a reference to a declaration from an enclosing scope. 9226 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9227 if (!DRE) return NCCK_None; 9228 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9229 9230 // The declaration must be a variable which is not declared 'const'. 9231 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9232 if (!var) return NCCK_None; 9233 if (var->getType().isConstQualified()) return NCCK_None; 9234 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9235 9236 // Decide whether the first capture was for a block or a lambda. 9237 DeclContext *DC = S.CurContext, *Prev = nullptr; 9238 while (DC != var->getDeclContext()) { 9239 Prev = DC; 9240 DC = DC->getParent(); 9241 } 9242 // Unless we have an init-capture, we've gone one step too far. 9243 if (!var->isInitCapture()) 9244 DC = Prev; 9245 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9246 } 9247 9248 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9249 Ty = Ty.getNonReferenceType(); 9250 if (IsDereference && Ty->isPointerType()) 9251 Ty = Ty->getPointeeType(); 9252 return !Ty.isConstQualified(); 9253 } 9254 9255 /// Emit the "read-only variable not assignable" error and print notes to give 9256 /// more information about why the variable is not assignable, such as pointing 9257 /// to the declaration of a const variable, showing that a method is const, or 9258 /// that the function is returning a const reference. 9259 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9260 SourceLocation Loc) { 9261 // Update err_typecheck_assign_const and note_typecheck_assign_const 9262 // when this enum is changed. 9263 enum { 9264 ConstFunction, 9265 ConstVariable, 9266 ConstMember, 9267 ConstMethod, 9268 ConstUnknown, // Keep as last element 9269 }; 9270 9271 SourceRange ExprRange = E->getSourceRange(); 9272 9273 // Only emit one error on the first const found. All other consts will emit 9274 // a note to the error. 9275 bool DiagnosticEmitted = false; 9276 9277 // Track if the current expression is the result of a derefence, and if the 9278 // next checked expression is the result of a derefence. 9279 bool IsDereference = false; 9280 bool NextIsDereference = false; 9281 9282 // Loop to process MemberExpr chains. 9283 while (true) { 9284 IsDereference = NextIsDereference; 9285 NextIsDereference = false; 9286 9287 E = E->IgnoreParenImpCasts(); 9288 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9289 NextIsDereference = ME->isArrow(); 9290 const ValueDecl *VD = ME->getMemberDecl(); 9291 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9292 // Mutable fields can be modified even if the class is const. 9293 if (Field->isMutable()) { 9294 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9295 break; 9296 } 9297 9298 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9299 if (!DiagnosticEmitted) { 9300 S.Diag(Loc, diag::err_typecheck_assign_const) 9301 << ExprRange << ConstMember << false /*static*/ << Field 9302 << Field->getType(); 9303 DiagnosticEmitted = true; 9304 } 9305 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9306 << ConstMember << false /*static*/ << Field << Field->getType() 9307 << Field->getSourceRange(); 9308 } 9309 E = ME->getBase(); 9310 continue; 9311 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9312 if (VDecl->getType().isConstQualified()) { 9313 if (!DiagnosticEmitted) { 9314 S.Diag(Loc, diag::err_typecheck_assign_const) 9315 << ExprRange << ConstMember << true /*static*/ << VDecl 9316 << VDecl->getType(); 9317 DiagnosticEmitted = true; 9318 } 9319 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9320 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9321 << VDecl->getSourceRange(); 9322 } 9323 // Static fields do not inherit constness from parents. 9324 break; 9325 } 9326 break; 9327 } // End MemberExpr 9328 break; 9329 } 9330 9331 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9332 // Function calls 9333 const FunctionDecl *FD = CE->getDirectCallee(); 9334 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9335 if (!DiagnosticEmitted) { 9336 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9337 << ConstFunction << FD; 9338 DiagnosticEmitted = true; 9339 } 9340 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9341 diag::note_typecheck_assign_const) 9342 << ConstFunction << FD << FD->getReturnType() 9343 << FD->getReturnTypeSourceRange(); 9344 } 9345 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9346 // Point to variable declaration. 9347 if (const ValueDecl *VD = DRE->getDecl()) { 9348 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9349 if (!DiagnosticEmitted) { 9350 S.Diag(Loc, diag::err_typecheck_assign_const) 9351 << ExprRange << ConstVariable << VD << VD->getType(); 9352 DiagnosticEmitted = true; 9353 } 9354 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9355 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9356 } 9357 } 9358 } else if (isa<CXXThisExpr>(E)) { 9359 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9360 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9361 if (MD->isConst()) { 9362 if (!DiagnosticEmitted) { 9363 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9364 << ConstMethod << MD; 9365 DiagnosticEmitted = true; 9366 } 9367 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9368 << ConstMethod << MD << MD->getSourceRange(); 9369 } 9370 } 9371 } 9372 } 9373 9374 if (DiagnosticEmitted) 9375 return; 9376 9377 // Can't determine a more specific message, so display the generic error. 9378 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9379 } 9380 9381 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9382 /// emit an error and return true. If so, return false. 9383 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9384 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9385 SourceLocation OrigLoc = Loc; 9386 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9387 &Loc); 9388 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9389 IsLV = Expr::MLV_InvalidMessageExpression; 9390 if (IsLV == Expr::MLV_Valid) 9391 return false; 9392 9393 unsigned DiagID = 0; 9394 bool NeedType = false; 9395 switch (IsLV) { // C99 6.5.16p2 9396 case Expr::MLV_ConstQualified: 9397 // Use a specialized diagnostic when we're assigning to an object 9398 // from an enclosing function or block. 9399 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9400 if (NCCK == NCCK_Block) 9401 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9402 else 9403 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9404 break; 9405 } 9406 9407 // In ARC, use some specialized diagnostics for occasions where we 9408 // infer 'const'. These are always pseudo-strong variables. 9409 if (S.getLangOpts().ObjCAutoRefCount) { 9410 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9411 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9412 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9413 9414 // Use the normal diagnostic if it's pseudo-__strong but the 9415 // user actually wrote 'const'. 9416 if (var->isARCPseudoStrong() && 9417 (!var->getTypeSourceInfo() || 9418 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9419 // There are two pseudo-strong cases: 9420 // - self 9421 ObjCMethodDecl *method = S.getCurMethodDecl(); 9422 if (method && var == method->getSelfDecl()) 9423 DiagID = method->isClassMethod() 9424 ? diag::err_typecheck_arc_assign_self_class_method 9425 : diag::err_typecheck_arc_assign_self; 9426 9427 // - fast enumeration variables 9428 else 9429 DiagID = diag::err_typecheck_arr_assign_enumeration; 9430 9431 SourceRange Assign; 9432 if (Loc != OrigLoc) 9433 Assign = SourceRange(OrigLoc, OrigLoc); 9434 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9435 // We need to preserve the AST regardless, so migration tool 9436 // can do its job. 9437 return false; 9438 } 9439 } 9440 } 9441 9442 // If none of the special cases above are triggered, then this is a 9443 // simple const assignment. 9444 if (DiagID == 0) { 9445 DiagnoseConstAssignment(S, E, Loc); 9446 return true; 9447 } 9448 9449 break; 9450 case Expr::MLV_ConstAddrSpace: 9451 DiagnoseConstAssignment(S, E, Loc); 9452 return true; 9453 case Expr::MLV_ArrayType: 9454 case Expr::MLV_ArrayTemporary: 9455 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9456 NeedType = true; 9457 break; 9458 case Expr::MLV_NotObjectType: 9459 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9460 NeedType = true; 9461 break; 9462 case Expr::MLV_LValueCast: 9463 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9464 break; 9465 case Expr::MLV_Valid: 9466 llvm_unreachable("did not take early return for MLV_Valid"); 9467 case Expr::MLV_InvalidExpression: 9468 case Expr::MLV_MemberFunction: 9469 case Expr::MLV_ClassTemporary: 9470 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9471 break; 9472 case Expr::MLV_IncompleteType: 9473 case Expr::MLV_IncompleteVoidType: 9474 return S.RequireCompleteType(Loc, E->getType(), 9475 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9476 case Expr::MLV_DuplicateVectorComponents: 9477 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9478 break; 9479 case Expr::MLV_NoSetterProperty: 9480 llvm_unreachable("readonly properties should be processed differently"); 9481 case Expr::MLV_InvalidMessageExpression: 9482 DiagID = diag::error_readonly_message_assignment; 9483 break; 9484 case Expr::MLV_SubObjCPropertySetting: 9485 DiagID = diag::error_no_subobject_property_setting; 9486 break; 9487 } 9488 9489 SourceRange Assign; 9490 if (Loc != OrigLoc) 9491 Assign = SourceRange(OrigLoc, OrigLoc); 9492 if (NeedType) 9493 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9494 else 9495 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9496 return true; 9497 } 9498 9499 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9500 SourceLocation Loc, 9501 Sema &Sema) { 9502 // C / C++ fields 9503 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9504 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9505 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9506 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9507 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9508 } 9509 9510 // Objective-C instance variables 9511 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9512 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9513 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9514 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9515 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9516 if (RL && RR && RL->getDecl() == RR->getDecl()) 9517 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9518 } 9519 } 9520 9521 // C99 6.5.16.1 9522 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9523 SourceLocation Loc, 9524 QualType CompoundType) { 9525 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9526 9527 // Verify that LHS is a modifiable lvalue, and emit error if not. 9528 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9529 return QualType(); 9530 9531 QualType LHSType = LHSExpr->getType(); 9532 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9533 CompoundType; 9534 AssignConvertType ConvTy; 9535 if (CompoundType.isNull()) { 9536 Expr *RHSCheck = RHS.get(); 9537 9538 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9539 9540 QualType LHSTy(LHSType); 9541 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9542 if (RHS.isInvalid()) 9543 return QualType(); 9544 // Special case of NSObject attributes on c-style pointer types. 9545 if (ConvTy == IncompatiblePointer && 9546 ((Context.isObjCNSObjectType(LHSType) && 9547 RHSType->isObjCObjectPointerType()) || 9548 (Context.isObjCNSObjectType(RHSType) && 9549 LHSType->isObjCObjectPointerType()))) 9550 ConvTy = Compatible; 9551 9552 if (ConvTy == Compatible && 9553 LHSType->isObjCObjectType()) 9554 Diag(Loc, diag::err_objc_object_assignment) 9555 << LHSType; 9556 9557 // If the RHS is a unary plus or minus, check to see if they = and + are 9558 // right next to each other. If so, the user may have typo'd "x =+ 4" 9559 // instead of "x += 4". 9560 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9561 RHSCheck = ICE->getSubExpr(); 9562 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9563 if ((UO->getOpcode() == UO_Plus || 9564 UO->getOpcode() == UO_Minus) && 9565 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9566 // Only if the two operators are exactly adjacent. 9567 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9568 // And there is a space or other character before the subexpr of the 9569 // unary +/-. We don't want to warn on "x=-1". 9570 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9571 UO->getSubExpr()->getLocStart().isFileID()) { 9572 Diag(Loc, diag::warn_not_compound_assign) 9573 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9574 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9575 } 9576 } 9577 9578 if (ConvTy == Compatible) { 9579 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9580 // Warn about retain cycles where a block captures the LHS, but 9581 // not if the LHS is a simple variable into which the block is 9582 // being stored...unless that variable can be captured by reference! 9583 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9584 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9585 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9586 checkRetainCycles(LHSExpr, RHS.get()); 9587 9588 // It is safe to assign a weak reference into a strong variable. 9589 // Although this code can still have problems: 9590 // id x = self.weakProp; 9591 // id y = self.weakProp; 9592 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9593 // paths through the function. This should be revisited if 9594 // -Wrepeated-use-of-weak is made flow-sensitive. 9595 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9596 RHS.get()->getLocStart())) 9597 getCurFunction()->markSafeWeakUse(RHS.get()); 9598 9599 } else if (getLangOpts().ObjCAutoRefCount) { 9600 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9601 } 9602 } 9603 } else { 9604 // Compound assignment "x += y" 9605 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9606 } 9607 9608 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9609 RHS.get(), AA_Assigning)) 9610 return QualType(); 9611 9612 CheckForNullPointerDereference(*this, LHSExpr); 9613 9614 // C99 6.5.16p3: The type of an assignment expression is the type of the 9615 // left operand unless the left operand has qualified type, in which case 9616 // it is the unqualified version of the type of the left operand. 9617 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9618 // is converted to the type of the assignment expression (above). 9619 // C++ 5.17p1: the type of the assignment expression is that of its left 9620 // operand. 9621 return (getLangOpts().CPlusPlus 9622 ? LHSType : LHSType.getUnqualifiedType()); 9623 } 9624 9625 // C99 6.5.17 9626 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9627 SourceLocation Loc) { 9628 LHS = S.CheckPlaceholderExpr(LHS.get()); 9629 RHS = S.CheckPlaceholderExpr(RHS.get()); 9630 if (LHS.isInvalid() || RHS.isInvalid()) 9631 return QualType(); 9632 9633 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9634 // operands, but not unary promotions. 9635 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9636 9637 // So we treat the LHS as a ignored value, and in C++ we allow the 9638 // containing site to determine what should be done with the RHS. 9639 LHS = S.IgnoredValueConversions(LHS.get()); 9640 if (LHS.isInvalid()) 9641 return QualType(); 9642 9643 S.DiagnoseUnusedExprResult(LHS.get()); 9644 9645 if (!S.getLangOpts().CPlusPlus) { 9646 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9647 if (RHS.isInvalid()) 9648 return QualType(); 9649 if (!RHS.get()->getType()->isVoidType()) 9650 S.RequireCompleteType(Loc, RHS.get()->getType(), 9651 diag::err_incomplete_type); 9652 } 9653 9654 return RHS.get()->getType(); 9655 } 9656 9657 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9658 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9659 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9660 ExprValueKind &VK, 9661 ExprObjectKind &OK, 9662 SourceLocation OpLoc, 9663 bool IsInc, bool IsPrefix) { 9664 if (Op->isTypeDependent()) 9665 return S.Context.DependentTy; 9666 9667 QualType ResType = Op->getType(); 9668 // Atomic types can be used for increment / decrement where the non-atomic 9669 // versions can, so ignore the _Atomic() specifier for the purpose of 9670 // checking. 9671 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9672 ResType = ResAtomicType->getValueType(); 9673 9674 assert(!ResType.isNull() && "no type for increment/decrement expression"); 9675 9676 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 9677 // Decrement of bool is not allowed. 9678 if (!IsInc) { 9679 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 9680 return QualType(); 9681 } 9682 // Increment of bool sets it to true, but is deprecated. 9683 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 9684 : diag::warn_increment_bool) 9685 << Op->getSourceRange(); 9686 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 9687 // Error on enum increments and decrements in C++ mode 9688 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 9689 return QualType(); 9690 } else if (ResType->isRealType()) { 9691 // OK! 9692 } else if (ResType->isPointerType()) { 9693 // C99 6.5.2.4p2, 6.5.6p2 9694 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 9695 return QualType(); 9696 } else if (ResType->isObjCObjectPointerType()) { 9697 // On modern runtimes, ObjC pointer arithmetic is forbidden. 9698 // Otherwise, we just need a complete type. 9699 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 9700 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 9701 return QualType(); 9702 } else if (ResType->isAnyComplexType()) { 9703 // C99 does not support ++/-- on complex types, we allow as an extension. 9704 S.Diag(OpLoc, diag::ext_integer_increment_complex) 9705 << ResType << Op->getSourceRange(); 9706 } else if (ResType->isPlaceholderType()) { 9707 ExprResult PR = S.CheckPlaceholderExpr(Op); 9708 if (PR.isInvalid()) return QualType(); 9709 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 9710 IsInc, IsPrefix); 9711 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 9712 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 9713 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 9714 (ResType->getAs<VectorType>()->getVectorKind() != 9715 VectorType::AltiVecBool)) { 9716 // The z vector extensions allow ++ and -- for non-bool vectors. 9717 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 9718 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 9719 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 9720 } else { 9721 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 9722 << ResType << int(IsInc) << Op->getSourceRange(); 9723 return QualType(); 9724 } 9725 // At this point, we know we have a real, complex or pointer type. 9726 // Now make sure the operand is a modifiable lvalue. 9727 if (CheckForModifiableLvalue(Op, OpLoc, S)) 9728 return QualType(); 9729 // In C++, a prefix increment is the same type as the operand. Otherwise 9730 // (in C or with postfix), the increment is the unqualified type of the 9731 // operand. 9732 if (IsPrefix && S.getLangOpts().CPlusPlus) { 9733 VK = VK_LValue; 9734 OK = Op->getObjectKind(); 9735 return ResType; 9736 } else { 9737 VK = VK_RValue; 9738 return ResType.getUnqualifiedType(); 9739 } 9740 } 9741 9742 9743 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 9744 /// This routine allows us to typecheck complex/recursive expressions 9745 /// where the declaration is needed for type checking. We only need to 9746 /// handle cases when the expression references a function designator 9747 /// or is an lvalue. Here are some examples: 9748 /// - &(x) => x 9749 /// - &*****f => f for f a function designator. 9750 /// - &s.xx => s 9751 /// - &s.zz[1].yy -> s, if zz is an array 9752 /// - *(x + 1) -> x, if x is an array 9753 /// - &"123"[2] -> 0 9754 /// - & __real__ x -> x 9755 static ValueDecl *getPrimaryDecl(Expr *E) { 9756 switch (E->getStmtClass()) { 9757 case Stmt::DeclRefExprClass: 9758 return cast<DeclRefExpr>(E)->getDecl(); 9759 case Stmt::MemberExprClass: 9760 // If this is an arrow operator, the address is an offset from 9761 // the base's value, so the object the base refers to is 9762 // irrelevant. 9763 if (cast<MemberExpr>(E)->isArrow()) 9764 return nullptr; 9765 // Otherwise, the expression refers to a part of the base 9766 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 9767 case Stmt::ArraySubscriptExprClass: { 9768 // FIXME: This code shouldn't be necessary! We should catch the implicit 9769 // promotion of register arrays earlier. 9770 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 9771 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 9772 if (ICE->getSubExpr()->getType()->isArrayType()) 9773 return getPrimaryDecl(ICE->getSubExpr()); 9774 } 9775 return nullptr; 9776 } 9777 case Stmt::UnaryOperatorClass: { 9778 UnaryOperator *UO = cast<UnaryOperator>(E); 9779 9780 switch(UO->getOpcode()) { 9781 case UO_Real: 9782 case UO_Imag: 9783 case UO_Extension: 9784 return getPrimaryDecl(UO->getSubExpr()); 9785 default: 9786 return nullptr; 9787 } 9788 } 9789 case Stmt::ParenExprClass: 9790 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 9791 case Stmt::ImplicitCastExprClass: 9792 // If the result of an implicit cast is an l-value, we care about 9793 // the sub-expression; otherwise, the result here doesn't matter. 9794 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 9795 default: 9796 return nullptr; 9797 } 9798 } 9799 9800 namespace { 9801 enum { 9802 AO_Bit_Field = 0, 9803 AO_Vector_Element = 1, 9804 AO_Property_Expansion = 2, 9805 AO_Register_Variable = 3, 9806 AO_No_Error = 4 9807 }; 9808 } 9809 /// \brief Diagnose invalid operand for address of operations. 9810 /// 9811 /// \param Type The type of operand which cannot have its address taken. 9812 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 9813 Expr *E, unsigned Type) { 9814 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 9815 } 9816 9817 /// CheckAddressOfOperand - The operand of & must be either a function 9818 /// designator or an lvalue designating an object. If it is an lvalue, the 9819 /// object cannot be declared with storage class register or be a bit field. 9820 /// Note: The usual conversions are *not* applied to the operand of the & 9821 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 9822 /// In C++, the operand might be an overloaded function name, in which case 9823 /// we allow the '&' but retain the overloaded-function type. 9824 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 9825 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 9826 if (PTy->getKind() == BuiltinType::Overload) { 9827 Expr *E = OrigOp.get()->IgnoreParens(); 9828 if (!isa<OverloadExpr>(E)) { 9829 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 9830 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 9831 << OrigOp.get()->getSourceRange(); 9832 return QualType(); 9833 } 9834 9835 OverloadExpr *Ovl = cast<OverloadExpr>(E); 9836 if (isa<UnresolvedMemberExpr>(Ovl)) 9837 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 9838 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9839 << OrigOp.get()->getSourceRange(); 9840 return QualType(); 9841 } 9842 9843 return Context.OverloadTy; 9844 } 9845 9846 if (PTy->getKind() == BuiltinType::UnknownAny) 9847 return Context.UnknownAnyTy; 9848 9849 if (PTy->getKind() == BuiltinType::BoundMember) { 9850 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9851 << OrigOp.get()->getSourceRange(); 9852 return QualType(); 9853 } 9854 9855 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 9856 if (OrigOp.isInvalid()) return QualType(); 9857 } 9858 9859 if (OrigOp.get()->isTypeDependent()) 9860 return Context.DependentTy; 9861 9862 assert(!OrigOp.get()->getType()->isPlaceholderType()); 9863 9864 // Make sure to ignore parentheses in subsequent checks 9865 Expr *op = OrigOp.get()->IgnoreParens(); 9866 9867 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 9868 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 9869 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 9870 return QualType(); 9871 } 9872 9873 if (getLangOpts().C99) { 9874 // Implement C99-only parts of addressof rules. 9875 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 9876 if (uOp->getOpcode() == UO_Deref) 9877 // Per C99 6.5.3.2, the address of a deref always returns a valid result 9878 // (assuming the deref expression is valid). 9879 return uOp->getSubExpr()->getType(); 9880 } 9881 // Technically, there should be a check for array subscript 9882 // expressions here, but the result of one is always an lvalue anyway. 9883 } 9884 ValueDecl *dcl = getPrimaryDecl(op); 9885 Expr::LValueClassification lval = op->ClassifyLValue(Context); 9886 unsigned AddressOfError = AO_No_Error; 9887 9888 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 9889 bool sfinae = (bool)isSFINAEContext(); 9890 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 9891 : diag::ext_typecheck_addrof_temporary) 9892 << op->getType() << op->getSourceRange(); 9893 if (sfinae) 9894 return QualType(); 9895 // Materialize the temporary as an lvalue so that we can take its address. 9896 OrigOp = op = new (Context) 9897 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 9898 } else if (isa<ObjCSelectorExpr>(op)) { 9899 return Context.getPointerType(op->getType()); 9900 } else if (lval == Expr::LV_MemberFunction) { 9901 // If it's an instance method, make a member pointer. 9902 // The expression must have exactly the form &A::foo. 9903 9904 // If the underlying expression isn't a decl ref, give up. 9905 if (!isa<DeclRefExpr>(op)) { 9906 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9907 << OrigOp.get()->getSourceRange(); 9908 return QualType(); 9909 } 9910 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 9911 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 9912 9913 // The id-expression was parenthesized. 9914 if (OrigOp.get() != DRE) { 9915 Diag(OpLoc, diag::err_parens_pointer_member_function) 9916 << OrigOp.get()->getSourceRange(); 9917 9918 // The method was named without a qualifier. 9919 } else if (!DRE->getQualifier()) { 9920 if (MD->getParent()->getName().empty()) 9921 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9922 << op->getSourceRange(); 9923 else { 9924 SmallString<32> Str; 9925 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 9926 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9927 << op->getSourceRange() 9928 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 9929 } 9930 } 9931 9932 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 9933 if (isa<CXXDestructorDecl>(MD)) 9934 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 9935 9936 QualType MPTy = Context.getMemberPointerType( 9937 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 9938 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9939 RequireCompleteType(OpLoc, MPTy, 0); 9940 return MPTy; 9941 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 9942 // C99 6.5.3.2p1 9943 // The operand must be either an l-value or a function designator 9944 if (!op->getType()->isFunctionType()) { 9945 // Use a special diagnostic for loads from property references. 9946 if (isa<PseudoObjectExpr>(op)) { 9947 AddressOfError = AO_Property_Expansion; 9948 } else { 9949 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 9950 << op->getType() << op->getSourceRange(); 9951 return QualType(); 9952 } 9953 } 9954 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 9955 // The operand cannot be a bit-field 9956 AddressOfError = AO_Bit_Field; 9957 } else if (op->getObjectKind() == OK_VectorComponent) { 9958 // The operand cannot be an element of a vector 9959 AddressOfError = AO_Vector_Element; 9960 } else if (dcl) { // C99 6.5.3.2p1 9961 // We have an lvalue with a decl. Make sure the decl is not declared 9962 // with the register storage-class specifier. 9963 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 9964 // in C++ it is not error to take address of a register 9965 // variable (c++03 7.1.1P3) 9966 if (vd->getStorageClass() == SC_Register && 9967 !getLangOpts().CPlusPlus) { 9968 AddressOfError = AO_Register_Variable; 9969 } 9970 } else if (isa<MSPropertyDecl>(dcl)) { 9971 AddressOfError = AO_Property_Expansion; 9972 } else if (isa<FunctionTemplateDecl>(dcl)) { 9973 return Context.OverloadTy; 9974 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 9975 // Okay: we can take the address of a field. 9976 // Could be a pointer to member, though, if there is an explicit 9977 // scope qualifier for the class. 9978 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 9979 DeclContext *Ctx = dcl->getDeclContext(); 9980 if (Ctx && Ctx->isRecord()) { 9981 if (dcl->getType()->isReferenceType()) { 9982 Diag(OpLoc, 9983 diag::err_cannot_form_pointer_to_member_of_reference_type) 9984 << dcl->getDeclName() << dcl->getType(); 9985 return QualType(); 9986 } 9987 9988 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 9989 Ctx = Ctx->getParent(); 9990 9991 QualType MPTy = Context.getMemberPointerType( 9992 op->getType(), 9993 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 9994 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9995 RequireCompleteType(OpLoc, MPTy, 0); 9996 return MPTy; 9997 } 9998 } 9999 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10000 llvm_unreachable("Unknown/unexpected decl type"); 10001 } 10002 10003 if (AddressOfError != AO_No_Error) { 10004 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10005 return QualType(); 10006 } 10007 10008 if (lval == Expr::LV_IncompleteVoidType) { 10009 // Taking the address of a void variable is technically illegal, but we 10010 // allow it in cases which are otherwise valid. 10011 // Example: "extern void x; void* y = &x;". 10012 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10013 } 10014 10015 // If the operand has type "type", the result has type "pointer to type". 10016 if (op->getType()->isObjCObjectType()) 10017 return Context.getObjCObjectPointerType(op->getType()); 10018 return Context.getPointerType(op->getType()); 10019 } 10020 10021 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10022 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10023 if (!DRE) 10024 return; 10025 const Decl *D = DRE->getDecl(); 10026 if (!D) 10027 return; 10028 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10029 if (!Param) 10030 return; 10031 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10032 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10033 return; 10034 if (FunctionScopeInfo *FD = S.getCurFunction()) 10035 if (!FD->ModifiedNonNullParams.count(Param)) 10036 FD->ModifiedNonNullParams.insert(Param); 10037 } 10038 10039 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10040 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10041 SourceLocation OpLoc) { 10042 if (Op->isTypeDependent()) 10043 return S.Context.DependentTy; 10044 10045 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10046 if (ConvResult.isInvalid()) 10047 return QualType(); 10048 Op = ConvResult.get(); 10049 QualType OpTy = Op->getType(); 10050 QualType Result; 10051 10052 if (isa<CXXReinterpretCastExpr>(Op)) { 10053 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10054 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10055 Op->getSourceRange()); 10056 } 10057 10058 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10059 Result = PT->getPointeeType(); 10060 else if (const ObjCObjectPointerType *OPT = 10061 OpTy->getAs<ObjCObjectPointerType>()) 10062 Result = OPT->getPointeeType(); 10063 else { 10064 ExprResult PR = S.CheckPlaceholderExpr(Op); 10065 if (PR.isInvalid()) return QualType(); 10066 if (PR.get() != Op) 10067 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10068 } 10069 10070 if (Result.isNull()) { 10071 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10072 << OpTy << Op->getSourceRange(); 10073 return QualType(); 10074 } 10075 10076 // Note that per both C89 and C99, indirection is always legal, even if Result 10077 // is an incomplete type or void. It would be possible to warn about 10078 // dereferencing a void pointer, but it's completely well-defined, and such a 10079 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10080 // for pointers to 'void' but is fine for any other pointer type: 10081 // 10082 // C++ [expr.unary.op]p1: 10083 // [...] the expression to which [the unary * operator] is applied shall 10084 // be a pointer to an object type, or a pointer to a function type 10085 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10086 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10087 << OpTy << Op->getSourceRange(); 10088 10089 // Dereferences are usually l-values... 10090 VK = VK_LValue; 10091 10092 // ...except that certain expressions are never l-values in C. 10093 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10094 VK = VK_RValue; 10095 10096 return Result; 10097 } 10098 10099 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10100 BinaryOperatorKind Opc; 10101 switch (Kind) { 10102 default: llvm_unreachable("Unknown binop!"); 10103 case tok::periodstar: Opc = BO_PtrMemD; break; 10104 case tok::arrowstar: Opc = BO_PtrMemI; break; 10105 case tok::star: Opc = BO_Mul; break; 10106 case tok::slash: Opc = BO_Div; break; 10107 case tok::percent: Opc = BO_Rem; break; 10108 case tok::plus: Opc = BO_Add; break; 10109 case tok::minus: Opc = BO_Sub; break; 10110 case tok::lessless: Opc = BO_Shl; break; 10111 case tok::greatergreater: Opc = BO_Shr; break; 10112 case tok::lessequal: Opc = BO_LE; break; 10113 case tok::less: Opc = BO_LT; break; 10114 case tok::greaterequal: Opc = BO_GE; break; 10115 case tok::greater: Opc = BO_GT; break; 10116 case tok::exclaimequal: Opc = BO_NE; break; 10117 case tok::equalequal: Opc = BO_EQ; break; 10118 case tok::amp: Opc = BO_And; break; 10119 case tok::caret: Opc = BO_Xor; break; 10120 case tok::pipe: Opc = BO_Or; break; 10121 case tok::ampamp: Opc = BO_LAnd; break; 10122 case tok::pipepipe: Opc = BO_LOr; break; 10123 case tok::equal: Opc = BO_Assign; break; 10124 case tok::starequal: Opc = BO_MulAssign; break; 10125 case tok::slashequal: Opc = BO_DivAssign; break; 10126 case tok::percentequal: Opc = BO_RemAssign; break; 10127 case tok::plusequal: Opc = BO_AddAssign; break; 10128 case tok::minusequal: Opc = BO_SubAssign; break; 10129 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10130 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10131 case tok::ampequal: Opc = BO_AndAssign; break; 10132 case tok::caretequal: Opc = BO_XorAssign; break; 10133 case tok::pipeequal: Opc = BO_OrAssign; break; 10134 case tok::comma: Opc = BO_Comma; break; 10135 } 10136 return Opc; 10137 } 10138 10139 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10140 tok::TokenKind Kind) { 10141 UnaryOperatorKind Opc; 10142 switch (Kind) { 10143 default: llvm_unreachable("Unknown unary op!"); 10144 case tok::plusplus: Opc = UO_PreInc; break; 10145 case tok::minusminus: Opc = UO_PreDec; break; 10146 case tok::amp: Opc = UO_AddrOf; break; 10147 case tok::star: Opc = UO_Deref; break; 10148 case tok::plus: Opc = UO_Plus; break; 10149 case tok::minus: Opc = UO_Minus; break; 10150 case tok::tilde: Opc = UO_Not; break; 10151 case tok::exclaim: Opc = UO_LNot; break; 10152 case tok::kw___real: Opc = UO_Real; break; 10153 case tok::kw___imag: Opc = UO_Imag; break; 10154 case tok::kw___extension__: Opc = UO_Extension; break; 10155 } 10156 return Opc; 10157 } 10158 10159 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10160 /// This warning is only emitted for builtin assignment operations. It is also 10161 /// suppressed in the event of macro expansions. 10162 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10163 SourceLocation OpLoc) { 10164 if (!S.ActiveTemplateInstantiations.empty()) 10165 return; 10166 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10167 return; 10168 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10169 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10170 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10171 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10172 if (!LHSDeclRef || !RHSDeclRef || 10173 LHSDeclRef->getLocation().isMacroID() || 10174 RHSDeclRef->getLocation().isMacroID()) 10175 return; 10176 const ValueDecl *LHSDecl = 10177 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10178 const ValueDecl *RHSDecl = 10179 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10180 if (LHSDecl != RHSDecl) 10181 return; 10182 if (LHSDecl->getType().isVolatileQualified()) 10183 return; 10184 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10185 if (RefTy->getPointeeType().isVolatileQualified()) 10186 return; 10187 10188 S.Diag(OpLoc, diag::warn_self_assignment) 10189 << LHSDeclRef->getType() 10190 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10191 } 10192 10193 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10194 /// is usually indicative of introspection within the Objective-C pointer. 10195 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10196 SourceLocation OpLoc) { 10197 if (!S.getLangOpts().ObjC1) 10198 return; 10199 10200 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10201 const Expr *LHS = L.get(); 10202 const Expr *RHS = R.get(); 10203 10204 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10205 ObjCPointerExpr = LHS; 10206 OtherExpr = RHS; 10207 } 10208 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10209 ObjCPointerExpr = RHS; 10210 OtherExpr = LHS; 10211 } 10212 10213 // This warning is deliberately made very specific to reduce false 10214 // positives with logic that uses '&' for hashing. This logic mainly 10215 // looks for code trying to introspect into tagged pointers, which 10216 // code should generally never do. 10217 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10218 unsigned Diag = diag::warn_objc_pointer_masking; 10219 // Determine if we are introspecting the result of performSelectorXXX. 10220 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10221 // Special case messages to -performSelector and friends, which 10222 // can return non-pointer values boxed in a pointer value. 10223 // Some clients may wish to silence warnings in this subcase. 10224 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10225 Selector S = ME->getSelector(); 10226 StringRef SelArg0 = S.getNameForSlot(0); 10227 if (SelArg0.startswith("performSelector")) 10228 Diag = diag::warn_objc_pointer_masking_performSelector; 10229 } 10230 10231 S.Diag(OpLoc, Diag) 10232 << ObjCPointerExpr->getSourceRange(); 10233 } 10234 } 10235 10236 static NamedDecl *getDeclFromExpr(Expr *E) { 10237 if (!E) 10238 return nullptr; 10239 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10240 return DRE->getDecl(); 10241 if (auto *ME = dyn_cast<MemberExpr>(E)) 10242 return ME->getMemberDecl(); 10243 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10244 return IRE->getDecl(); 10245 return nullptr; 10246 } 10247 10248 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10249 /// operator @p Opc at location @c TokLoc. This routine only supports 10250 /// built-in operations; ActOnBinOp handles overloaded operators. 10251 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10252 BinaryOperatorKind Opc, 10253 Expr *LHSExpr, Expr *RHSExpr) { 10254 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10255 // The syntax only allows initializer lists on the RHS of assignment, 10256 // so we don't need to worry about accepting invalid code for 10257 // non-assignment operators. 10258 // C++11 5.17p9: 10259 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10260 // of x = {} is x = T(). 10261 InitializationKind Kind = 10262 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10263 InitializedEntity Entity = 10264 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10265 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10266 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10267 if (Init.isInvalid()) 10268 return Init; 10269 RHSExpr = Init.get(); 10270 } 10271 10272 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10273 QualType ResultTy; // Result type of the binary operator. 10274 // The following two variables are used for compound assignment operators 10275 QualType CompLHSTy; // Type of LHS after promotions for computation 10276 QualType CompResultTy; // Type of computation result 10277 ExprValueKind VK = VK_RValue; 10278 ExprObjectKind OK = OK_Ordinary; 10279 10280 if (!getLangOpts().CPlusPlus) { 10281 // C cannot handle TypoExpr nodes on either side of a binop because it 10282 // doesn't handle dependent types properly, so make sure any TypoExprs have 10283 // been dealt with before checking the operands. 10284 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10285 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10286 if (Opc != BO_Assign) 10287 return ExprResult(E); 10288 // Avoid correcting the RHS to the same Expr as the LHS. 10289 Decl *D = getDeclFromExpr(E); 10290 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10291 }); 10292 if (!LHS.isUsable() || !RHS.isUsable()) 10293 return ExprError(); 10294 } 10295 10296 if (getLangOpts().OpenCL) { 10297 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10298 // the ATOMIC_VAR_INIT macro. 10299 if (LHSExpr->getType()->isAtomicType() || 10300 RHSExpr->getType()->isAtomicType()) { 10301 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10302 if (BO_Assign == Opc) 10303 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10304 else 10305 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10306 return ExprError(); 10307 } 10308 } 10309 10310 switch (Opc) { 10311 case BO_Assign: 10312 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10313 if (getLangOpts().CPlusPlus && 10314 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10315 VK = LHS.get()->getValueKind(); 10316 OK = LHS.get()->getObjectKind(); 10317 } 10318 if (!ResultTy.isNull()) { 10319 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10320 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10321 } 10322 RecordModifiableNonNullParam(*this, LHS.get()); 10323 break; 10324 case BO_PtrMemD: 10325 case BO_PtrMemI: 10326 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10327 Opc == BO_PtrMemI); 10328 break; 10329 case BO_Mul: 10330 case BO_Div: 10331 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10332 Opc == BO_Div); 10333 break; 10334 case BO_Rem: 10335 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10336 break; 10337 case BO_Add: 10338 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10339 break; 10340 case BO_Sub: 10341 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10342 break; 10343 case BO_Shl: 10344 case BO_Shr: 10345 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10346 break; 10347 case BO_LE: 10348 case BO_LT: 10349 case BO_GE: 10350 case BO_GT: 10351 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10352 break; 10353 case BO_EQ: 10354 case BO_NE: 10355 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10356 break; 10357 case BO_And: 10358 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10359 case BO_Xor: 10360 case BO_Or: 10361 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10362 break; 10363 case BO_LAnd: 10364 case BO_LOr: 10365 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10366 break; 10367 case BO_MulAssign: 10368 case BO_DivAssign: 10369 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10370 Opc == BO_DivAssign); 10371 CompLHSTy = CompResultTy; 10372 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10373 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10374 break; 10375 case BO_RemAssign: 10376 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10377 CompLHSTy = CompResultTy; 10378 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10379 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10380 break; 10381 case BO_AddAssign: 10382 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10383 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10384 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10385 break; 10386 case BO_SubAssign: 10387 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10388 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10389 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10390 break; 10391 case BO_ShlAssign: 10392 case BO_ShrAssign: 10393 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10394 CompLHSTy = CompResultTy; 10395 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10396 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10397 break; 10398 case BO_AndAssign: 10399 case BO_OrAssign: // fallthrough 10400 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10401 case BO_XorAssign: 10402 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10403 CompLHSTy = CompResultTy; 10404 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10405 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10406 break; 10407 case BO_Comma: 10408 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10409 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10410 VK = RHS.get()->getValueKind(); 10411 OK = RHS.get()->getObjectKind(); 10412 } 10413 break; 10414 } 10415 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10416 return ExprError(); 10417 10418 // Check for array bounds violations for both sides of the BinaryOperator 10419 CheckArrayAccess(LHS.get()); 10420 CheckArrayAccess(RHS.get()); 10421 10422 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10423 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10424 &Context.Idents.get("object_setClass"), 10425 SourceLocation(), LookupOrdinaryName); 10426 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10427 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 10428 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10429 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10430 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10431 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10432 } 10433 else 10434 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10435 } 10436 else if (const ObjCIvarRefExpr *OIRE = 10437 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10438 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10439 10440 if (CompResultTy.isNull()) 10441 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10442 OK, OpLoc, FPFeatures.fp_contract); 10443 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10444 OK_ObjCProperty) { 10445 VK = VK_LValue; 10446 OK = LHS.get()->getObjectKind(); 10447 } 10448 return new (Context) CompoundAssignOperator( 10449 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10450 OpLoc, FPFeatures.fp_contract); 10451 } 10452 10453 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10454 /// operators are mixed in a way that suggests that the programmer forgot that 10455 /// comparison operators have higher precedence. The most typical example of 10456 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10457 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10458 SourceLocation OpLoc, Expr *LHSExpr, 10459 Expr *RHSExpr) { 10460 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10461 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10462 10463 // Check that one of the sides is a comparison operator. 10464 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10465 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10466 if (!isLeftComp && !isRightComp) 10467 return; 10468 10469 // Bitwise operations are sometimes used as eager logical ops. 10470 // Don't diagnose this. 10471 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10472 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10473 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 10474 return; 10475 10476 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10477 OpLoc) 10478 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10479 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10480 SourceRange ParensRange = isLeftComp ? 10481 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10482 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10483 10484 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10485 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10486 SuggestParentheses(Self, OpLoc, 10487 Self.PDiag(diag::note_precedence_silence) << OpStr, 10488 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10489 SuggestParentheses(Self, OpLoc, 10490 Self.PDiag(diag::note_precedence_bitwise_first) 10491 << BinaryOperator::getOpcodeStr(Opc), 10492 ParensRange); 10493 } 10494 10495 /// \brief It accepts a '&' expr that is inside a '|' one. 10496 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 10497 /// in parentheses. 10498 static void 10499 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 10500 BinaryOperator *Bop) { 10501 assert(Bop->getOpcode() == BO_And); 10502 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 10503 << Bop->getSourceRange() << OpLoc; 10504 SuggestParentheses(Self, Bop->getOperatorLoc(), 10505 Self.PDiag(diag::note_precedence_silence) 10506 << Bop->getOpcodeStr(), 10507 Bop->getSourceRange()); 10508 } 10509 10510 /// \brief It accepts a '&&' expr that is inside a '||' one. 10511 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10512 /// in parentheses. 10513 static void 10514 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10515 BinaryOperator *Bop) { 10516 assert(Bop->getOpcode() == BO_LAnd); 10517 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10518 << Bop->getSourceRange() << OpLoc; 10519 SuggestParentheses(Self, Bop->getOperatorLoc(), 10520 Self.PDiag(diag::note_precedence_silence) 10521 << Bop->getOpcodeStr(), 10522 Bop->getSourceRange()); 10523 } 10524 10525 /// \brief Returns true if the given expression can be evaluated as a constant 10526 /// 'true'. 10527 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10528 bool Res; 10529 return !E->isValueDependent() && 10530 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10531 } 10532 10533 /// \brief Returns true if the given expression can be evaluated as a constant 10534 /// 'false'. 10535 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10536 bool Res; 10537 return !E->isValueDependent() && 10538 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10539 } 10540 10541 /// \brief Look for '&&' in the left hand of a '||' expr. 10542 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10543 Expr *LHSExpr, Expr *RHSExpr) { 10544 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10545 if (Bop->getOpcode() == BO_LAnd) { 10546 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10547 if (EvaluatesAsFalse(S, RHSExpr)) 10548 return; 10549 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10550 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10551 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10552 } else if (Bop->getOpcode() == BO_LOr) { 10553 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10554 // If it's "a || b && 1 || c" we didn't warn earlier for 10555 // "a || b && 1", but warn now. 10556 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10557 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10558 } 10559 } 10560 } 10561 } 10562 10563 /// \brief Look for '&&' in the right hand of a '||' expr. 10564 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10565 Expr *LHSExpr, Expr *RHSExpr) { 10566 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10567 if (Bop->getOpcode() == BO_LAnd) { 10568 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10569 if (EvaluatesAsFalse(S, LHSExpr)) 10570 return; 10571 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10572 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10573 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10574 } 10575 } 10576 } 10577 10578 /// \brief Look for '&' in the left or right hand of a '|' expr. 10579 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 10580 Expr *OrArg) { 10581 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 10582 if (Bop->getOpcode() == BO_And) 10583 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 10584 } 10585 } 10586 10587 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10588 Expr *SubExpr, StringRef Shift) { 10589 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10590 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10591 StringRef Op = Bop->getOpcodeStr(); 10592 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10593 << Bop->getSourceRange() << OpLoc << Shift << Op; 10594 SuggestParentheses(S, Bop->getOperatorLoc(), 10595 S.PDiag(diag::note_precedence_silence) << Op, 10596 Bop->getSourceRange()); 10597 } 10598 } 10599 } 10600 10601 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10602 Expr *LHSExpr, Expr *RHSExpr) { 10603 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10604 if (!OCE) 10605 return; 10606 10607 FunctionDecl *FD = OCE->getDirectCallee(); 10608 if (!FD || !FD->isOverloadedOperator()) 10609 return; 10610 10611 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10612 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10613 return; 10614 10615 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10616 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10617 << (Kind == OO_LessLess); 10618 SuggestParentheses(S, OCE->getOperatorLoc(), 10619 S.PDiag(diag::note_precedence_silence) 10620 << (Kind == OO_LessLess ? "<<" : ">>"), 10621 OCE->getSourceRange()); 10622 SuggestParentheses(S, OpLoc, 10623 S.PDiag(diag::note_evaluate_comparison_first), 10624 SourceRange(OCE->getArg(1)->getLocStart(), 10625 RHSExpr->getLocEnd())); 10626 } 10627 10628 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10629 /// precedence. 10630 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10631 SourceLocation OpLoc, Expr *LHSExpr, 10632 Expr *RHSExpr){ 10633 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10634 if (BinaryOperator::isBitwiseOp(Opc)) 10635 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10636 10637 // Diagnose "arg1 & arg2 | arg3" 10638 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10639 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 10640 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 10641 } 10642 10643 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10644 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10645 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10646 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10647 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10648 } 10649 10650 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 10651 || Opc == BO_Shr) { 10652 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 10653 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 10654 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 10655 } 10656 10657 // Warn on overloaded shift operators and comparisons, such as: 10658 // cout << 5 == 4; 10659 if (BinaryOperator::isComparisonOp(Opc)) 10660 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 10661 } 10662 10663 // Binary Operators. 'Tok' is the token for the operator. 10664 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 10665 tok::TokenKind Kind, 10666 Expr *LHSExpr, Expr *RHSExpr) { 10667 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 10668 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 10669 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 10670 10671 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 10672 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 10673 10674 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 10675 } 10676 10677 /// Build an overloaded binary operator expression in the given scope. 10678 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 10679 BinaryOperatorKind Opc, 10680 Expr *LHS, Expr *RHS) { 10681 // Find all of the overloaded operators visible from this 10682 // point. We perform both an operator-name lookup from the local 10683 // scope and an argument-dependent lookup based on the types of 10684 // the arguments. 10685 UnresolvedSet<16> Functions; 10686 OverloadedOperatorKind OverOp 10687 = BinaryOperator::getOverloadedOperator(Opc); 10688 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 10689 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 10690 RHS->getType(), Functions); 10691 10692 // Build the (potentially-overloaded, potentially-dependent) 10693 // binary operation. 10694 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 10695 } 10696 10697 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 10698 BinaryOperatorKind Opc, 10699 Expr *LHSExpr, Expr *RHSExpr) { 10700 // We want to end up calling one of checkPseudoObjectAssignment 10701 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 10702 // both expressions are overloadable or either is type-dependent), 10703 // or CreateBuiltinBinOp (in any other case). We also want to get 10704 // any placeholder types out of the way. 10705 10706 // Handle pseudo-objects in the LHS. 10707 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 10708 // Assignments with a pseudo-object l-value need special analysis. 10709 if (pty->getKind() == BuiltinType::PseudoObject && 10710 BinaryOperator::isAssignmentOp(Opc)) 10711 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 10712 10713 // Don't resolve overloads if the other type is overloadable. 10714 if (pty->getKind() == BuiltinType::Overload) { 10715 // We can't actually test that if we still have a placeholder, 10716 // though. Fortunately, none of the exceptions we see in that 10717 // code below are valid when the LHS is an overload set. Note 10718 // that an overload set can be dependently-typed, but it never 10719 // instantiates to having an overloadable type. 10720 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10721 if (resolvedRHS.isInvalid()) return ExprError(); 10722 RHSExpr = resolvedRHS.get(); 10723 10724 if (RHSExpr->isTypeDependent() || 10725 RHSExpr->getType()->isOverloadableType()) 10726 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10727 } 10728 10729 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 10730 if (LHS.isInvalid()) return ExprError(); 10731 LHSExpr = LHS.get(); 10732 } 10733 10734 // Handle pseudo-objects in the RHS. 10735 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 10736 // An overload in the RHS can potentially be resolved by the type 10737 // being assigned to. 10738 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 10739 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10740 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10741 10742 if (LHSExpr->getType()->isOverloadableType()) 10743 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10744 10745 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10746 } 10747 10748 // Don't resolve overloads if the other type is overloadable. 10749 if (pty->getKind() == BuiltinType::Overload && 10750 LHSExpr->getType()->isOverloadableType()) 10751 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10752 10753 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10754 if (!resolvedRHS.isUsable()) return ExprError(); 10755 RHSExpr = resolvedRHS.get(); 10756 } 10757 10758 if (getLangOpts().CPlusPlus) { 10759 // If either expression is type-dependent, always build an 10760 // overloaded op. 10761 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10762 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10763 10764 // Otherwise, build an overloaded op if either expression has an 10765 // overloadable type. 10766 if (LHSExpr->getType()->isOverloadableType() || 10767 RHSExpr->getType()->isOverloadableType()) 10768 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10769 } 10770 10771 // Build a built-in binary operation. 10772 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10773 } 10774 10775 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 10776 UnaryOperatorKind Opc, 10777 Expr *InputExpr) { 10778 ExprResult Input = InputExpr; 10779 ExprValueKind VK = VK_RValue; 10780 ExprObjectKind OK = OK_Ordinary; 10781 QualType resultType; 10782 if (getLangOpts().OpenCL) { 10783 // The only legal unary operation for atomics is '&'. 10784 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 10785 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10786 << InputExpr->getType() 10787 << Input.get()->getSourceRange()); 10788 } 10789 } 10790 switch (Opc) { 10791 case UO_PreInc: 10792 case UO_PreDec: 10793 case UO_PostInc: 10794 case UO_PostDec: 10795 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 10796 OpLoc, 10797 Opc == UO_PreInc || 10798 Opc == UO_PostInc, 10799 Opc == UO_PreInc || 10800 Opc == UO_PreDec); 10801 break; 10802 case UO_AddrOf: 10803 resultType = CheckAddressOfOperand(Input, OpLoc); 10804 RecordModifiableNonNullParam(*this, InputExpr); 10805 break; 10806 case UO_Deref: { 10807 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10808 if (Input.isInvalid()) return ExprError(); 10809 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 10810 break; 10811 } 10812 case UO_Plus: 10813 case UO_Minus: 10814 Input = UsualUnaryConversions(Input.get()); 10815 if (Input.isInvalid()) return ExprError(); 10816 resultType = Input.get()->getType(); 10817 if (resultType->isDependentType()) 10818 break; 10819 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 10820 break; 10821 else if (resultType->isVectorType() && 10822 // The z vector extensions don't allow + or - with bool vectors. 10823 (!Context.getLangOpts().ZVector || 10824 resultType->getAs<VectorType>()->getVectorKind() != 10825 VectorType::AltiVecBool)) 10826 break; 10827 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 10828 Opc == UO_Plus && 10829 resultType->isPointerType()) 10830 break; 10831 10832 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10833 << resultType << Input.get()->getSourceRange()); 10834 10835 case UO_Not: // bitwise complement 10836 Input = UsualUnaryConversions(Input.get()); 10837 if (Input.isInvalid()) 10838 return ExprError(); 10839 resultType = Input.get()->getType(); 10840 if (resultType->isDependentType()) 10841 break; 10842 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 10843 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 10844 // C99 does not support '~' for complex conjugation. 10845 Diag(OpLoc, diag::ext_integer_complement_complex) 10846 << resultType << Input.get()->getSourceRange(); 10847 else if (resultType->hasIntegerRepresentation()) 10848 break; 10849 else if (resultType->isExtVectorType()) { 10850 if (Context.getLangOpts().OpenCL) { 10851 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 10852 // on vector float types. 10853 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10854 if (!T->isIntegerType()) 10855 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10856 << resultType << Input.get()->getSourceRange()); 10857 } 10858 break; 10859 } else { 10860 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10861 << resultType << Input.get()->getSourceRange()); 10862 } 10863 break; 10864 10865 case UO_LNot: // logical negation 10866 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 10867 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10868 if (Input.isInvalid()) return ExprError(); 10869 resultType = Input.get()->getType(); 10870 10871 // Though we still have to promote half FP to float... 10872 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 10873 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 10874 resultType = Context.FloatTy; 10875 } 10876 10877 if (resultType->isDependentType()) 10878 break; 10879 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 10880 // C99 6.5.3.3p1: ok, fallthrough; 10881 if (Context.getLangOpts().CPlusPlus) { 10882 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 10883 // operand contextually converted to bool. 10884 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 10885 ScalarTypeToBooleanCastKind(resultType)); 10886 } else if (Context.getLangOpts().OpenCL && 10887 Context.getLangOpts().OpenCLVersion < 120) { 10888 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10889 // operate on scalar float types. 10890 if (!resultType->isIntegerType()) 10891 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10892 << resultType << Input.get()->getSourceRange()); 10893 } 10894 } else if (resultType->isExtVectorType()) { 10895 if (Context.getLangOpts().OpenCL && 10896 Context.getLangOpts().OpenCLVersion < 120) { 10897 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10898 // operate on vector float types. 10899 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10900 if (!T->isIntegerType()) 10901 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10902 << resultType << Input.get()->getSourceRange()); 10903 } 10904 // Vector logical not returns the signed variant of the operand type. 10905 resultType = GetSignedVectorType(resultType); 10906 break; 10907 } else { 10908 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10909 << resultType << Input.get()->getSourceRange()); 10910 } 10911 10912 // LNot always has type int. C99 6.5.3.3p5. 10913 // In C++, it's bool. C++ 5.3.1p8 10914 resultType = Context.getLogicalOperationType(); 10915 break; 10916 case UO_Real: 10917 case UO_Imag: 10918 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 10919 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 10920 // complex l-values to ordinary l-values and all other values to r-values. 10921 if (Input.isInvalid()) return ExprError(); 10922 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 10923 if (Input.get()->getValueKind() != VK_RValue && 10924 Input.get()->getObjectKind() == OK_Ordinary) 10925 VK = Input.get()->getValueKind(); 10926 } else if (!getLangOpts().CPlusPlus) { 10927 // In C, a volatile scalar is read by __imag. In C++, it is not. 10928 Input = DefaultLvalueConversion(Input.get()); 10929 } 10930 break; 10931 case UO_Extension: 10932 case UO_Coawait: 10933 resultType = Input.get()->getType(); 10934 VK = Input.get()->getValueKind(); 10935 OK = Input.get()->getObjectKind(); 10936 break; 10937 } 10938 if (resultType.isNull() || Input.isInvalid()) 10939 return ExprError(); 10940 10941 // Check for array bounds violations in the operand of the UnaryOperator, 10942 // except for the '*' and '&' operators that have to be handled specially 10943 // by CheckArrayAccess (as there are special cases like &array[arraysize] 10944 // that are explicitly defined as valid by the standard). 10945 if (Opc != UO_AddrOf && Opc != UO_Deref) 10946 CheckArrayAccess(Input.get()); 10947 10948 return new (Context) 10949 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 10950 } 10951 10952 /// \brief Determine whether the given expression is a qualified member 10953 /// access expression, of a form that could be turned into a pointer to member 10954 /// with the address-of operator. 10955 static bool isQualifiedMemberAccess(Expr *E) { 10956 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10957 if (!DRE->getQualifier()) 10958 return false; 10959 10960 ValueDecl *VD = DRE->getDecl(); 10961 if (!VD->isCXXClassMember()) 10962 return false; 10963 10964 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 10965 return true; 10966 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 10967 return Method->isInstance(); 10968 10969 return false; 10970 } 10971 10972 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 10973 if (!ULE->getQualifier()) 10974 return false; 10975 10976 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 10977 DEnd = ULE->decls_end(); 10978 D != DEnd; ++D) { 10979 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 10980 if (Method->isInstance()) 10981 return true; 10982 } else { 10983 // Overload set does not contain methods. 10984 break; 10985 } 10986 } 10987 10988 return false; 10989 } 10990 10991 return false; 10992 } 10993 10994 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 10995 UnaryOperatorKind Opc, Expr *Input) { 10996 // First things first: handle placeholders so that the 10997 // overloaded-operator check considers the right type. 10998 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 10999 // Increment and decrement of pseudo-object references. 11000 if (pty->getKind() == BuiltinType::PseudoObject && 11001 UnaryOperator::isIncrementDecrementOp(Opc)) 11002 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11003 11004 // extension is always a builtin operator. 11005 if (Opc == UO_Extension) 11006 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11007 11008 // & gets special logic for several kinds of placeholder. 11009 // The builtin code knows what to do. 11010 if (Opc == UO_AddrOf && 11011 (pty->getKind() == BuiltinType::Overload || 11012 pty->getKind() == BuiltinType::UnknownAny || 11013 pty->getKind() == BuiltinType::BoundMember)) 11014 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11015 11016 // Anything else needs to be handled now. 11017 ExprResult Result = CheckPlaceholderExpr(Input); 11018 if (Result.isInvalid()) return ExprError(); 11019 Input = Result.get(); 11020 } 11021 11022 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11023 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11024 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11025 // Find all of the overloaded operators visible from this 11026 // point. We perform both an operator-name lookup from the local 11027 // scope and an argument-dependent lookup based on the types of 11028 // the arguments. 11029 UnresolvedSet<16> Functions; 11030 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11031 if (S && OverOp != OO_None) 11032 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11033 Functions); 11034 11035 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11036 } 11037 11038 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11039 } 11040 11041 // Unary Operators. 'Tok' is the token for the operator. 11042 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11043 tok::TokenKind Op, Expr *Input) { 11044 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11045 } 11046 11047 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11048 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11049 LabelDecl *TheDecl) { 11050 TheDecl->markUsed(Context); 11051 // Create the AST node. The address of a label always has type 'void*'. 11052 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11053 Context.getPointerType(Context.VoidTy)); 11054 } 11055 11056 /// Given the last statement in a statement-expression, check whether 11057 /// the result is a producing expression (like a call to an 11058 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11059 /// release out of the full-expression. Otherwise, return null. 11060 /// Cannot fail. 11061 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11062 // Should always be wrapped with one of these. 11063 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11064 if (!cleanups) return nullptr; 11065 11066 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11067 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11068 return nullptr; 11069 11070 // Splice out the cast. This shouldn't modify any interesting 11071 // features of the statement. 11072 Expr *producer = cast->getSubExpr(); 11073 assert(producer->getType() == cast->getType()); 11074 assert(producer->getValueKind() == cast->getValueKind()); 11075 cleanups->setSubExpr(producer); 11076 return cleanups; 11077 } 11078 11079 void Sema::ActOnStartStmtExpr() { 11080 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11081 } 11082 11083 void Sema::ActOnStmtExprError() { 11084 // Note that function is also called by TreeTransform when leaving a 11085 // StmtExpr scope without rebuilding anything. 11086 11087 DiscardCleanupsInEvaluationContext(); 11088 PopExpressionEvaluationContext(); 11089 } 11090 11091 ExprResult 11092 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11093 SourceLocation RPLoc) { // "({..})" 11094 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11095 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11096 11097 if (hasAnyUnrecoverableErrorsInThisFunction()) 11098 DiscardCleanupsInEvaluationContext(); 11099 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11100 PopExpressionEvaluationContext(); 11101 11102 // FIXME: there are a variety of strange constraints to enforce here, for 11103 // example, it is not possible to goto into a stmt expression apparently. 11104 // More semantic analysis is needed. 11105 11106 // If there are sub-stmts in the compound stmt, take the type of the last one 11107 // as the type of the stmtexpr. 11108 QualType Ty = Context.VoidTy; 11109 bool StmtExprMayBindToTemp = false; 11110 if (!Compound->body_empty()) { 11111 Stmt *LastStmt = Compound->body_back(); 11112 LabelStmt *LastLabelStmt = nullptr; 11113 // If LastStmt is a label, skip down through into the body. 11114 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11115 LastLabelStmt = Label; 11116 LastStmt = Label->getSubStmt(); 11117 } 11118 11119 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11120 // Do function/array conversion on the last expression, but not 11121 // lvalue-to-rvalue. However, initialize an unqualified type. 11122 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11123 if (LastExpr.isInvalid()) 11124 return ExprError(); 11125 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11126 11127 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11128 // In ARC, if the final expression ends in a consume, splice 11129 // the consume out and bind it later. In the alternate case 11130 // (when dealing with a retainable type), the result 11131 // initialization will create a produce. In both cases the 11132 // result will be +1, and we'll need to balance that out with 11133 // a bind. 11134 if (Expr *rebuiltLastStmt 11135 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11136 LastExpr = rebuiltLastStmt; 11137 } else { 11138 LastExpr = PerformCopyInitialization( 11139 InitializedEntity::InitializeResult(LPLoc, 11140 Ty, 11141 false), 11142 SourceLocation(), 11143 LastExpr); 11144 } 11145 11146 if (LastExpr.isInvalid()) 11147 return ExprError(); 11148 if (LastExpr.get() != nullptr) { 11149 if (!LastLabelStmt) 11150 Compound->setLastStmt(LastExpr.get()); 11151 else 11152 LastLabelStmt->setSubStmt(LastExpr.get()); 11153 StmtExprMayBindToTemp = true; 11154 } 11155 } 11156 } 11157 } 11158 11159 // FIXME: Check that expression type is complete/non-abstract; statement 11160 // expressions are not lvalues. 11161 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11162 if (StmtExprMayBindToTemp) 11163 return MaybeBindToTemporary(ResStmtExpr); 11164 return ResStmtExpr; 11165 } 11166 11167 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11168 TypeSourceInfo *TInfo, 11169 ArrayRef<OffsetOfComponent> Components, 11170 SourceLocation RParenLoc) { 11171 QualType ArgTy = TInfo->getType(); 11172 bool Dependent = ArgTy->isDependentType(); 11173 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11174 11175 // We must have at least one component that refers to the type, and the first 11176 // one is known to be a field designator. Verify that the ArgTy represents 11177 // a struct/union/class. 11178 if (!Dependent && !ArgTy->isRecordType()) 11179 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11180 << ArgTy << TypeRange); 11181 11182 // Type must be complete per C99 7.17p3 because a declaring a variable 11183 // with an incomplete type would be ill-formed. 11184 if (!Dependent 11185 && RequireCompleteType(BuiltinLoc, ArgTy, 11186 diag::err_offsetof_incomplete_type, TypeRange)) 11187 return ExprError(); 11188 11189 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11190 // GCC extension, diagnose them. 11191 // FIXME: This diagnostic isn't actually visible because the location is in 11192 // a system header! 11193 if (Components.size() != 1) 11194 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11195 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11196 11197 bool DidWarnAboutNonPOD = false; 11198 QualType CurrentType = ArgTy; 11199 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 11200 SmallVector<OffsetOfNode, 4> Comps; 11201 SmallVector<Expr*, 4> Exprs; 11202 for (const OffsetOfComponent &OC : Components) { 11203 if (OC.isBrackets) { 11204 // Offset of an array sub-field. TODO: Should we allow vector elements? 11205 if (!CurrentType->isDependentType()) { 11206 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11207 if(!AT) 11208 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11209 << CurrentType); 11210 CurrentType = AT->getElementType(); 11211 } else 11212 CurrentType = Context.DependentTy; 11213 11214 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11215 if (IdxRval.isInvalid()) 11216 return ExprError(); 11217 Expr *Idx = IdxRval.get(); 11218 11219 // The expression must be an integral expression. 11220 // FIXME: An integral constant expression? 11221 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11222 !Idx->getType()->isIntegerType()) 11223 return ExprError(Diag(Idx->getLocStart(), 11224 diag::err_typecheck_subscript_not_integer) 11225 << Idx->getSourceRange()); 11226 11227 // Record this array index. 11228 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11229 Exprs.push_back(Idx); 11230 continue; 11231 } 11232 11233 // Offset of a field. 11234 if (CurrentType->isDependentType()) { 11235 // We have the offset of a field, but we can't look into the dependent 11236 // type. Just record the identifier of the field. 11237 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11238 CurrentType = Context.DependentTy; 11239 continue; 11240 } 11241 11242 // We need to have a complete type to look into. 11243 if (RequireCompleteType(OC.LocStart, CurrentType, 11244 diag::err_offsetof_incomplete_type)) 11245 return ExprError(); 11246 11247 // Look for the designated field. 11248 const RecordType *RC = CurrentType->getAs<RecordType>(); 11249 if (!RC) 11250 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11251 << CurrentType); 11252 RecordDecl *RD = RC->getDecl(); 11253 11254 // C++ [lib.support.types]p5: 11255 // The macro offsetof accepts a restricted set of type arguments in this 11256 // International Standard. type shall be a POD structure or a POD union 11257 // (clause 9). 11258 // C++11 [support.types]p4: 11259 // If type is not a standard-layout class (Clause 9), the results are 11260 // undefined. 11261 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11262 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11263 unsigned DiagID = 11264 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11265 : diag::ext_offsetof_non_pod_type; 11266 11267 if (!IsSafe && !DidWarnAboutNonPOD && 11268 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11269 PDiag(DiagID) 11270 << SourceRange(Components[0].LocStart, OC.LocEnd) 11271 << CurrentType)) 11272 DidWarnAboutNonPOD = true; 11273 } 11274 11275 // Look for the field. 11276 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11277 LookupQualifiedName(R, RD); 11278 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11279 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11280 if (!MemberDecl) { 11281 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11282 MemberDecl = IndirectMemberDecl->getAnonField(); 11283 } 11284 11285 if (!MemberDecl) 11286 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11287 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11288 OC.LocEnd)); 11289 11290 // C99 7.17p3: 11291 // (If the specified member is a bit-field, the behavior is undefined.) 11292 // 11293 // We diagnose this as an error. 11294 if (MemberDecl->isBitField()) { 11295 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11296 << MemberDecl->getDeclName() 11297 << SourceRange(BuiltinLoc, RParenLoc); 11298 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11299 return ExprError(); 11300 } 11301 11302 RecordDecl *Parent = MemberDecl->getParent(); 11303 if (IndirectMemberDecl) 11304 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11305 11306 // If the member was found in a base class, introduce OffsetOfNodes for 11307 // the base class indirections. 11308 CXXBasePaths Paths; 11309 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 11310 if (Paths.getDetectedVirtual()) { 11311 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11312 << MemberDecl->getDeclName() 11313 << SourceRange(BuiltinLoc, RParenLoc); 11314 return ExprError(); 11315 } 11316 11317 CXXBasePath &Path = Paths.front(); 11318 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 11319 B != BEnd; ++B) 11320 Comps.push_back(OffsetOfNode(B->Base)); 11321 } 11322 11323 if (IndirectMemberDecl) { 11324 for (auto *FI : IndirectMemberDecl->chain()) { 11325 assert(isa<FieldDecl>(FI)); 11326 Comps.push_back(OffsetOfNode(OC.LocStart, 11327 cast<FieldDecl>(FI), OC.LocEnd)); 11328 } 11329 } else 11330 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11331 11332 CurrentType = MemberDecl->getType().getNonReferenceType(); 11333 } 11334 11335 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11336 Comps, Exprs, RParenLoc); 11337 } 11338 11339 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11340 SourceLocation BuiltinLoc, 11341 SourceLocation TypeLoc, 11342 ParsedType ParsedArgTy, 11343 ArrayRef<OffsetOfComponent> Components, 11344 SourceLocation RParenLoc) { 11345 11346 TypeSourceInfo *ArgTInfo; 11347 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11348 if (ArgTy.isNull()) 11349 return ExprError(); 11350 11351 if (!ArgTInfo) 11352 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11353 11354 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11355 } 11356 11357 11358 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11359 Expr *CondExpr, 11360 Expr *LHSExpr, Expr *RHSExpr, 11361 SourceLocation RPLoc) { 11362 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11363 11364 ExprValueKind VK = VK_RValue; 11365 ExprObjectKind OK = OK_Ordinary; 11366 QualType resType; 11367 bool ValueDependent = false; 11368 bool CondIsTrue = false; 11369 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11370 resType = Context.DependentTy; 11371 ValueDependent = true; 11372 } else { 11373 // The conditional expression is required to be a constant expression. 11374 llvm::APSInt condEval(32); 11375 ExprResult CondICE 11376 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11377 diag::err_typecheck_choose_expr_requires_constant, false); 11378 if (CondICE.isInvalid()) 11379 return ExprError(); 11380 CondExpr = CondICE.get(); 11381 CondIsTrue = condEval.getZExtValue(); 11382 11383 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11384 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11385 11386 resType = ActiveExpr->getType(); 11387 ValueDependent = ActiveExpr->isValueDependent(); 11388 VK = ActiveExpr->getValueKind(); 11389 OK = ActiveExpr->getObjectKind(); 11390 } 11391 11392 return new (Context) 11393 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11394 CondIsTrue, resType->isDependentType(), ValueDependent); 11395 } 11396 11397 //===----------------------------------------------------------------------===// 11398 // Clang Extensions. 11399 //===----------------------------------------------------------------------===// 11400 11401 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11402 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11403 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11404 11405 if (LangOpts.CPlusPlus) { 11406 Decl *ManglingContextDecl; 11407 if (MangleNumberingContext *MCtx = 11408 getCurrentMangleNumberContext(Block->getDeclContext(), 11409 ManglingContextDecl)) { 11410 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11411 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11412 } 11413 } 11414 11415 PushBlockScope(CurScope, Block); 11416 CurContext->addDecl(Block); 11417 if (CurScope) 11418 PushDeclContext(CurScope, Block); 11419 else 11420 CurContext = Block; 11421 11422 getCurBlock()->HasImplicitReturnType = true; 11423 11424 // Enter a new evaluation context to insulate the block from any 11425 // cleanups from the enclosing full-expression. 11426 PushExpressionEvaluationContext(PotentiallyEvaluated); 11427 } 11428 11429 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11430 Scope *CurScope) { 11431 assert(ParamInfo.getIdentifier() == nullptr && 11432 "block-id should have no identifier!"); 11433 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11434 BlockScopeInfo *CurBlock = getCurBlock(); 11435 11436 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11437 QualType T = Sig->getType(); 11438 11439 // FIXME: We should allow unexpanded parameter packs here, but that would, 11440 // in turn, make the block expression contain unexpanded parameter packs. 11441 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11442 // Drop the parameters. 11443 FunctionProtoType::ExtProtoInfo EPI; 11444 EPI.HasTrailingReturn = false; 11445 EPI.TypeQuals |= DeclSpec::TQ_const; 11446 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11447 Sig = Context.getTrivialTypeSourceInfo(T); 11448 } 11449 11450 // GetTypeForDeclarator always produces a function type for a block 11451 // literal signature. Furthermore, it is always a FunctionProtoType 11452 // unless the function was written with a typedef. 11453 assert(T->isFunctionType() && 11454 "GetTypeForDeclarator made a non-function block signature"); 11455 11456 // Look for an explicit signature in that function type. 11457 FunctionProtoTypeLoc ExplicitSignature; 11458 11459 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11460 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11461 11462 // Check whether that explicit signature was synthesized by 11463 // GetTypeForDeclarator. If so, don't save that as part of the 11464 // written signature. 11465 if (ExplicitSignature.getLocalRangeBegin() == 11466 ExplicitSignature.getLocalRangeEnd()) { 11467 // This would be much cheaper if we stored TypeLocs instead of 11468 // TypeSourceInfos. 11469 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11470 unsigned Size = Result.getFullDataSize(); 11471 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11472 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11473 11474 ExplicitSignature = FunctionProtoTypeLoc(); 11475 } 11476 } 11477 11478 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11479 CurBlock->FunctionType = T; 11480 11481 const FunctionType *Fn = T->getAs<FunctionType>(); 11482 QualType RetTy = Fn->getReturnType(); 11483 bool isVariadic = 11484 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11485 11486 CurBlock->TheDecl->setIsVariadic(isVariadic); 11487 11488 // Context.DependentTy is used as a placeholder for a missing block 11489 // return type. TODO: what should we do with declarators like: 11490 // ^ * { ... } 11491 // If the answer is "apply template argument deduction".... 11492 if (RetTy != Context.DependentTy) { 11493 CurBlock->ReturnType = RetTy; 11494 CurBlock->TheDecl->setBlockMissingReturnType(false); 11495 CurBlock->HasImplicitReturnType = false; 11496 } 11497 11498 // Push block parameters from the declarator if we had them. 11499 SmallVector<ParmVarDecl*, 8> Params; 11500 if (ExplicitSignature) { 11501 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11502 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11503 if (Param->getIdentifier() == nullptr && 11504 !Param->isImplicit() && 11505 !Param->isInvalidDecl() && 11506 !getLangOpts().CPlusPlus) 11507 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11508 Params.push_back(Param); 11509 } 11510 11511 // Fake up parameter variables if we have a typedef, like 11512 // ^ fntype { ... } 11513 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11514 for (const auto &I : Fn->param_types()) { 11515 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11516 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11517 Params.push_back(Param); 11518 } 11519 } 11520 11521 // Set the parameters on the block decl. 11522 if (!Params.empty()) { 11523 CurBlock->TheDecl->setParams(Params); 11524 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11525 CurBlock->TheDecl->param_end(), 11526 /*CheckParameterNames=*/false); 11527 } 11528 11529 // Finally we can process decl attributes. 11530 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11531 11532 // Put the parameter variables in scope. 11533 for (auto AI : CurBlock->TheDecl->params()) { 11534 AI->setOwningFunction(CurBlock->TheDecl); 11535 11536 // If this has an identifier, add it to the scope stack. 11537 if (AI->getIdentifier()) { 11538 CheckShadow(CurBlock->TheScope, AI); 11539 11540 PushOnScopeChains(AI, CurBlock->TheScope); 11541 } 11542 } 11543 } 11544 11545 /// ActOnBlockError - If there is an error parsing a block, this callback 11546 /// is invoked to pop the information about the block from the action impl. 11547 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11548 // Leave the expression-evaluation context. 11549 DiscardCleanupsInEvaluationContext(); 11550 PopExpressionEvaluationContext(); 11551 11552 // Pop off CurBlock, handle nested blocks. 11553 PopDeclContext(); 11554 PopFunctionScopeInfo(); 11555 } 11556 11557 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11558 /// literal was successfully completed. ^(int x){...} 11559 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11560 Stmt *Body, Scope *CurScope) { 11561 // If blocks are disabled, emit an error. 11562 if (!LangOpts.Blocks) 11563 Diag(CaretLoc, diag::err_blocks_disable); 11564 11565 // Leave the expression-evaluation context. 11566 if (hasAnyUnrecoverableErrorsInThisFunction()) 11567 DiscardCleanupsInEvaluationContext(); 11568 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11569 PopExpressionEvaluationContext(); 11570 11571 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11572 11573 if (BSI->HasImplicitReturnType) 11574 deduceClosureReturnType(*BSI); 11575 11576 PopDeclContext(); 11577 11578 QualType RetTy = Context.VoidTy; 11579 if (!BSI->ReturnType.isNull()) 11580 RetTy = BSI->ReturnType; 11581 11582 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11583 QualType BlockTy; 11584 11585 // Set the captured variables on the block. 11586 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11587 SmallVector<BlockDecl::Capture, 4> Captures; 11588 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 11589 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 11590 if (Cap.isThisCapture()) 11591 continue; 11592 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11593 Cap.isNested(), Cap.getInitExpr()); 11594 Captures.push_back(NewCap); 11595 } 11596 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 11597 11598 // If the user wrote a function type in some form, try to use that. 11599 if (!BSI->FunctionType.isNull()) { 11600 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11601 11602 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11603 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11604 11605 // Turn protoless block types into nullary block types. 11606 if (isa<FunctionNoProtoType>(FTy)) { 11607 FunctionProtoType::ExtProtoInfo EPI; 11608 EPI.ExtInfo = Ext; 11609 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11610 11611 // Otherwise, if we don't need to change anything about the function type, 11612 // preserve its sugar structure. 11613 } else if (FTy->getReturnType() == RetTy && 11614 (!NoReturn || FTy->getNoReturnAttr())) { 11615 BlockTy = BSI->FunctionType; 11616 11617 // Otherwise, make the minimal modifications to the function type. 11618 } else { 11619 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11620 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11621 EPI.TypeQuals = 0; // FIXME: silently? 11622 EPI.ExtInfo = Ext; 11623 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11624 } 11625 11626 // If we don't have a function type, just build one from nothing. 11627 } else { 11628 FunctionProtoType::ExtProtoInfo EPI; 11629 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11630 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11631 } 11632 11633 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11634 BSI->TheDecl->param_end()); 11635 BlockTy = Context.getBlockPointerType(BlockTy); 11636 11637 // If needed, diagnose invalid gotos and switches in the block. 11638 if (getCurFunction()->NeedsScopeChecking() && 11639 !PP.isCodeCompletionEnabled()) 11640 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11641 11642 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11643 11644 // Try to apply the named return value optimization. We have to check again 11645 // if we can do this, though, because blocks keep return statements around 11646 // to deduce an implicit return type. 11647 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11648 !BSI->TheDecl->isDependentContext()) 11649 computeNRVO(Body, BSI); 11650 11651 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11652 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11653 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11654 11655 // If the block isn't obviously global, i.e. it captures anything at 11656 // all, then we need to do a few things in the surrounding context: 11657 if (Result->getBlockDecl()->hasCaptures()) { 11658 // First, this expression has a new cleanup object. 11659 ExprCleanupObjects.push_back(Result->getBlockDecl()); 11660 ExprNeedsCleanups = true; 11661 11662 // It also gets a branch-protected scope if any of the captured 11663 // variables needs destruction. 11664 for (const auto &CI : Result->getBlockDecl()->captures()) { 11665 const VarDecl *var = CI.getVariable(); 11666 if (var->getType().isDestructedType() != QualType::DK_none) { 11667 getCurFunction()->setHasBranchProtectedScope(); 11668 break; 11669 } 11670 } 11671 } 11672 11673 return Result; 11674 } 11675 11676 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 11677 Expr *E, ParsedType Ty, 11678 SourceLocation RPLoc) { 11679 TypeSourceInfo *TInfo; 11680 GetTypeFromParser(Ty, &TInfo); 11681 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 11682 } 11683 11684 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 11685 Expr *E, TypeSourceInfo *TInfo, 11686 SourceLocation RPLoc) { 11687 Expr *OrigExpr = E; 11688 bool IsMS = false; 11689 11690 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 11691 // as Microsoft ABI on an actual Microsoft platform, where 11692 // __builtin_ms_va_list and __builtin_va_list are the same.) 11693 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 11694 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 11695 QualType MSVaListType = Context.getBuiltinMSVaListType(); 11696 if (Context.hasSameType(MSVaListType, E->getType())) { 11697 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11698 return ExprError(); 11699 IsMS = true; 11700 } 11701 } 11702 11703 // Get the va_list type 11704 QualType VaListType = Context.getBuiltinVaListType(); 11705 if (!IsMS) { 11706 if (VaListType->isArrayType()) { 11707 // Deal with implicit array decay; for example, on x86-64, 11708 // va_list is an array, but it's supposed to decay to 11709 // a pointer for va_arg. 11710 VaListType = Context.getArrayDecayedType(VaListType); 11711 // Make sure the input expression also decays appropriately. 11712 ExprResult Result = UsualUnaryConversions(E); 11713 if (Result.isInvalid()) 11714 return ExprError(); 11715 E = Result.get(); 11716 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 11717 // If va_list is a record type and we are compiling in C++ mode, 11718 // check the argument using reference binding. 11719 InitializedEntity Entity = InitializedEntity::InitializeParameter( 11720 Context, Context.getLValueReferenceType(VaListType), false); 11721 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 11722 if (Init.isInvalid()) 11723 return ExprError(); 11724 E = Init.getAs<Expr>(); 11725 } else { 11726 // Otherwise, the va_list argument must be an l-value because 11727 // it is modified by va_arg. 11728 if (!E->isTypeDependent() && 11729 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11730 return ExprError(); 11731 } 11732 } 11733 11734 if (!IsMS && !E->isTypeDependent() && 11735 !Context.hasSameType(VaListType, E->getType())) 11736 return ExprError(Diag(E->getLocStart(), 11737 diag::err_first_argument_to_va_arg_not_of_type_va_list) 11738 << OrigExpr->getType() << E->getSourceRange()); 11739 11740 if (!TInfo->getType()->isDependentType()) { 11741 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 11742 diag::err_second_parameter_to_va_arg_incomplete, 11743 TInfo->getTypeLoc())) 11744 return ExprError(); 11745 11746 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 11747 TInfo->getType(), 11748 diag::err_second_parameter_to_va_arg_abstract, 11749 TInfo->getTypeLoc())) 11750 return ExprError(); 11751 11752 if (!TInfo->getType().isPODType(Context)) { 11753 Diag(TInfo->getTypeLoc().getBeginLoc(), 11754 TInfo->getType()->isObjCLifetimeType() 11755 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 11756 : diag::warn_second_parameter_to_va_arg_not_pod) 11757 << TInfo->getType() 11758 << TInfo->getTypeLoc().getSourceRange(); 11759 } 11760 11761 // Check for va_arg where arguments of the given type will be promoted 11762 // (i.e. this va_arg is guaranteed to have undefined behavior). 11763 QualType PromoteType; 11764 if (TInfo->getType()->isPromotableIntegerType()) { 11765 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 11766 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 11767 PromoteType = QualType(); 11768 } 11769 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 11770 PromoteType = Context.DoubleTy; 11771 if (!PromoteType.isNull()) 11772 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 11773 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 11774 << TInfo->getType() 11775 << PromoteType 11776 << TInfo->getTypeLoc().getSourceRange()); 11777 } 11778 11779 QualType T = TInfo->getType().getNonLValueExprType(Context); 11780 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 11781 } 11782 11783 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 11784 // The type of __null will be int or long, depending on the size of 11785 // pointers on the target. 11786 QualType Ty; 11787 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 11788 if (pw == Context.getTargetInfo().getIntWidth()) 11789 Ty = Context.IntTy; 11790 else if (pw == Context.getTargetInfo().getLongWidth()) 11791 Ty = Context.LongTy; 11792 else if (pw == Context.getTargetInfo().getLongLongWidth()) 11793 Ty = Context.LongLongTy; 11794 else { 11795 llvm_unreachable("I don't know size of pointer!"); 11796 } 11797 11798 return new (Context) GNUNullExpr(Ty, TokenLoc); 11799 } 11800 11801 bool 11802 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 11803 if (!getLangOpts().ObjC1) 11804 return false; 11805 11806 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 11807 if (!PT) 11808 return false; 11809 11810 if (!PT->isObjCIdType()) { 11811 // Check if the destination is the 'NSString' interface. 11812 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 11813 if (!ID || !ID->getIdentifier()->isStr("NSString")) 11814 return false; 11815 } 11816 11817 // Ignore any parens, implicit casts (should only be 11818 // array-to-pointer decays), and not-so-opaque values. The last is 11819 // important for making this trigger for property assignments. 11820 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 11821 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 11822 if (OV->getSourceExpr()) 11823 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 11824 11825 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 11826 if (!SL || !SL->isAscii()) 11827 return false; 11828 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 11829 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 11830 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 11831 return true; 11832 } 11833 11834 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 11835 SourceLocation Loc, 11836 QualType DstType, QualType SrcType, 11837 Expr *SrcExpr, AssignmentAction Action, 11838 bool *Complained) { 11839 if (Complained) 11840 *Complained = false; 11841 11842 // Decode the result (notice that AST's are still created for extensions). 11843 bool CheckInferredResultType = false; 11844 bool isInvalid = false; 11845 unsigned DiagKind = 0; 11846 FixItHint Hint; 11847 ConversionFixItGenerator ConvHints; 11848 bool MayHaveConvFixit = false; 11849 bool MayHaveFunctionDiff = false; 11850 const ObjCInterfaceDecl *IFace = nullptr; 11851 const ObjCProtocolDecl *PDecl = nullptr; 11852 11853 switch (ConvTy) { 11854 case Compatible: 11855 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 11856 return false; 11857 11858 case PointerToInt: 11859 DiagKind = diag::ext_typecheck_convert_pointer_int; 11860 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11861 MayHaveConvFixit = true; 11862 break; 11863 case IntToPointer: 11864 DiagKind = diag::ext_typecheck_convert_int_pointer; 11865 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11866 MayHaveConvFixit = true; 11867 break; 11868 case IncompatiblePointer: 11869 DiagKind = 11870 (Action == AA_Passing_CFAudited ? 11871 diag::err_arc_typecheck_convert_incompatible_pointer : 11872 diag::ext_typecheck_convert_incompatible_pointer); 11873 CheckInferredResultType = DstType->isObjCObjectPointerType() && 11874 SrcType->isObjCObjectPointerType(); 11875 if (Hint.isNull() && !CheckInferredResultType) { 11876 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11877 } 11878 else if (CheckInferredResultType) { 11879 SrcType = SrcType.getUnqualifiedType(); 11880 DstType = DstType.getUnqualifiedType(); 11881 } 11882 MayHaveConvFixit = true; 11883 break; 11884 case IncompatiblePointerSign: 11885 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 11886 break; 11887 case FunctionVoidPointer: 11888 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 11889 break; 11890 case IncompatiblePointerDiscardsQualifiers: { 11891 // Perform array-to-pointer decay if necessary. 11892 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 11893 11894 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 11895 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 11896 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 11897 DiagKind = diag::err_typecheck_incompatible_address_space; 11898 break; 11899 11900 11901 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 11902 DiagKind = diag::err_typecheck_incompatible_ownership; 11903 break; 11904 } 11905 11906 llvm_unreachable("unknown error case for discarding qualifiers!"); 11907 // fallthrough 11908 } 11909 case CompatiblePointerDiscardsQualifiers: 11910 // If the qualifiers lost were because we were applying the 11911 // (deprecated) C++ conversion from a string literal to a char* 11912 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 11913 // Ideally, this check would be performed in 11914 // checkPointerTypesForAssignment. However, that would require a 11915 // bit of refactoring (so that the second argument is an 11916 // expression, rather than a type), which should be done as part 11917 // of a larger effort to fix checkPointerTypesForAssignment for 11918 // C++ semantics. 11919 if (getLangOpts().CPlusPlus && 11920 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 11921 return false; 11922 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 11923 break; 11924 case IncompatibleNestedPointerQualifiers: 11925 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 11926 break; 11927 case IntToBlockPointer: 11928 DiagKind = diag::err_int_to_block_pointer; 11929 break; 11930 case IncompatibleBlockPointer: 11931 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 11932 break; 11933 case IncompatibleObjCQualifiedId: { 11934 if (SrcType->isObjCQualifiedIdType()) { 11935 const ObjCObjectPointerType *srcOPT = 11936 SrcType->getAs<ObjCObjectPointerType>(); 11937 for (auto *srcProto : srcOPT->quals()) { 11938 PDecl = srcProto; 11939 break; 11940 } 11941 if (const ObjCInterfaceType *IFaceT = 11942 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11943 IFace = IFaceT->getDecl(); 11944 } 11945 else if (DstType->isObjCQualifiedIdType()) { 11946 const ObjCObjectPointerType *dstOPT = 11947 DstType->getAs<ObjCObjectPointerType>(); 11948 for (auto *dstProto : dstOPT->quals()) { 11949 PDecl = dstProto; 11950 break; 11951 } 11952 if (const ObjCInterfaceType *IFaceT = 11953 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11954 IFace = IFaceT->getDecl(); 11955 } 11956 DiagKind = diag::warn_incompatible_qualified_id; 11957 break; 11958 } 11959 case IncompatibleVectors: 11960 DiagKind = diag::warn_incompatible_vectors; 11961 break; 11962 case IncompatibleObjCWeakRef: 11963 DiagKind = diag::err_arc_weak_unavailable_assign; 11964 break; 11965 case Incompatible: 11966 DiagKind = diag::err_typecheck_convert_incompatible; 11967 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11968 MayHaveConvFixit = true; 11969 isInvalid = true; 11970 MayHaveFunctionDiff = true; 11971 break; 11972 } 11973 11974 QualType FirstType, SecondType; 11975 switch (Action) { 11976 case AA_Assigning: 11977 case AA_Initializing: 11978 // The destination type comes first. 11979 FirstType = DstType; 11980 SecondType = SrcType; 11981 break; 11982 11983 case AA_Returning: 11984 case AA_Passing: 11985 case AA_Passing_CFAudited: 11986 case AA_Converting: 11987 case AA_Sending: 11988 case AA_Casting: 11989 // The source type comes first. 11990 FirstType = SrcType; 11991 SecondType = DstType; 11992 break; 11993 } 11994 11995 PartialDiagnostic FDiag = PDiag(DiagKind); 11996 if (Action == AA_Passing_CFAudited) 11997 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 11998 else 11999 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12000 12001 // If we can fix the conversion, suggest the FixIts. 12002 assert(ConvHints.isNull() || Hint.isNull()); 12003 if (!ConvHints.isNull()) { 12004 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 12005 HE = ConvHints.Hints.end(); HI != HE; ++HI) 12006 FDiag << *HI; 12007 } else { 12008 FDiag << Hint; 12009 } 12010 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12011 12012 if (MayHaveFunctionDiff) 12013 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12014 12015 Diag(Loc, FDiag); 12016 if (DiagKind == diag::warn_incompatible_qualified_id && 12017 PDecl && IFace && !IFace->hasDefinition()) 12018 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12019 << IFace->getName() << PDecl->getName(); 12020 12021 if (SecondType == Context.OverloadTy) 12022 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12023 FirstType, /*TakingAddress=*/true); 12024 12025 if (CheckInferredResultType) 12026 EmitRelatedResultTypeNote(SrcExpr); 12027 12028 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12029 EmitRelatedResultTypeNoteForReturn(DstType); 12030 12031 if (Complained) 12032 *Complained = true; 12033 return isInvalid; 12034 } 12035 12036 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12037 llvm::APSInt *Result) { 12038 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12039 public: 12040 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12041 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12042 } 12043 } Diagnoser; 12044 12045 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12046 } 12047 12048 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12049 llvm::APSInt *Result, 12050 unsigned DiagID, 12051 bool AllowFold) { 12052 class IDDiagnoser : public VerifyICEDiagnoser { 12053 unsigned DiagID; 12054 12055 public: 12056 IDDiagnoser(unsigned DiagID) 12057 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12058 12059 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12060 S.Diag(Loc, DiagID) << SR; 12061 } 12062 } Diagnoser(DiagID); 12063 12064 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12065 } 12066 12067 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12068 SourceRange SR) { 12069 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12070 } 12071 12072 ExprResult 12073 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12074 VerifyICEDiagnoser &Diagnoser, 12075 bool AllowFold) { 12076 SourceLocation DiagLoc = E->getLocStart(); 12077 12078 if (getLangOpts().CPlusPlus11) { 12079 // C++11 [expr.const]p5: 12080 // If an expression of literal class type is used in a context where an 12081 // integral constant expression is required, then that class type shall 12082 // have a single non-explicit conversion function to an integral or 12083 // unscoped enumeration type 12084 ExprResult Converted; 12085 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12086 public: 12087 CXX11ConvertDiagnoser(bool Silent) 12088 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12089 Silent, true) {} 12090 12091 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12092 QualType T) override { 12093 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12094 } 12095 12096 SemaDiagnosticBuilder diagnoseIncomplete( 12097 Sema &S, SourceLocation Loc, QualType T) override { 12098 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12099 } 12100 12101 SemaDiagnosticBuilder diagnoseExplicitConv( 12102 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12103 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12104 } 12105 12106 SemaDiagnosticBuilder noteExplicitConv( 12107 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12108 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12109 << ConvTy->isEnumeralType() << ConvTy; 12110 } 12111 12112 SemaDiagnosticBuilder diagnoseAmbiguous( 12113 Sema &S, SourceLocation Loc, QualType T) override { 12114 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12115 } 12116 12117 SemaDiagnosticBuilder noteAmbiguous( 12118 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12119 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12120 << ConvTy->isEnumeralType() << ConvTy; 12121 } 12122 12123 SemaDiagnosticBuilder diagnoseConversion( 12124 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12125 llvm_unreachable("conversion functions are permitted"); 12126 } 12127 } ConvertDiagnoser(Diagnoser.Suppress); 12128 12129 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12130 ConvertDiagnoser); 12131 if (Converted.isInvalid()) 12132 return Converted; 12133 E = Converted.get(); 12134 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12135 return ExprError(); 12136 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12137 // An ICE must be of integral or unscoped enumeration type. 12138 if (!Diagnoser.Suppress) 12139 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12140 return ExprError(); 12141 } 12142 12143 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12144 // in the non-ICE case. 12145 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12146 if (Result) 12147 *Result = E->EvaluateKnownConstInt(Context); 12148 return E; 12149 } 12150 12151 Expr::EvalResult EvalResult; 12152 SmallVector<PartialDiagnosticAt, 8> Notes; 12153 EvalResult.Diag = &Notes; 12154 12155 // Try to evaluate the expression, and produce diagnostics explaining why it's 12156 // not a constant expression as a side-effect. 12157 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12158 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12159 12160 // In C++11, we can rely on diagnostics being produced for any expression 12161 // which is not a constant expression. If no diagnostics were produced, then 12162 // this is a constant expression. 12163 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12164 if (Result) 12165 *Result = EvalResult.Val.getInt(); 12166 return E; 12167 } 12168 12169 // If our only note is the usual "invalid subexpression" note, just point 12170 // the caret at its location rather than producing an essentially 12171 // redundant note. 12172 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12173 diag::note_invalid_subexpr_in_const_expr) { 12174 DiagLoc = Notes[0].first; 12175 Notes.clear(); 12176 } 12177 12178 if (!Folded || !AllowFold) { 12179 if (!Diagnoser.Suppress) { 12180 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12181 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12182 Diag(Notes[I].first, Notes[I].second); 12183 } 12184 12185 return ExprError(); 12186 } 12187 12188 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12189 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12190 Diag(Notes[I].first, Notes[I].second); 12191 12192 if (Result) 12193 *Result = EvalResult.Val.getInt(); 12194 return E; 12195 } 12196 12197 namespace { 12198 // Handle the case where we conclude a expression which we speculatively 12199 // considered to be unevaluated is actually evaluated. 12200 class TransformToPE : public TreeTransform<TransformToPE> { 12201 typedef TreeTransform<TransformToPE> BaseTransform; 12202 12203 public: 12204 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12205 12206 // Make sure we redo semantic analysis 12207 bool AlwaysRebuild() { return true; } 12208 12209 // Make sure we handle LabelStmts correctly. 12210 // FIXME: This does the right thing, but maybe we need a more general 12211 // fix to TreeTransform? 12212 StmtResult TransformLabelStmt(LabelStmt *S) { 12213 S->getDecl()->setStmt(nullptr); 12214 return BaseTransform::TransformLabelStmt(S); 12215 } 12216 12217 // We need to special-case DeclRefExprs referring to FieldDecls which 12218 // are not part of a member pointer formation; normal TreeTransforming 12219 // doesn't catch this case because of the way we represent them in the AST. 12220 // FIXME: This is a bit ugly; is it really the best way to handle this 12221 // case? 12222 // 12223 // Error on DeclRefExprs referring to FieldDecls. 12224 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12225 if (isa<FieldDecl>(E->getDecl()) && 12226 !SemaRef.isUnevaluatedContext()) 12227 return SemaRef.Diag(E->getLocation(), 12228 diag::err_invalid_non_static_member_use) 12229 << E->getDecl() << E->getSourceRange(); 12230 12231 return BaseTransform::TransformDeclRefExpr(E); 12232 } 12233 12234 // Exception: filter out member pointer formation 12235 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12236 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12237 return E; 12238 12239 return BaseTransform::TransformUnaryOperator(E); 12240 } 12241 12242 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12243 // Lambdas never need to be transformed. 12244 return E; 12245 } 12246 }; 12247 } 12248 12249 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12250 assert(isUnevaluatedContext() && 12251 "Should only transform unevaluated expressions"); 12252 ExprEvalContexts.back().Context = 12253 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12254 if (isUnevaluatedContext()) 12255 return E; 12256 return TransformToPE(*this).TransformExpr(E); 12257 } 12258 12259 void 12260 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12261 Decl *LambdaContextDecl, 12262 bool IsDecltype) { 12263 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12264 ExprNeedsCleanups, LambdaContextDecl, 12265 IsDecltype); 12266 ExprNeedsCleanups = false; 12267 if (!MaybeODRUseExprs.empty()) 12268 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12269 } 12270 12271 void 12272 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12273 ReuseLambdaContextDecl_t, 12274 bool IsDecltype) { 12275 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12276 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12277 } 12278 12279 void Sema::PopExpressionEvaluationContext() { 12280 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12281 unsigned NumTypos = Rec.NumTypos; 12282 12283 if (!Rec.Lambdas.empty()) { 12284 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12285 unsigned D; 12286 if (Rec.isUnevaluated()) { 12287 // C++11 [expr.prim.lambda]p2: 12288 // A lambda-expression shall not appear in an unevaluated operand 12289 // (Clause 5). 12290 D = diag::err_lambda_unevaluated_operand; 12291 } else { 12292 // C++1y [expr.const]p2: 12293 // A conditional-expression e is a core constant expression unless the 12294 // evaluation of e, following the rules of the abstract machine, would 12295 // evaluate [...] a lambda-expression. 12296 D = diag::err_lambda_in_constant_expression; 12297 } 12298 for (const auto *L : Rec.Lambdas) 12299 Diag(L->getLocStart(), D); 12300 } else { 12301 // Mark the capture expressions odr-used. This was deferred 12302 // during lambda expression creation. 12303 for (auto *Lambda : Rec.Lambdas) { 12304 for (auto *C : Lambda->capture_inits()) 12305 MarkDeclarationsReferencedInExpr(C); 12306 } 12307 } 12308 } 12309 12310 // When are coming out of an unevaluated context, clear out any 12311 // temporaries that we may have created as part of the evaluation of 12312 // the expression in that context: they aren't relevant because they 12313 // will never be constructed. 12314 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12315 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12316 ExprCleanupObjects.end()); 12317 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12318 CleanupVarDeclMarking(); 12319 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12320 // Otherwise, merge the contexts together. 12321 } else { 12322 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12323 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12324 Rec.SavedMaybeODRUseExprs.end()); 12325 } 12326 12327 // Pop the current expression evaluation context off the stack. 12328 ExprEvalContexts.pop_back(); 12329 12330 if (!ExprEvalContexts.empty()) 12331 ExprEvalContexts.back().NumTypos += NumTypos; 12332 else 12333 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12334 "last ExpressionEvaluationContextRecord"); 12335 } 12336 12337 void Sema::DiscardCleanupsInEvaluationContext() { 12338 ExprCleanupObjects.erase( 12339 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12340 ExprCleanupObjects.end()); 12341 ExprNeedsCleanups = false; 12342 MaybeODRUseExprs.clear(); 12343 } 12344 12345 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12346 if (!E->getType()->isVariablyModifiedType()) 12347 return E; 12348 return TransformToPotentiallyEvaluated(E); 12349 } 12350 12351 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12352 // Do not mark anything as "used" within a dependent context; wait for 12353 // an instantiation. 12354 if (SemaRef.CurContext->isDependentContext()) 12355 return false; 12356 12357 switch (SemaRef.ExprEvalContexts.back().Context) { 12358 case Sema::Unevaluated: 12359 case Sema::UnevaluatedAbstract: 12360 // We are in an expression that is not potentially evaluated; do nothing. 12361 // (Depending on how you read the standard, we actually do need to do 12362 // something here for null pointer constants, but the standard's 12363 // definition of a null pointer constant is completely crazy.) 12364 return false; 12365 12366 case Sema::ConstantEvaluated: 12367 case Sema::PotentiallyEvaluated: 12368 // We are in a potentially evaluated expression (or a constant-expression 12369 // in C++03); we need to do implicit template instantiation, implicitly 12370 // define class members, and mark most declarations as used. 12371 return true; 12372 12373 case Sema::PotentiallyEvaluatedIfUsed: 12374 // Referenced declarations will only be used if the construct in the 12375 // containing expression is used. 12376 return false; 12377 } 12378 llvm_unreachable("Invalid context"); 12379 } 12380 12381 /// \brief Mark a function referenced, and check whether it is odr-used 12382 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12383 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12384 bool OdrUse) { 12385 assert(Func && "No function?"); 12386 12387 Func->setReferenced(); 12388 12389 // C++11 [basic.def.odr]p3: 12390 // A function whose name appears as a potentially-evaluated expression is 12391 // odr-used if it is the unique lookup result or the selected member of a 12392 // set of overloaded functions [...]. 12393 // 12394 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12395 // can just check that here. Skip the rest of this function if we've already 12396 // marked the function as used. 12397 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12398 !IsPotentiallyEvaluatedContext(*this)) { 12399 // C++11 [temp.inst]p3: 12400 // Unless a function template specialization has been explicitly 12401 // instantiated or explicitly specialized, the function template 12402 // specialization is implicitly instantiated when the specialization is 12403 // referenced in a context that requires a function definition to exist. 12404 // 12405 // We consider constexpr function templates to be referenced in a context 12406 // that requires a definition to exist whenever they are referenced. 12407 // 12408 // FIXME: This instantiates constexpr functions too frequently. If this is 12409 // really an unevaluated context (and we're not just in the definition of a 12410 // function template or overload resolution or other cases which we 12411 // incorrectly consider to be unevaluated contexts), and we're not in a 12412 // subexpression which we actually need to evaluate (for instance, a 12413 // template argument, array bound or an expression in a braced-init-list), 12414 // we are not permitted to instantiate this constexpr function definition. 12415 // 12416 // FIXME: This also implicitly defines special members too frequently. They 12417 // are only supposed to be implicitly defined if they are odr-used, but they 12418 // are not odr-used from constant expressions in unevaluated contexts. 12419 // However, they cannot be referenced if they are deleted, and they are 12420 // deleted whenever the implicit definition of the special member would 12421 // fail. 12422 if (!Func->isConstexpr() || Func->getBody()) 12423 return; 12424 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12425 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12426 return; 12427 } 12428 12429 // Note that this declaration has been used. 12430 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12431 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12432 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12433 if (Constructor->isDefaultConstructor()) { 12434 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12435 return; 12436 DefineImplicitDefaultConstructor(Loc, Constructor); 12437 } else if (Constructor->isCopyConstructor()) { 12438 DefineImplicitCopyConstructor(Loc, Constructor); 12439 } else if (Constructor->isMoveConstructor()) { 12440 DefineImplicitMoveConstructor(Loc, Constructor); 12441 } 12442 } else if (Constructor->getInheritedConstructor()) { 12443 DefineInheritingConstructor(Loc, Constructor); 12444 } 12445 } else if (CXXDestructorDecl *Destructor = 12446 dyn_cast<CXXDestructorDecl>(Func)) { 12447 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12448 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12449 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12450 return; 12451 DefineImplicitDestructor(Loc, Destructor); 12452 } 12453 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12454 MarkVTableUsed(Loc, Destructor->getParent()); 12455 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12456 if (MethodDecl->isOverloadedOperator() && 12457 MethodDecl->getOverloadedOperator() == OO_Equal) { 12458 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12459 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12460 if (MethodDecl->isCopyAssignmentOperator()) 12461 DefineImplicitCopyAssignment(Loc, MethodDecl); 12462 else 12463 DefineImplicitMoveAssignment(Loc, MethodDecl); 12464 } 12465 } else if (isa<CXXConversionDecl>(MethodDecl) && 12466 MethodDecl->getParent()->isLambda()) { 12467 CXXConversionDecl *Conversion = 12468 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12469 if (Conversion->isLambdaToBlockPointerConversion()) 12470 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12471 else 12472 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12473 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12474 MarkVTableUsed(Loc, MethodDecl->getParent()); 12475 } 12476 12477 // Recursive functions should be marked when used from another function. 12478 // FIXME: Is this really right? 12479 if (CurContext == Func) return; 12480 12481 // Resolve the exception specification for any function which is 12482 // used: CodeGen will need it. 12483 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12484 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12485 ResolveExceptionSpec(Loc, FPT); 12486 12487 if (!OdrUse) return; 12488 12489 // Implicit instantiation of function templates and member functions of 12490 // class templates. 12491 if (Func->isImplicitlyInstantiable()) { 12492 bool AlreadyInstantiated = false; 12493 SourceLocation PointOfInstantiation = Loc; 12494 if (FunctionTemplateSpecializationInfo *SpecInfo 12495 = Func->getTemplateSpecializationInfo()) { 12496 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12497 SpecInfo->setPointOfInstantiation(Loc); 12498 else if (SpecInfo->getTemplateSpecializationKind() 12499 == TSK_ImplicitInstantiation) { 12500 AlreadyInstantiated = true; 12501 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12502 } 12503 } else if (MemberSpecializationInfo *MSInfo 12504 = Func->getMemberSpecializationInfo()) { 12505 if (MSInfo->getPointOfInstantiation().isInvalid()) 12506 MSInfo->setPointOfInstantiation(Loc); 12507 else if (MSInfo->getTemplateSpecializationKind() 12508 == TSK_ImplicitInstantiation) { 12509 AlreadyInstantiated = true; 12510 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12511 } 12512 } 12513 12514 if (!AlreadyInstantiated || Func->isConstexpr()) { 12515 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12516 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12517 ActiveTemplateInstantiations.size()) 12518 PendingLocalImplicitInstantiations.push_back( 12519 std::make_pair(Func, PointOfInstantiation)); 12520 else if (Func->isConstexpr()) 12521 // Do not defer instantiations of constexpr functions, to avoid the 12522 // expression evaluator needing to call back into Sema if it sees a 12523 // call to such a function. 12524 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12525 else { 12526 PendingInstantiations.push_back(std::make_pair(Func, 12527 PointOfInstantiation)); 12528 // Notify the consumer that a function was implicitly instantiated. 12529 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12530 } 12531 } 12532 } else { 12533 // Walk redefinitions, as some of them may be instantiable. 12534 for (auto i : Func->redecls()) { 12535 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12536 MarkFunctionReferenced(Loc, i); 12537 } 12538 } 12539 12540 // Keep track of used but undefined functions. 12541 if (!Func->isDefined()) { 12542 if (mightHaveNonExternalLinkage(Func)) 12543 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12544 else if (Func->getMostRecentDecl()->isInlined() && 12545 !LangOpts.GNUInline && 12546 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12547 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12548 } 12549 12550 // Normally the most current decl is marked used while processing the use and 12551 // any subsequent decls are marked used by decl merging. This fails with 12552 // template instantiation since marking can happen at the end of the file 12553 // and, because of the two phase lookup, this function is called with at 12554 // decl in the middle of a decl chain. We loop to maintain the invariant 12555 // that once a decl is used, all decls after it are also used. 12556 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12557 F->markUsed(Context); 12558 if (F == Func) 12559 break; 12560 } 12561 } 12562 12563 static void 12564 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12565 VarDecl *var, DeclContext *DC) { 12566 DeclContext *VarDC = var->getDeclContext(); 12567 12568 // If the parameter still belongs to the translation unit, then 12569 // we're actually just using one parameter in the declaration of 12570 // the next. 12571 if (isa<ParmVarDecl>(var) && 12572 isa<TranslationUnitDecl>(VarDC)) 12573 return; 12574 12575 // For C code, don't diagnose about capture if we're not actually in code 12576 // right now; it's impossible to write a non-constant expression outside of 12577 // function context, so we'll get other (more useful) diagnostics later. 12578 // 12579 // For C++, things get a bit more nasty... it would be nice to suppress this 12580 // diagnostic for certain cases like using a local variable in an array bound 12581 // for a member of a local class, but the correct predicate is not obvious. 12582 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12583 return; 12584 12585 if (isa<CXXMethodDecl>(VarDC) && 12586 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12587 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12588 << var->getIdentifier(); 12589 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12590 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12591 << var->getIdentifier() << fn->getDeclName(); 12592 } else if (isa<BlockDecl>(VarDC)) { 12593 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12594 << var->getIdentifier(); 12595 } else { 12596 // FIXME: Is there any other context where a local variable can be 12597 // declared? 12598 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12599 << var->getIdentifier(); 12600 } 12601 12602 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12603 << var->getIdentifier(); 12604 12605 // FIXME: Add additional diagnostic info about class etc. which prevents 12606 // capture. 12607 } 12608 12609 12610 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12611 bool &SubCapturesAreNested, 12612 QualType &CaptureType, 12613 QualType &DeclRefType) { 12614 // Check whether we've already captured it. 12615 if (CSI->CaptureMap.count(Var)) { 12616 // If we found a capture, any subcaptures are nested. 12617 SubCapturesAreNested = true; 12618 12619 // Retrieve the capture type for this variable. 12620 CaptureType = CSI->getCapture(Var).getCaptureType(); 12621 12622 // Compute the type of an expression that refers to this variable. 12623 DeclRefType = CaptureType.getNonReferenceType(); 12624 12625 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 12626 if (Cap.isCopyCapture() && 12627 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 12628 DeclRefType.addConst(); 12629 return true; 12630 } 12631 return false; 12632 } 12633 12634 // Only block literals, captured statements, and lambda expressions can 12635 // capture; other scopes don't work. 12636 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 12637 SourceLocation Loc, 12638 const bool Diagnose, Sema &S) { 12639 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 12640 return getLambdaAwareParentOfDeclContext(DC); 12641 else if (Var->hasLocalStorage()) { 12642 if (Diagnose) 12643 diagnoseUncapturableValueReference(S, Loc, Var, DC); 12644 } 12645 return nullptr; 12646 } 12647 12648 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12649 // certain types of variables (unnamed, variably modified types etc.) 12650 // so check for eligibility. 12651 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 12652 SourceLocation Loc, 12653 const bool Diagnose, Sema &S) { 12654 12655 bool IsBlock = isa<BlockScopeInfo>(CSI); 12656 bool IsLambda = isa<LambdaScopeInfo>(CSI); 12657 12658 // Lambdas are not allowed to capture unnamed variables 12659 // (e.g. anonymous unions). 12660 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 12661 // assuming that's the intent. 12662 if (IsLambda && !Var->getDeclName()) { 12663 if (Diagnose) { 12664 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 12665 S.Diag(Var->getLocation(), diag::note_declared_at); 12666 } 12667 return false; 12668 } 12669 12670 // Prohibit variably-modified types in blocks; they're difficult to deal with. 12671 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 12672 if (Diagnose) { 12673 S.Diag(Loc, diag::err_ref_vm_type); 12674 S.Diag(Var->getLocation(), diag::note_previous_decl) 12675 << Var->getDeclName(); 12676 } 12677 return false; 12678 } 12679 // Prohibit structs with flexible array members too. 12680 // We cannot capture what is in the tail end of the struct. 12681 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 12682 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 12683 if (Diagnose) { 12684 if (IsBlock) 12685 S.Diag(Loc, diag::err_ref_flexarray_type); 12686 else 12687 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 12688 << Var->getDeclName(); 12689 S.Diag(Var->getLocation(), diag::note_previous_decl) 12690 << Var->getDeclName(); 12691 } 12692 return false; 12693 } 12694 } 12695 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12696 // Lambdas and captured statements are not allowed to capture __block 12697 // variables; they don't support the expected semantics. 12698 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 12699 if (Diagnose) { 12700 S.Diag(Loc, diag::err_capture_block_variable) 12701 << Var->getDeclName() << !IsLambda; 12702 S.Diag(Var->getLocation(), diag::note_previous_decl) 12703 << Var->getDeclName(); 12704 } 12705 return false; 12706 } 12707 12708 return true; 12709 } 12710 12711 // Returns true if the capture by block was successful. 12712 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 12713 SourceLocation Loc, 12714 const bool BuildAndDiagnose, 12715 QualType &CaptureType, 12716 QualType &DeclRefType, 12717 const bool Nested, 12718 Sema &S) { 12719 Expr *CopyExpr = nullptr; 12720 bool ByRef = false; 12721 12722 // Blocks are not allowed to capture arrays. 12723 if (CaptureType->isArrayType()) { 12724 if (BuildAndDiagnose) { 12725 S.Diag(Loc, diag::err_ref_array_type); 12726 S.Diag(Var->getLocation(), diag::note_previous_decl) 12727 << Var->getDeclName(); 12728 } 12729 return false; 12730 } 12731 12732 // Forbid the block-capture of autoreleasing variables. 12733 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12734 if (BuildAndDiagnose) { 12735 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 12736 << /*block*/ 0; 12737 S.Diag(Var->getLocation(), diag::note_previous_decl) 12738 << Var->getDeclName(); 12739 } 12740 return false; 12741 } 12742 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12743 if (HasBlocksAttr || CaptureType->isReferenceType()) { 12744 // Block capture by reference does not change the capture or 12745 // declaration reference types. 12746 ByRef = true; 12747 } else { 12748 // Block capture by copy introduces 'const'. 12749 CaptureType = CaptureType.getNonReferenceType().withConst(); 12750 DeclRefType = CaptureType; 12751 12752 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 12753 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 12754 // The capture logic needs the destructor, so make sure we mark it. 12755 // Usually this is unnecessary because most local variables have 12756 // their destructors marked at declaration time, but parameters are 12757 // an exception because it's technically only the call site that 12758 // actually requires the destructor. 12759 if (isa<ParmVarDecl>(Var)) 12760 S.FinalizeVarWithDestructor(Var, Record); 12761 12762 // Enter a new evaluation context to insulate the copy 12763 // full-expression. 12764 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 12765 12766 // According to the blocks spec, the capture of a variable from 12767 // the stack requires a const copy constructor. This is not true 12768 // of the copy/move done to move a __block variable to the heap. 12769 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 12770 DeclRefType.withConst(), 12771 VK_LValue, Loc); 12772 12773 ExprResult Result 12774 = S.PerformCopyInitialization( 12775 InitializedEntity::InitializeBlock(Var->getLocation(), 12776 CaptureType, false), 12777 Loc, DeclRef); 12778 12779 // Build a full-expression copy expression if initialization 12780 // succeeded and used a non-trivial constructor. Recover from 12781 // errors by pretending that the copy isn't necessary. 12782 if (!Result.isInvalid() && 12783 !cast<CXXConstructExpr>(Result.get())->getConstructor() 12784 ->isTrivial()) { 12785 Result = S.MaybeCreateExprWithCleanups(Result); 12786 CopyExpr = Result.get(); 12787 } 12788 } 12789 } 12790 } 12791 12792 // Actually capture the variable. 12793 if (BuildAndDiagnose) 12794 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 12795 SourceLocation(), CaptureType, CopyExpr); 12796 12797 return true; 12798 12799 } 12800 12801 12802 /// \brief Capture the given variable in the captured region. 12803 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 12804 VarDecl *Var, 12805 SourceLocation Loc, 12806 const bool BuildAndDiagnose, 12807 QualType &CaptureType, 12808 QualType &DeclRefType, 12809 const bool RefersToCapturedVariable, 12810 Sema &S) { 12811 12812 // By default, capture variables by reference. 12813 bool ByRef = true; 12814 // Using an LValue reference type is consistent with Lambdas (see below). 12815 if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var)) 12816 DeclRefType = DeclRefType.getUnqualifiedType(); 12817 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12818 Expr *CopyExpr = nullptr; 12819 if (BuildAndDiagnose) { 12820 // The current implementation assumes that all variables are captured 12821 // by references. Since there is no capture by copy, no expression 12822 // evaluation will be needed. 12823 RecordDecl *RD = RSI->TheRecordDecl; 12824 12825 FieldDecl *Field 12826 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 12827 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 12828 nullptr, false, ICIS_NoInit); 12829 Field->setImplicit(true); 12830 Field->setAccess(AS_private); 12831 RD->addDecl(Field); 12832 12833 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 12834 DeclRefType, VK_LValue, Loc); 12835 Var->setReferenced(true); 12836 Var->markUsed(S.Context); 12837 } 12838 12839 // Actually capture the variable. 12840 if (BuildAndDiagnose) 12841 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 12842 SourceLocation(), CaptureType, CopyExpr); 12843 12844 12845 return true; 12846 } 12847 12848 /// \brief Create a field within the lambda class for the variable 12849 /// being captured. 12850 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 12851 QualType FieldType, QualType DeclRefType, 12852 SourceLocation Loc, 12853 bool RefersToCapturedVariable) { 12854 CXXRecordDecl *Lambda = LSI->Lambda; 12855 12856 // Build the non-static data member. 12857 FieldDecl *Field 12858 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 12859 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 12860 nullptr, false, ICIS_NoInit); 12861 Field->setImplicit(true); 12862 Field->setAccess(AS_private); 12863 Lambda->addDecl(Field); 12864 } 12865 12866 /// \brief Capture the given variable in the lambda. 12867 static bool captureInLambda(LambdaScopeInfo *LSI, 12868 VarDecl *Var, 12869 SourceLocation Loc, 12870 const bool BuildAndDiagnose, 12871 QualType &CaptureType, 12872 QualType &DeclRefType, 12873 const bool RefersToCapturedVariable, 12874 const Sema::TryCaptureKind Kind, 12875 SourceLocation EllipsisLoc, 12876 const bool IsTopScope, 12877 Sema &S) { 12878 12879 // Determine whether we are capturing by reference or by value. 12880 bool ByRef = false; 12881 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 12882 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 12883 } else { 12884 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 12885 } 12886 12887 // Compute the type of the field that will capture this variable. 12888 if (ByRef) { 12889 // C++11 [expr.prim.lambda]p15: 12890 // An entity is captured by reference if it is implicitly or 12891 // explicitly captured but not captured by copy. It is 12892 // unspecified whether additional unnamed non-static data 12893 // members are declared in the closure type for entities 12894 // captured by reference. 12895 // 12896 // FIXME: It is not clear whether we want to build an lvalue reference 12897 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 12898 // to do the former, while EDG does the latter. Core issue 1249 will 12899 // clarify, but for now we follow GCC because it's a more permissive and 12900 // easily defensible position. 12901 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12902 } else { 12903 // C++11 [expr.prim.lambda]p14: 12904 // For each entity captured by copy, an unnamed non-static 12905 // data member is declared in the closure type. The 12906 // declaration order of these members is unspecified. The type 12907 // of such a data member is the type of the corresponding 12908 // captured entity if the entity is not a reference to an 12909 // object, or the referenced type otherwise. [Note: If the 12910 // captured entity is a reference to a function, the 12911 // corresponding data member is also a reference to a 12912 // function. - end note ] 12913 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 12914 if (!RefType->getPointeeType()->isFunctionType()) 12915 CaptureType = RefType->getPointeeType(); 12916 } 12917 12918 // Forbid the lambda copy-capture of autoreleasing variables. 12919 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12920 if (BuildAndDiagnose) { 12921 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 12922 S.Diag(Var->getLocation(), diag::note_previous_decl) 12923 << Var->getDeclName(); 12924 } 12925 return false; 12926 } 12927 12928 // Make sure that by-copy captures are of a complete and non-abstract type. 12929 if (BuildAndDiagnose) { 12930 if (!CaptureType->isDependentType() && 12931 S.RequireCompleteType(Loc, CaptureType, 12932 diag::err_capture_of_incomplete_type, 12933 Var->getDeclName())) 12934 return false; 12935 12936 if (S.RequireNonAbstractType(Loc, CaptureType, 12937 diag::err_capture_of_abstract_type)) 12938 return false; 12939 } 12940 } 12941 12942 // Capture this variable in the lambda. 12943 if (BuildAndDiagnose) 12944 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 12945 RefersToCapturedVariable); 12946 12947 // Compute the type of a reference to this captured variable. 12948 if (ByRef) 12949 DeclRefType = CaptureType.getNonReferenceType(); 12950 else { 12951 // C++ [expr.prim.lambda]p5: 12952 // The closure type for a lambda-expression has a public inline 12953 // function call operator [...]. This function call operator is 12954 // declared const (9.3.1) if and only if the lambda-expression’s 12955 // parameter-declaration-clause is not followed by mutable. 12956 DeclRefType = CaptureType.getNonReferenceType(); 12957 if (!LSI->Mutable && !CaptureType->isReferenceType()) 12958 DeclRefType.addConst(); 12959 } 12960 12961 // Add the capture. 12962 if (BuildAndDiagnose) 12963 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 12964 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 12965 12966 return true; 12967 } 12968 12969 bool Sema::tryCaptureVariable( 12970 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 12971 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 12972 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 12973 // An init-capture is notionally from the context surrounding its 12974 // declaration, but its parent DC is the lambda class. 12975 DeclContext *VarDC = Var->getDeclContext(); 12976 if (Var->isInitCapture()) 12977 VarDC = VarDC->getParent(); 12978 12979 DeclContext *DC = CurContext; 12980 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12981 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 12982 // We need to sync up the Declaration Context with the 12983 // FunctionScopeIndexToStopAt 12984 if (FunctionScopeIndexToStopAt) { 12985 unsigned FSIndex = FunctionScopes.size() - 1; 12986 while (FSIndex != MaxFunctionScopesIndex) { 12987 DC = getLambdaAwareParentOfDeclContext(DC); 12988 --FSIndex; 12989 } 12990 } 12991 12992 12993 // If the variable is declared in the current context, there is no need to 12994 // capture it. 12995 if (VarDC == DC) return true; 12996 12997 // Capture global variables if it is required to use private copy of this 12998 // variable. 12999 bool IsGlobal = !Var->hasLocalStorage(); 13000 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var))) 13001 return true; 13002 13003 // Walk up the stack to determine whether we can capture the variable, 13004 // performing the "simple" checks that don't depend on type. We stop when 13005 // we've either hit the declared scope of the variable or find an existing 13006 // capture of that variable. We start from the innermost capturing-entity 13007 // (the DC) and ensure that all intervening capturing-entities 13008 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13009 // declcontext can either capture the variable or have already captured 13010 // the variable. 13011 CaptureType = Var->getType(); 13012 DeclRefType = CaptureType.getNonReferenceType(); 13013 bool Nested = false; 13014 bool Explicit = (Kind != TryCapture_Implicit); 13015 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13016 unsigned OpenMPLevel = 0; 13017 do { 13018 // Only block literals, captured statements, and lambda expressions can 13019 // capture; other scopes don't work. 13020 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13021 ExprLoc, 13022 BuildAndDiagnose, 13023 *this); 13024 // We need to check for the parent *first* because, if we *have* 13025 // private-captured a global variable, we need to recursively capture it in 13026 // intermediate blocks, lambdas, etc. 13027 if (!ParentDC) { 13028 if (IsGlobal) { 13029 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13030 break; 13031 } 13032 return true; 13033 } 13034 13035 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13036 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13037 13038 13039 // Check whether we've already captured it. 13040 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13041 DeclRefType)) 13042 break; 13043 // If we are instantiating a generic lambda call operator body, 13044 // we do not want to capture new variables. What was captured 13045 // during either a lambdas transformation or initial parsing 13046 // should be used. 13047 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13048 if (BuildAndDiagnose) { 13049 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13050 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13051 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13052 Diag(Var->getLocation(), diag::note_previous_decl) 13053 << Var->getDeclName(); 13054 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13055 } else 13056 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13057 } 13058 return true; 13059 } 13060 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13061 // certain types of variables (unnamed, variably modified types etc.) 13062 // so check for eligibility. 13063 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13064 return true; 13065 13066 // Try to capture variable-length arrays types. 13067 if (Var->getType()->isVariablyModifiedType()) { 13068 // We're going to walk down into the type and look for VLA 13069 // expressions. 13070 QualType QTy = Var->getType(); 13071 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13072 QTy = PVD->getOriginalType(); 13073 do { 13074 const Type *Ty = QTy.getTypePtr(); 13075 switch (Ty->getTypeClass()) { 13076 #define TYPE(Class, Base) 13077 #define ABSTRACT_TYPE(Class, Base) 13078 #define NON_CANONICAL_TYPE(Class, Base) 13079 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 13080 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 13081 #include "clang/AST/TypeNodes.def" 13082 QTy = QualType(); 13083 break; 13084 // These types are never variably-modified. 13085 case Type::Builtin: 13086 case Type::Complex: 13087 case Type::Vector: 13088 case Type::ExtVector: 13089 case Type::Record: 13090 case Type::Enum: 13091 case Type::Elaborated: 13092 case Type::TemplateSpecialization: 13093 case Type::ObjCObject: 13094 case Type::ObjCInterface: 13095 case Type::ObjCObjectPointer: 13096 llvm_unreachable("type class is never variably-modified!"); 13097 case Type::Adjusted: 13098 QTy = cast<AdjustedType>(Ty)->getOriginalType(); 13099 break; 13100 case Type::Decayed: 13101 QTy = cast<DecayedType>(Ty)->getPointeeType(); 13102 break; 13103 case Type::Pointer: 13104 QTy = cast<PointerType>(Ty)->getPointeeType(); 13105 break; 13106 case Type::BlockPointer: 13107 QTy = cast<BlockPointerType>(Ty)->getPointeeType(); 13108 break; 13109 case Type::LValueReference: 13110 case Type::RValueReference: 13111 QTy = cast<ReferenceType>(Ty)->getPointeeType(); 13112 break; 13113 case Type::MemberPointer: 13114 QTy = cast<MemberPointerType>(Ty)->getPointeeType(); 13115 break; 13116 case Type::ConstantArray: 13117 case Type::IncompleteArray: 13118 // Losing element qualification here is fine. 13119 QTy = cast<ArrayType>(Ty)->getElementType(); 13120 break; 13121 case Type::VariableArray: { 13122 // Losing element qualification here is fine. 13123 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 13124 13125 // Unknown size indication requires no size computation. 13126 // Otherwise, evaluate and record it. 13127 if (auto Size = VAT->getSizeExpr()) { 13128 if (!CSI->isVLATypeCaptured(VAT)) { 13129 RecordDecl *CapRecord = nullptr; 13130 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 13131 CapRecord = LSI->Lambda; 13132 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13133 CapRecord = CRSI->TheRecordDecl; 13134 } 13135 if (CapRecord) { 13136 auto ExprLoc = Size->getExprLoc(); 13137 auto SizeType = Context.getSizeType(); 13138 // Build the non-static data member. 13139 auto Field = FieldDecl::Create( 13140 Context, CapRecord, ExprLoc, ExprLoc, 13141 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 13142 /*BW*/ nullptr, /*Mutable*/ false, 13143 /*InitStyle*/ ICIS_NoInit); 13144 Field->setImplicit(true); 13145 Field->setAccess(AS_private); 13146 Field->setCapturedVLAType(VAT); 13147 CapRecord->addDecl(Field); 13148 13149 CSI->addVLATypeCapture(ExprLoc, SizeType); 13150 } 13151 } 13152 } 13153 QTy = VAT->getElementType(); 13154 break; 13155 } 13156 case Type::FunctionProto: 13157 case Type::FunctionNoProto: 13158 QTy = cast<FunctionType>(Ty)->getReturnType(); 13159 break; 13160 case Type::Paren: 13161 case Type::TypeOf: 13162 case Type::UnaryTransform: 13163 case Type::Attributed: 13164 case Type::SubstTemplateTypeParm: 13165 case Type::PackExpansion: 13166 // Keep walking after single level desugaring. 13167 QTy = QTy.getSingleStepDesugaredType(getASTContext()); 13168 break; 13169 case Type::Typedef: 13170 QTy = cast<TypedefType>(Ty)->desugar(); 13171 break; 13172 case Type::Decltype: 13173 QTy = cast<DecltypeType>(Ty)->desugar(); 13174 break; 13175 case Type::Auto: 13176 QTy = cast<AutoType>(Ty)->getDeducedType(); 13177 break; 13178 case Type::TypeOfExpr: 13179 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 13180 break; 13181 case Type::Atomic: 13182 QTy = cast<AtomicType>(Ty)->getValueType(); 13183 break; 13184 } 13185 } while (!QTy.isNull() && QTy->isVariablyModifiedType()); 13186 } 13187 13188 if (getLangOpts().OpenMP) { 13189 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13190 // OpenMP private variables should not be captured in outer scope, so 13191 // just break here. Similarly, global variables that are captured in a 13192 // target region should not be captured outside the scope of the region. 13193 if (RSI->CapRegionKind == CR_OpenMP) { 13194 auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel); 13195 // When we detect target captures we are looking from inside the 13196 // target region, therefore we need to propagate the capture from the 13197 // enclosing region. Therefore, the capture is not initially nested. 13198 if (isTargetCap) 13199 FunctionScopesIndex--; 13200 13201 if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) { 13202 Nested = !isTargetCap; 13203 DeclRefType = DeclRefType.getUnqualifiedType(); 13204 CaptureType = Context.getLValueReferenceType(DeclRefType); 13205 break; 13206 } 13207 ++OpenMPLevel; 13208 } 13209 } 13210 } 13211 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13212 // No capture-default, and this is not an explicit capture 13213 // so cannot capture this variable. 13214 if (BuildAndDiagnose) { 13215 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13216 Diag(Var->getLocation(), diag::note_previous_decl) 13217 << Var->getDeclName(); 13218 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13219 diag::note_lambda_decl); 13220 // FIXME: If we error out because an outer lambda can not implicitly 13221 // capture a variable that an inner lambda explicitly captures, we 13222 // should have the inner lambda do the explicit capture - because 13223 // it makes for cleaner diagnostics later. This would purely be done 13224 // so that the diagnostic does not misleadingly claim that a variable 13225 // can not be captured by a lambda implicitly even though it is captured 13226 // explicitly. Suggestion: 13227 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13228 // at the function head 13229 // - cache the StartingDeclContext - this must be a lambda 13230 // - captureInLambda in the innermost lambda the variable. 13231 } 13232 return true; 13233 } 13234 13235 FunctionScopesIndex--; 13236 DC = ParentDC; 13237 Explicit = false; 13238 } while (!VarDC->Equals(DC)); 13239 13240 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13241 // computing the type of the capture at each step, checking type-specific 13242 // requirements, and adding captures if requested. 13243 // If the variable had already been captured previously, we start capturing 13244 // at the lambda nested within that one. 13245 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13246 ++I) { 13247 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13248 13249 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13250 if (!captureInBlock(BSI, Var, ExprLoc, 13251 BuildAndDiagnose, CaptureType, 13252 DeclRefType, Nested, *this)) 13253 return true; 13254 Nested = true; 13255 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13256 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13257 BuildAndDiagnose, CaptureType, 13258 DeclRefType, Nested, *this)) 13259 return true; 13260 Nested = true; 13261 } else { 13262 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13263 if (!captureInLambda(LSI, Var, ExprLoc, 13264 BuildAndDiagnose, CaptureType, 13265 DeclRefType, Nested, Kind, EllipsisLoc, 13266 /*IsTopScope*/I == N - 1, *this)) 13267 return true; 13268 Nested = true; 13269 } 13270 } 13271 return false; 13272 } 13273 13274 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13275 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13276 QualType CaptureType; 13277 QualType DeclRefType; 13278 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13279 /*BuildAndDiagnose=*/true, CaptureType, 13280 DeclRefType, nullptr); 13281 } 13282 13283 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13284 QualType CaptureType; 13285 QualType DeclRefType; 13286 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13287 /*BuildAndDiagnose=*/false, CaptureType, 13288 DeclRefType, nullptr); 13289 } 13290 13291 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13292 QualType CaptureType; 13293 QualType DeclRefType; 13294 13295 // Determine whether we can capture this variable. 13296 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13297 /*BuildAndDiagnose=*/false, CaptureType, 13298 DeclRefType, nullptr)) 13299 return QualType(); 13300 13301 return DeclRefType; 13302 } 13303 13304 13305 13306 // If either the type of the variable or the initializer is dependent, 13307 // return false. Otherwise, determine whether the variable is a constant 13308 // expression. Use this if you need to know if a variable that might or 13309 // might not be dependent is truly a constant expression. 13310 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13311 ASTContext &Context) { 13312 13313 if (Var->getType()->isDependentType()) 13314 return false; 13315 const VarDecl *DefVD = nullptr; 13316 Var->getAnyInitializer(DefVD); 13317 if (!DefVD) 13318 return false; 13319 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13320 Expr *Init = cast<Expr>(Eval->Value); 13321 if (Init->isValueDependent()) 13322 return false; 13323 return IsVariableAConstantExpression(Var, Context); 13324 } 13325 13326 13327 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13328 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13329 // an object that satisfies the requirements for appearing in a 13330 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13331 // is immediately applied." This function handles the lvalue-to-rvalue 13332 // conversion part. 13333 MaybeODRUseExprs.erase(E->IgnoreParens()); 13334 13335 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13336 // to a variable that is a constant expression, and if so, identify it as 13337 // a reference to a variable that does not involve an odr-use of that 13338 // variable. 13339 if (LambdaScopeInfo *LSI = getCurLambda()) { 13340 Expr *SansParensExpr = E->IgnoreParens(); 13341 VarDecl *Var = nullptr; 13342 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13343 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13344 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13345 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13346 13347 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13348 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13349 } 13350 } 13351 13352 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13353 Res = CorrectDelayedTyposInExpr(Res); 13354 13355 if (!Res.isUsable()) 13356 return Res; 13357 13358 // If a constant-expression is a reference to a variable where we delay 13359 // deciding whether it is an odr-use, just assume we will apply the 13360 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13361 // (a non-type template argument), we have special handling anyway. 13362 UpdateMarkingForLValueToRValue(Res.get()); 13363 return Res; 13364 } 13365 13366 void Sema::CleanupVarDeclMarking() { 13367 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 13368 e = MaybeODRUseExprs.end(); 13369 i != e; ++i) { 13370 VarDecl *Var; 13371 SourceLocation Loc; 13372 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 13373 Var = cast<VarDecl>(DRE->getDecl()); 13374 Loc = DRE->getLocation(); 13375 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 13376 Var = cast<VarDecl>(ME->getMemberDecl()); 13377 Loc = ME->getMemberLoc(); 13378 } else { 13379 llvm_unreachable("Unexpected expression"); 13380 } 13381 13382 MarkVarDeclODRUsed(Var, Loc, *this, 13383 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13384 } 13385 13386 MaybeODRUseExprs.clear(); 13387 } 13388 13389 13390 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13391 VarDecl *Var, Expr *E) { 13392 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13393 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13394 Var->setReferenced(); 13395 13396 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13397 bool MarkODRUsed = true; 13398 13399 // If the context is not potentially evaluated, this is not an odr-use and 13400 // does not trigger instantiation. 13401 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13402 if (SemaRef.isUnevaluatedContext()) 13403 return; 13404 13405 // If we don't yet know whether this context is going to end up being an 13406 // evaluated context, and we're referencing a variable from an enclosing 13407 // scope, add a potential capture. 13408 // 13409 // FIXME: Is this necessary? These contexts are only used for default 13410 // arguments, where local variables can't be used. 13411 const bool RefersToEnclosingScope = 13412 (SemaRef.CurContext != Var->getDeclContext() && 13413 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13414 if (RefersToEnclosingScope) { 13415 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13416 // If a variable could potentially be odr-used, defer marking it so 13417 // until we finish analyzing the full expression for any 13418 // lvalue-to-rvalue 13419 // or discarded value conversions that would obviate odr-use. 13420 // Add it to the list of potential captures that will be analyzed 13421 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13422 // unless the variable is a reference that was initialized by a constant 13423 // expression (this will never need to be captured or odr-used). 13424 assert(E && "Capture variable should be used in an expression."); 13425 if (!Var->getType()->isReferenceType() || 13426 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13427 LSI->addPotentialCapture(E->IgnoreParens()); 13428 } 13429 } 13430 13431 if (!isTemplateInstantiation(TSK)) 13432 return; 13433 13434 // Instantiate, but do not mark as odr-used, variable templates. 13435 MarkODRUsed = false; 13436 } 13437 13438 VarTemplateSpecializationDecl *VarSpec = 13439 dyn_cast<VarTemplateSpecializationDecl>(Var); 13440 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13441 "Can't instantiate a partial template specialization."); 13442 13443 // Perform implicit instantiation of static data members, static data member 13444 // templates of class templates, and variable template specializations. Delay 13445 // instantiations of variable templates, except for those that could be used 13446 // in a constant expression. 13447 if (isTemplateInstantiation(TSK)) { 13448 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13449 13450 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13451 if (Var->getPointOfInstantiation().isInvalid()) { 13452 // This is a modification of an existing AST node. Notify listeners. 13453 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13454 L->StaticDataMemberInstantiated(Var); 13455 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13456 // Don't bother trying to instantiate it again, unless we might need 13457 // its initializer before we get to the end of the TU. 13458 TryInstantiating = false; 13459 } 13460 13461 if (Var->getPointOfInstantiation().isInvalid()) 13462 Var->setTemplateSpecializationKind(TSK, Loc); 13463 13464 if (TryInstantiating) { 13465 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13466 bool InstantiationDependent = false; 13467 bool IsNonDependent = 13468 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13469 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13470 : true; 13471 13472 // Do not instantiate specializations that are still type-dependent. 13473 if (IsNonDependent) { 13474 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13475 // Do not defer instantiations of variables which could be used in a 13476 // constant expression. 13477 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13478 } else { 13479 SemaRef.PendingInstantiations 13480 .push_back(std::make_pair(Var, PointOfInstantiation)); 13481 } 13482 } 13483 } 13484 } 13485 13486 if(!MarkODRUsed) return; 13487 13488 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13489 // the requirements for appearing in a constant expression (5.19) and, if 13490 // it is an object, the lvalue-to-rvalue conversion (4.1) 13491 // is immediately applied." We check the first part here, and 13492 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13493 // Note that we use the C++11 definition everywhere because nothing in 13494 // C++03 depends on whether we get the C++03 version correct. The second 13495 // part does not apply to references, since they are not objects. 13496 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13497 // A reference initialized by a constant expression can never be 13498 // odr-used, so simply ignore it. 13499 if (!Var->getType()->isReferenceType()) 13500 SemaRef.MaybeODRUseExprs.insert(E); 13501 } else 13502 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13503 /*MaxFunctionScopeIndex ptr*/ nullptr); 13504 } 13505 13506 /// \brief Mark a variable referenced, and check whether it is odr-used 13507 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13508 /// used directly for normal expressions referring to VarDecl. 13509 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13510 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13511 } 13512 13513 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13514 Decl *D, Expr *E, bool OdrUse) { 13515 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13516 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13517 return; 13518 } 13519 13520 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13521 13522 // If this is a call to a method via a cast, also mark the method in the 13523 // derived class used in case codegen can devirtualize the call. 13524 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13525 if (!ME) 13526 return; 13527 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13528 if (!MD) 13529 return; 13530 // Only attempt to devirtualize if this is truly a virtual call. 13531 bool IsVirtualCall = MD->isVirtual() && 13532 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13533 if (!IsVirtualCall) 13534 return; 13535 const Expr *Base = ME->getBase(); 13536 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13537 if (!MostDerivedClassDecl) 13538 return; 13539 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13540 if (!DM || DM->isPure()) 13541 return; 13542 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13543 } 13544 13545 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13546 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13547 // TODO: update this with DR# once a defect report is filed. 13548 // C++11 defect. The address of a pure member should not be an ODR use, even 13549 // if it's a qualified reference. 13550 bool OdrUse = true; 13551 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13552 if (Method->isVirtual()) 13553 OdrUse = false; 13554 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13555 } 13556 13557 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13558 void Sema::MarkMemberReferenced(MemberExpr *E) { 13559 // C++11 [basic.def.odr]p2: 13560 // A non-overloaded function whose name appears as a potentially-evaluated 13561 // expression or a member of a set of candidate functions, if selected by 13562 // overload resolution when referred to from a potentially-evaluated 13563 // expression, is odr-used, unless it is a pure virtual function and its 13564 // name is not explicitly qualified. 13565 bool OdrUse = true; 13566 if (E->performsVirtualDispatch(getLangOpts())) { 13567 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13568 if (Method->isPure()) 13569 OdrUse = false; 13570 } 13571 SourceLocation Loc = E->getMemberLoc().isValid() ? 13572 E->getMemberLoc() : E->getLocStart(); 13573 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13574 } 13575 13576 /// \brief Perform marking for a reference to an arbitrary declaration. It 13577 /// marks the declaration referenced, and performs odr-use checking for 13578 /// functions and variables. This method should not be used when building a 13579 /// normal expression which refers to a variable. 13580 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13581 if (OdrUse) { 13582 if (auto *VD = dyn_cast<VarDecl>(D)) { 13583 MarkVariableReferenced(Loc, VD); 13584 return; 13585 } 13586 } 13587 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13588 MarkFunctionReferenced(Loc, FD, OdrUse); 13589 return; 13590 } 13591 D->setReferenced(); 13592 } 13593 13594 namespace { 13595 // Mark all of the declarations referenced 13596 // FIXME: Not fully implemented yet! We need to have a better understanding 13597 // of when we're entering 13598 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13599 Sema &S; 13600 SourceLocation Loc; 13601 13602 public: 13603 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13604 13605 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13606 13607 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13608 bool TraverseRecordType(RecordType *T); 13609 }; 13610 } 13611 13612 bool MarkReferencedDecls::TraverseTemplateArgument( 13613 const TemplateArgument &Arg) { 13614 if (Arg.getKind() == TemplateArgument::Declaration) { 13615 if (Decl *D = Arg.getAsDecl()) 13616 S.MarkAnyDeclReferenced(Loc, D, true); 13617 } 13618 13619 return Inherited::TraverseTemplateArgument(Arg); 13620 } 13621 13622 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13623 if (ClassTemplateSpecializationDecl *Spec 13624 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13625 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13626 return TraverseTemplateArguments(Args.data(), Args.size()); 13627 } 13628 13629 return true; 13630 } 13631 13632 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13633 MarkReferencedDecls Marker(*this, Loc); 13634 Marker.TraverseType(Context.getCanonicalType(T)); 13635 } 13636 13637 namespace { 13638 /// \brief Helper class that marks all of the declarations referenced by 13639 /// potentially-evaluated subexpressions as "referenced". 13640 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13641 Sema &S; 13642 bool SkipLocalVariables; 13643 13644 public: 13645 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13646 13647 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13648 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13649 13650 void VisitDeclRefExpr(DeclRefExpr *E) { 13651 // If we were asked not to visit local variables, don't. 13652 if (SkipLocalVariables) { 13653 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13654 if (VD->hasLocalStorage()) 13655 return; 13656 } 13657 13658 S.MarkDeclRefReferenced(E); 13659 } 13660 13661 void VisitMemberExpr(MemberExpr *E) { 13662 S.MarkMemberReferenced(E); 13663 Inherited::VisitMemberExpr(E); 13664 } 13665 13666 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13667 S.MarkFunctionReferenced(E->getLocStart(), 13668 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13669 Visit(E->getSubExpr()); 13670 } 13671 13672 void VisitCXXNewExpr(CXXNewExpr *E) { 13673 if (E->getOperatorNew()) 13674 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13675 if (E->getOperatorDelete()) 13676 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13677 Inherited::VisitCXXNewExpr(E); 13678 } 13679 13680 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13681 if (E->getOperatorDelete()) 13682 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13683 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13684 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13685 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13686 S.MarkFunctionReferenced(E->getLocStart(), 13687 S.LookupDestructor(Record)); 13688 } 13689 13690 Inherited::VisitCXXDeleteExpr(E); 13691 } 13692 13693 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13694 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13695 Inherited::VisitCXXConstructExpr(E); 13696 } 13697 13698 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13699 Visit(E->getExpr()); 13700 } 13701 13702 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13703 Inherited::VisitImplicitCastExpr(E); 13704 13705 if (E->getCastKind() == CK_LValueToRValue) 13706 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13707 } 13708 }; 13709 } 13710 13711 /// \brief Mark any declarations that appear within this expression or any 13712 /// potentially-evaluated subexpressions as "referenced". 13713 /// 13714 /// \param SkipLocalVariables If true, don't mark local variables as 13715 /// 'referenced'. 13716 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13717 bool SkipLocalVariables) { 13718 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13719 } 13720 13721 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 13722 /// of the program being compiled. 13723 /// 13724 /// This routine emits the given diagnostic when the code currently being 13725 /// type-checked is "potentially evaluated", meaning that there is a 13726 /// possibility that the code will actually be executable. Code in sizeof() 13727 /// expressions, code used only during overload resolution, etc., are not 13728 /// potentially evaluated. This routine will suppress such diagnostics or, 13729 /// in the absolutely nutty case of potentially potentially evaluated 13730 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 13731 /// later. 13732 /// 13733 /// This routine should be used for all diagnostics that describe the run-time 13734 /// behavior of a program, such as passing a non-POD value through an ellipsis. 13735 /// Failure to do so will likely result in spurious diagnostics or failures 13736 /// during overload resolution or within sizeof/alignof/typeof/typeid. 13737 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 13738 const PartialDiagnostic &PD) { 13739 switch (ExprEvalContexts.back().Context) { 13740 case Unevaluated: 13741 case UnevaluatedAbstract: 13742 // The argument will never be evaluated, so don't complain. 13743 break; 13744 13745 case ConstantEvaluated: 13746 // Relevant diagnostics should be produced by constant evaluation. 13747 break; 13748 13749 case PotentiallyEvaluated: 13750 case PotentiallyEvaluatedIfUsed: 13751 if (Statement && getCurFunctionOrMethodDecl()) { 13752 FunctionScopes.back()->PossiblyUnreachableDiags. 13753 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 13754 } 13755 else 13756 Diag(Loc, PD); 13757 13758 return true; 13759 } 13760 13761 return false; 13762 } 13763 13764 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 13765 CallExpr *CE, FunctionDecl *FD) { 13766 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 13767 return false; 13768 13769 // If we're inside a decltype's expression, don't check for a valid return 13770 // type or construct temporaries until we know whether this is the last call. 13771 if (ExprEvalContexts.back().IsDecltype) { 13772 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 13773 return false; 13774 } 13775 13776 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 13777 FunctionDecl *FD; 13778 CallExpr *CE; 13779 13780 public: 13781 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 13782 : FD(FD), CE(CE) { } 13783 13784 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 13785 if (!FD) { 13786 S.Diag(Loc, diag::err_call_incomplete_return) 13787 << T << CE->getSourceRange(); 13788 return; 13789 } 13790 13791 S.Diag(Loc, diag::err_call_function_incomplete_return) 13792 << CE->getSourceRange() << FD->getDeclName() << T; 13793 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 13794 << FD->getDeclName(); 13795 } 13796 } Diagnoser(FD, CE); 13797 13798 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 13799 return true; 13800 13801 return false; 13802 } 13803 13804 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 13805 // will prevent this condition from triggering, which is what we want. 13806 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 13807 SourceLocation Loc; 13808 13809 unsigned diagnostic = diag::warn_condition_is_assignment; 13810 bool IsOrAssign = false; 13811 13812 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 13813 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 13814 return; 13815 13816 IsOrAssign = Op->getOpcode() == BO_OrAssign; 13817 13818 // Greylist some idioms by putting them into a warning subcategory. 13819 if (ObjCMessageExpr *ME 13820 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 13821 Selector Sel = ME->getSelector(); 13822 13823 // self = [<foo> init...] 13824 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 13825 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13826 13827 // <foo> = [<bar> nextObject] 13828 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 13829 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13830 } 13831 13832 Loc = Op->getOperatorLoc(); 13833 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 13834 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 13835 return; 13836 13837 IsOrAssign = Op->getOperator() == OO_PipeEqual; 13838 Loc = Op->getOperatorLoc(); 13839 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 13840 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 13841 else { 13842 // Not an assignment. 13843 return; 13844 } 13845 13846 Diag(Loc, diagnostic) << E->getSourceRange(); 13847 13848 SourceLocation Open = E->getLocStart(); 13849 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 13850 Diag(Loc, diag::note_condition_assign_silence) 13851 << FixItHint::CreateInsertion(Open, "(") 13852 << FixItHint::CreateInsertion(Close, ")"); 13853 13854 if (IsOrAssign) 13855 Diag(Loc, diag::note_condition_or_assign_to_comparison) 13856 << FixItHint::CreateReplacement(Loc, "!="); 13857 else 13858 Diag(Loc, diag::note_condition_assign_to_comparison) 13859 << FixItHint::CreateReplacement(Loc, "=="); 13860 } 13861 13862 /// \brief Redundant parentheses over an equality comparison can indicate 13863 /// that the user intended an assignment used as condition. 13864 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 13865 // Don't warn if the parens came from a macro. 13866 SourceLocation parenLoc = ParenE->getLocStart(); 13867 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 13868 return; 13869 // Don't warn for dependent expressions. 13870 if (ParenE->isTypeDependent()) 13871 return; 13872 13873 Expr *E = ParenE->IgnoreParens(); 13874 13875 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 13876 if (opE->getOpcode() == BO_EQ && 13877 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 13878 == Expr::MLV_Valid) { 13879 SourceLocation Loc = opE->getOperatorLoc(); 13880 13881 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 13882 SourceRange ParenERange = ParenE->getSourceRange(); 13883 Diag(Loc, diag::note_equality_comparison_silence) 13884 << FixItHint::CreateRemoval(ParenERange.getBegin()) 13885 << FixItHint::CreateRemoval(ParenERange.getEnd()); 13886 Diag(Loc, diag::note_equality_comparison_to_assign) 13887 << FixItHint::CreateReplacement(Loc, "="); 13888 } 13889 } 13890 13891 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 13892 DiagnoseAssignmentAsCondition(E); 13893 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 13894 DiagnoseEqualityWithExtraParens(parenE); 13895 13896 ExprResult result = CheckPlaceholderExpr(E); 13897 if (result.isInvalid()) return ExprError(); 13898 E = result.get(); 13899 13900 if (!E->isTypeDependent()) { 13901 if (getLangOpts().CPlusPlus) 13902 return CheckCXXBooleanCondition(E); // C++ 6.4p4 13903 13904 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 13905 if (ERes.isInvalid()) 13906 return ExprError(); 13907 E = ERes.get(); 13908 13909 QualType T = E->getType(); 13910 if (!T->isScalarType()) { // C99 6.8.4.1p1 13911 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 13912 << T << E->getSourceRange(); 13913 return ExprError(); 13914 } 13915 CheckBoolLikeConversion(E, Loc); 13916 } 13917 13918 return E; 13919 } 13920 13921 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 13922 Expr *SubExpr) { 13923 if (!SubExpr) 13924 return ExprError(); 13925 13926 return CheckBooleanCondition(SubExpr, Loc); 13927 } 13928 13929 namespace { 13930 /// A visitor for rebuilding a call to an __unknown_any expression 13931 /// to have an appropriate type. 13932 struct RebuildUnknownAnyFunction 13933 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 13934 13935 Sema &S; 13936 13937 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 13938 13939 ExprResult VisitStmt(Stmt *S) { 13940 llvm_unreachable("unexpected statement!"); 13941 } 13942 13943 ExprResult VisitExpr(Expr *E) { 13944 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 13945 << E->getSourceRange(); 13946 return ExprError(); 13947 } 13948 13949 /// Rebuild an expression which simply semantically wraps another 13950 /// expression which it shares the type and value kind of. 13951 template <class T> ExprResult rebuildSugarExpr(T *E) { 13952 ExprResult SubResult = Visit(E->getSubExpr()); 13953 if (SubResult.isInvalid()) return ExprError(); 13954 13955 Expr *SubExpr = SubResult.get(); 13956 E->setSubExpr(SubExpr); 13957 E->setType(SubExpr->getType()); 13958 E->setValueKind(SubExpr->getValueKind()); 13959 assert(E->getObjectKind() == OK_Ordinary); 13960 return E; 13961 } 13962 13963 ExprResult VisitParenExpr(ParenExpr *E) { 13964 return rebuildSugarExpr(E); 13965 } 13966 13967 ExprResult VisitUnaryExtension(UnaryOperator *E) { 13968 return rebuildSugarExpr(E); 13969 } 13970 13971 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 13972 ExprResult SubResult = Visit(E->getSubExpr()); 13973 if (SubResult.isInvalid()) return ExprError(); 13974 13975 Expr *SubExpr = SubResult.get(); 13976 E->setSubExpr(SubExpr); 13977 E->setType(S.Context.getPointerType(SubExpr->getType())); 13978 assert(E->getValueKind() == VK_RValue); 13979 assert(E->getObjectKind() == OK_Ordinary); 13980 return E; 13981 } 13982 13983 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 13984 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 13985 13986 E->setType(VD->getType()); 13987 13988 assert(E->getValueKind() == VK_RValue); 13989 if (S.getLangOpts().CPlusPlus && 13990 !(isa<CXXMethodDecl>(VD) && 13991 cast<CXXMethodDecl>(VD)->isInstance())) 13992 E->setValueKind(VK_LValue); 13993 13994 return E; 13995 } 13996 13997 ExprResult VisitMemberExpr(MemberExpr *E) { 13998 return resolveDecl(E, E->getMemberDecl()); 13999 } 14000 14001 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14002 return resolveDecl(E, E->getDecl()); 14003 } 14004 }; 14005 } 14006 14007 /// Given a function expression of unknown-any type, try to rebuild it 14008 /// to have a function type. 14009 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14010 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14011 if (Result.isInvalid()) return ExprError(); 14012 return S.DefaultFunctionArrayConversion(Result.get()); 14013 } 14014 14015 namespace { 14016 /// A visitor for rebuilding an expression of type __unknown_anytype 14017 /// into one which resolves the type directly on the referring 14018 /// expression. Strict preservation of the original source 14019 /// structure is not a goal. 14020 struct RebuildUnknownAnyExpr 14021 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14022 14023 Sema &S; 14024 14025 /// The current destination type. 14026 QualType DestType; 14027 14028 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14029 : S(S), DestType(CastType) {} 14030 14031 ExprResult VisitStmt(Stmt *S) { 14032 llvm_unreachable("unexpected statement!"); 14033 } 14034 14035 ExprResult VisitExpr(Expr *E) { 14036 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14037 << E->getSourceRange(); 14038 return ExprError(); 14039 } 14040 14041 ExprResult VisitCallExpr(CallExpr *E); 14042 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14043 14044 /// Rebuild an expression which simply semantically wraps another 14045 /// expression which it shares the type and value kind of. 14046 template <class T> ExprResult rebuildSugarExpr(T *E) { 14047 ExprResult SubResult = Visit(E->getSubExpr()); 14048 if (SubResult.isInvalid()) return ExprError(); 14049 Expr *SubExpr = SubResult.get(); 14050 E->setSubExpr(SubExpr); 14051 E->setType(SubExpr->getType()); 14052 E->setValueKind(SubExpr->getValueKind()); 14053 assert(E->getObjectKind() == OK_Ordinary); 14054 return E; 14055 } 14056 14057 ExprResult VisitParenExpr(ParenExpr *E) { 14058 return rebuildSugarExpr(E); 14059 } 14060 14061 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14062 return rebuildSugarExpr(E); 14063 } 14064 14065 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14066 const PointerType *Ptr = DestType->getAs<PointerType>(); 14067 if (!Ptr) { 14068 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14069 << E->getSourceRange(); 14070 return ExprError(); 14071 } 14072 assert(E->getValueKind() == VK_RValue); 14073 assert(E->getObjectKind() == OK_Ordinary); 14074 E->setType(DestType); 14075 14076 // Build the sub-expression as if it were an object of the pointee type. 14077 DestType = Ptr->getPointeeType(); 14078 ExprResult SubResult = Visit(E->getSubExpr()); 14079 if (SubResult.isInvalid()) return ExprError(); 14080 E->setSubExpr(SubResult.get()); 14081 return E; 14082 } 14083 14084 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14085 14086 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14087 14088 ExprResult VisitMemberExpr(MemberExpr *E) { 14089 return resolveDecl(E, E->getMemberDecl()); 14090 } 14091 14092 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14093 return resolveDecl(E, E->getDecl()); 14094 } 14095 }; 14096 } 14097 14098 /// Rebuilds a call expression which yielded __unknown_anytype. 14099 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14100 Expr *CalleeExpr = E->getCallee(); 14101 14102 enum FnKind { 14103 FK_MemberFunction, 14104 FK_FunctionPointer, 14105 FK_BlockPointer 14106 }; 14107 14108 FnKind Kind; 14109 QualType CalleeType = CalleeExpr->getType(); 14110 if (CalleeType == S.Context.BoundMemberTy) { 14111 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14112 Kind = FK_MemberFunction; 14113 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14114 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14115 CalleeType = Ptr->getPointeeType(); 14116 Kind = FK_FunctionPointer; 14117 } else { 14118 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14119 Kind = FK_BlockPointer; 14120 } 14121 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14122 14123 // Verify that this is a legal result type of a function. 14124 if (DestType->isArrayType() || DestType->isFunctionType()) { 14125 unsigned diagID = diag::err_func_returning_array_function; 14126 if (Kind == FK_BlockPointer) 14127 diagID = diag::err_block_returning_array_function; 14128 14129 S.Diag(E->getExprLoc(), diagID) 14130 << DestType->isFunctionType() << DestType; 14131 return ExprError(); 14132 } 14133 14134 // Otherwise, go ahead and set DestType as the call's result. 14135 E->setType(DestType.getNonLValueExprType(S.Context)); 14136 E->setValueKind(Expr::getValueKindForType(DestType)); 14137 assert(E->getObjectKind() == OK_Ordinary); 14138 14139 // Rebuild the function type, replacing the result type with DestType. 14140 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14141 if (Proto) { 14142 // __unknown_anytype(...) is a special case used by the debugger when 14143 // it has no idea what a function's signature is. 14144 // 14145 // We want to build this call essentially under the K&R 14146 // unprototyped rules, but making a FunctionNoProtoType in C++ 14147 // would foul up all sorts of assumptions. However, we cannot 14148 // simply pass all arguments as variadic arguments, nor can we 14149 // portably just call the function under a non-variadic type; see 14150 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14151 // However, it turns out that in practice it is generally safe to 14152 // call a function declared as "A foo(B,C,D);" under the prototype 14153 // "A foo(B,C,D,...);". The only known exception is with the 14154 // Windows ABI, where any variadic function is implicitly cdecl 14155 // regardless of its normal CC. Therefore we change the parameter 14156 // types to match the types of the arguments. 14157 // 14158 // This is a hack, but it is far superior to moving the 14159 // corresponding target-specific code from IR-gen to Sema/AST. 14160 14161 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14162 SmallVector<QualType, 8> ArgTypes; 14163 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14164 ArgTypes.reserve(E->getNumArgs()); 14165 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14166 Expr *Arg = E->getArg(i); 14167 QualType ArgType = Arg->getType(); 14168 if (E->isLValue()) { 14169 ArgType = S.Context.getLValueReferenceType(ArgType); 14170 } else if (E->isXValue()) { 14171 ArgType = S.Context.getRValueReferenceType(ArgType); 14172 } 14173 ArgTypes.push_back(ArgType); 14174 } 14175 ParamTypes = ArgTypes; 14176 } 14177 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14178 Proto->getExtProtoInfo()); 14179 } else { 14180 DestType = S.Context.getFunctionNoProtoType(DestType, 14181 FnType->getExtInfo()); 14182 } 14183 14184 // Rebuild the appropriate pointer-to-function type. 14185 switch (Kind) { 14186 case FK_MemberFunction: 14187 // Nothing to do. 14188 break; 14189 14190 case FK_FunctionPointer: 14191 DestType = S.Context.getPointerType(DestType); 14192 break; 14193 14194 case FK_BlockPointer: 14195 DestType = S.Context.getBlockPointerType(DestType); 14196 break; 14197 } 14198 14199 // Finally, we can recurse. 14200 ExprResult CalleeResult = Visit(CalleeExpr); 14201 if (!CalleeResult.isUsable()) return ExprError(); 14202 E->setCallee(CalleeResult.get()); 14203 14204 // Bind a temporary if necessary. 14205 return S.MaybeBindToTemporary(E); 14206 } 14207 14208 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14209 // Verify that this is a legal result type of a call. 14210 if (DestType->isArrayType() || DestType->isFunctionType()) { 14211 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14212 << DestType->isFunctionType() << DestType; 14213 return ExprError(); 14214 } 14215 14216 // Rewrite the method result type if available. 14217 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14218 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14219 Method->setReturnType(DestType); 14220 } 14221 14222 // Change the type of the message. 14223 E->setType(DestType.getNonReferenceType()); 14224 E->setValueKind(Expr::getValueKindForType(DestType)); 14225 14226 return S.MaybeBindToTemporary(E); 14227 } 14228 14229 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14230 // The only case we should ever see here is a function-to-pointer decay. 14231 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14232 assert(E->getValueKind() == VK_RValue); 14233 assert(E->getObjectKind() == OK_Ordinary); 14234 14235 E->setType(DestType); 14236 14237 // Rebuild the sub-expression as the pointee (function) type. 14238 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14239 14240 ExprResult Result = Visit(E->getSubExpr()); 14241 if (!Result.isUsable()) return ExprError(); 14242 14243 E->setSubExpr(Result.get()); 14244 return E; 14245 } else if (E->getCastKind() == CK_LValueToRValue) { 14246 assert(E->getValueKind() == VK_RValue); 14247 assert(E->getObjectKind() == OK_Ordinary); 14248 14249 assert(isa<BlockPointerType>(E->getType())); 14250 14251 E->setType(DestType); 14252 14253 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14254 DestType = S.Context.getLValueReferenceType(DestType); 14255 14256 ExprResult Result = Visit(E->getSubExpr()); 14257 if (!Result.isUsable()) return ExprError(); 14258 14259 E->setSubExpr(Result.get()); 14260 return E; 14261 } else { 14262 llvm_unreachable("Unhandled cast type!"); 14263 } 14264 } 14265 14266 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14267 ExprValueKind ValueKind = VK_LValue; 14268 QualType Type = DestType; 14269 14270 // We know how to make this work for certain kinds of decls: 14271 14272 // - functions 14273 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14274 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14275 DestType = Ptr->getPointeeType(); 14276 ExprResult Result = resolveDecl(E, VD); 14277 if (Result.isInvalid()) return ExprError(); 14278 return S.ImpCastExprToType(Result.get(), Type, 14279 CK_FunctionToPointerDecay, VK_RValue); 14280 } 14281 14282 if (!Type->isFunctionType()) { 14283 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14284 << VD << E->getSourceRange(); 14285 return ExprError(); 14286 } 14287 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14288 // We must match the FunctionDecl's type to the hack introduced in 14289 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14290 // type. See the lengthy commentary in that routine. 14291 QualType FDT = FD->getType(); 14292 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14293 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14294 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14295 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14296 SourceLocation Loc = FD->getLocation(); 14297 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14298 FD->getDeclContext(), 14299 Loc, Loc, FD->getNameInfo().getName(), 14300 DestType, FD->getTypeSourceInfo(), 14301 SC_None, false/*isInlineSpecified*/, 14302 FD->hasPrototype(), 14303 false/*isConstexprSpecified*/); 14304 14305 if (FD->getQualifier()) 14306 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14307 14308 SmallVector<ParmVarDecl*, 16> Params; 14309 for (const auto &AI : FT->param_types()) { 14310 ParmVarDecl *Param = 14311 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14312 Param->setScopeInfo(0, Params.size()); 14313 Params.push_back(Param); 14314 } 14315 NewFD->setParams(Params); 14316 DRE->setDecl(NewFD); 14317 VD = DRE->getDecl(); 14318 } 14319 } 14320 14321 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14322 if (MD->isInstance()) { 14323 ValueKind = VK_RValue; 14324 Type = S.Context.BoundMemberTy; 14325 } 14326 14327 // Function references aren't l-values in C. 14328 if (!S.getLangOpts().CPlusPlus) 14329 ValueKind = VK_RValue; 14330 14331 // - variables 14332 } else if (isa<VarDecl>(VD)) { 14333 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14334 Type = RefTy->getPointeeType(); 14335 } else if (Type->isFunctionType()) { 14336 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14337 << VD << E->getSourceRange(); 14338 return ExprError(); 14339 } 14340 14341 // - nothing else 14342 } else { 14343 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14344 << VD << E->getSourceRange(); 14345 return ExprError(); 14346 } 14347 14348 // Modifying the declaration like this is friendly to IR-gen but 14349 // also really dangerous. 14350 VD->setType(DestType); 14351 E->setType(Type); 14352 E->setValueKind(ValueKind); 14353 return E; 14354 } 14355 14356 /// Check a cast of an unknown-any type. We intentionally only 14357 /// trigger this for C-style casts. 14358 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14359 Expr *CastExpr, CastKind &CastKind, 14360 ExprValueKind &VK, CXXCastPath &Path) { 14361 // Rewrite the casted expression from scratch. 14362 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14363 if (!result.isUsable()) return ExprError(); 14364 14365 CastExpr = result.get(); 14366 VK = CastExpr->getValueKind(); 14367 CastKind = CK_NoOp; 14368 14369 return CastExpr; 14370 } 14371 14372 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14373 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14374 } 14375 14376 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14377 Expr *arg, QualType ¶mType) { 14378 // If the syntactic form of the argument is not an explicit cast of 14379 // any sort, just do default argument promotion. 14380 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14381 if (!castArg) { 14382 ExprResult result = DefaultArgumentPromotion(arg); 14383 if (result.isInvalid()) return ExprError(); 14384 paramType = result.get()->getType(); 14385 return result; 14386 } 14387 14388 // Otherwise, use the type that was written in the explicit cast. 14389 assert(!arg->hasPlaceholderType()); 14390 paramType = castArg->getTypeAsWritten(); 14391 14392 // Copy-initialize a parameter of that type. 14393 InitializedEntity entity = 14394 InitializedEntity::InitializeParameter(Context, paramType, 14395 /*consumed*/ false); 14396 return PerformCopyInitialization(entity, callLoc, arg); 14397 } 14398 14399 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14400 Expr *orig = E; 14401 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14402 while (true) { 14403 E = E->IgnoreParenImpCasts(); 14404 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14405 E = call->getCallee(); 14406 diagID = diag::err_uncasted_call_of_unknown_any; 14407 } else { 14408 break; 14409 } 14410 } 14411 14412 SourceLocation loc; 14413 NamedDecl *d; 14414 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14415 loc = ref->getLocation(); 14416 d = ref->getDecl(); 14417 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14418 loc = mem->getMemberLoc(); 14419 d = mem->getMemberDecl(); 14420 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14421 diagID = diag::err_uncasted_call_of_unknown_any; 14422 loc = msg->getSelectorStartLoc(); 14423 d = msg->getMethodDecl(); 14424 if (!d) { 14425 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14426 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14427 << orig->getSourceRange(); 14428 return ExprError(); 14429 } 14430 } else { 14431 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14432 << E->getSourceRange(); 14433 return ExprError(); 14434 } 14435 14436 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14437 14438 // Never recoverable. 14439 return ExprError(); 14440 } 14441 14442 /// Check for operands with placeholder types and complain if found. 14443 /// Returns true if there was an error and no recovery was possible. 14444 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14445 if (!getLangOpts().CPlusPlus) { 14446 // C cannot handle TypoExpr nodes on either side of a binop because it 14447 // doesn't handle dependent types properly, so make sure any TypoExprs have 14448 // been dealt with before checking the operands. 14449 ExprResult Result = CorrectDelayedTyposInExpr(E); 14450 if (!Result.isUsable()) return ExprError(); 14451 E = Result.get(); 14452 } 14453 14454 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14455 if (!placeholderType) return E; 14456 14457 switch (placeholderType->getKind()) { 14458 14459 // Overloaded expressions. 14460 case BuiltinType::Overload: { 14461 // Try to resolve a single function template specialization. 14462 // This is obligatory. 14463 ExprResult result = E; 14464 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14465 return result; 14466 14467 // If that failed, try to recover with a call. 14468 } else { 14469 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14470 /*complain*/ true); 14471 return result; 14472 } 14473 } 14474 14475 // Bound member functions. 14476 case BuiltinType::BoundMember: { 14477 ExprResult result = E; 14478 const Expr *BME = E->IgnoreParens(); 14479 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14480 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14481 if (isa<CXXPseudoDestructorExpr>(BME)) { 14482 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14483 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14484 if (ME->getMemberNameInfo().getName().getNameKind() == 14485 DeclarationName::CXXDestructorName) 14486 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14487 } 14488 tryToRecoverWithCall(result, PD, 14489 /*complain*/ true); 14490 return result; 14491 } 14492 14493 // ARC unbridged casts. 14494 case BuiltinType::ARCUnbridgedCast: { 14495 Expr *realCast = stripARCUnbridgedCast(E); 14496 diagnoseARCUnbridgedCast(realCast); 14497 return realCast; 14498 } 14499 14500 // Expressions of unknown type. 14501 case BuiltinType::UnknownAny: 14502 return diagnoseUnknownAnyExpr(*this, E); 14503 14504 // Pseudo-objects. 14505 case BuiltinType::PseudoObject: 14506 return checkPseudoObjectRValue(E); 14507 14508 case BuiltinType::BuiltinFn: { 14509 // Accept __noop without parens by implicitly converting it to a call expr. 14510 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14511 if (DRE) { 14512 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14513 if (FD->getBuiltinID() == Builtin::BI__noop) { 14514 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14515 CK_BuiltinFnToFnPtr).get(); 14516 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14517 VK_RValue, SourceLocation()); 14518 } 14519 } 14520 14521 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14522 return ExprError(); 14523 } 14524 14525 // Expressions of unknown type. 14526 case BuiltinType::OMPArraySection: 14527 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14528 return ExprError(); 14529 14530 // Everything else should be impossible. 14531 #define BUILTIN_TYPE(Id, SingletonId) \ 14532 case BuiltinType::Id: 14533 #define PLACEHOLDER_TYPE(Id, SingletonId) 14534 #include "clang/AST/BuiltinTypes.def" 14535 break; 14536 } 14537 14538 llvm_unreachable("invalid placeholder type!"); 14539 } 14540 14541 bool Sema::CheckCaseExpression(Expr *E) { 14542 if (E->isTypeDependent()) 14543 return true; 14544 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14545 return E->getType()->isIntegralOrEnumerationType(); 14546 return false; 14547 } 14548 14549 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14550 ExprResult 14551 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14552 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14553 "Unknown Objective-C Boolean value!"); 14554 QualType BoolT = Context.ObjCBuiltinBoolTy; 14555 if (!Context.getBOOLDecl()) { 14556 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14557 Sema::LookupOrdinaryName); 14558 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14559 NamedDecl *ND = Result.getFoundDecl(); 14560 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14561 Context.setBOOLDecl(TD); 14562 } 14563 } 14564 if (Context.getBOOLDecl()) 14565 BoolT = Context.getBOOLType(); 14566 return new (Context) 14567 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14568 } 14569