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 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName(); 354 return true; 355 } 356 357 // See if this is a deleted function. 358 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 359 if (FD->isDeleted()) { 360 Diag(Loc, diag::err_deleted_function_use); 361 NoteDeletedFunction(FD); 362 return true; 363 } 364 365 // If the function has a deduced return type, and we can't deduce it, 366 // then we can't use it either. 367 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 368 DeduceReturnType(FD, Loc)) 369 return true; 370 } 371 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 372 ObjCPropertyAccess); 373 374 DiagnoseUnusedOfDecl(*this, D, Loc); 375 376 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 377 378 return false; 379 } 380 381 /// \brief Retrieve the message suffix that should be added to a 382 /// diagnostic complaining about the given function being deleted or 383 /// unavailable. 384 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 385 std::string Message; 386 if (FD->getAvailability(&Message)) 387 return ": " + Message; 388 389 return std::string(); 390 } 391 392 /// DiagnoseSentinelCalls - This routine checks whether a call or 393 /// message-send is to a declaration with the sentinel attribute, and 394 /// if so, it checks that the requirements of the sentinel are 395 /// satisfied. 396 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 397 ArrayRef<Expr *> Args) { 398 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 399 if (!attr) 400 return; 401 402 // The number of formal parameters of the declaration. 403 unsigned numFormalParams; 404 405 // The kind of declaration. This is also an index into a %select in 406 // the diagnostic. 407 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 408 409 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 410 numFormalParams = MD->param_size(); 411 calleeType = CT_Method; 412 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 413 numFormalParams = FD->param_size(); 414 calleeType = CT_Function; 415 } else if (isa<VarDecl>(D)) { 416 QualType type = cast<ValueDecl>(D)->getType(); 417 const FunctionType *fn = nullptr; 418 if (const PointerType *ptr = type->getAs<PointerType>()) { 419 fn = ptr->getPointeeType()->getAs<FunctionType>(); 420 if (!fn) return; 421 calleeType = CT_Function; 422 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 423 fn = ptr->getPointeeType()->castAs<FunctionType>(); 424 calleeType = CT_Block; 425 } else { 426 return; 427 } 428 429 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 430 numFormalParams = proto->getNumParams(); 431 } else { 432 numFormalParams = 0; 433 } 434 } else { 435 return; 436 } 437 438 // "nullPos" is the number of formal parameters at the end which 439 // effectively count as part of the variadic arguments. This is 440 // useful if you would prefer to not have *any* formal parameters, 441 // but the language forces you to have at least one. 442 unsigned nullPos = attr->getNullPos(); 443 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 444 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 445 446 // The number of arguments which should follow the sentinel. 447 unsigned numArgsAfterSentinel = attr->getSentinel(); 448 449 // If there aren't enough arguments for all the formal parameters, 450 // the sentinel, and the args after the sentinel, complain. 451 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 452 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 453 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 454 return; 455 } 456 457 // Otherwise, find the sentinel expression. 458 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 459 if (!sentinelExpr) return; 460 if (sentinelExpr->isValueDependent()) return; 461 if (Context.isSentinelNullExpr(sentinelExpr)) return; 462 463 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 464 // or 'NULL' if those are actually defined in the context. Only use 465 // 'nil' for ObjC methods, where it's much more likely that the 466 // variadic arguments form a list of object pointers. 467 SourceLocation MissingNilLoc 468 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 // If we are here, we are not calling a function but taking 510 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 511 if (getLangOpts().OpenCL) { 512 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 513 return ExprError(); 514 } 515 E = ImpCastExprToType(E, Context.getPointerType(Ty), 516 CK_FunctionToPointerDecay).get(); 517 } else if (Ty->isArrayType()) { 518 // In C90 mode, arrays only promote to pointers if the array expression is 519 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 520 // type 'array of type' is converted to an expression that has type 'pointer 521 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 522 // that has type 'array of type' ...". The relevant change is "an lvalue" 523 // (C90) to "an expression" (C99). 524 // 525 // C++ 4.2p1: 526 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 527 // T" can be converted to an rvalue of type "pointer to T". 528 // 529 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 530 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 531 CK_ArrayToPointerDecay).get(); 532 } 533 return E; 534 } 535 536 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 537 // Check to see if we are dereferencing a null pointer. If so, 538 // and if not volatile-qualified, this is undefined behavior that the 539 // optimizer will delete, so warn about it. People sometimes try to use this 540 // to get a deterministic trap and are surprised by clang's behavior. This 541 // only handles the pattern "*null", which is a very syntactic check. 542 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 543 if (UO->getOpcode() == UO_Deref && 544 UO->getSubExpr()->IgnoreParenCasts()-> 545 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 546 !UO->getType().isVolatileQualified()) { 547 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 548 S.PDiag(diag::warn_indirection_through_null) 549 << UO->getSubExpr()->getSourceRange()); 550 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 551 S.PDiag(diag::note_indirection_through_null)); 552 } 553 } 554 555 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 556 SourceLocation AssignLoc, 557 const Expr* RHS) { 558 const ObjCIvarDecl *IV = OIRE->getDecl(); 559 if (!IV) 560 return; 561 562 DeclarationName MemberName = IV->getDeclName(); 563 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 564 if (!Member || !Member->isStr("isa")) 565 return; 566 567 const Expr *Base = OIRE->getBase(); 568 QualType BaseType = Base->getType(); 569 if (OIRE->isArrow()) 570 BaseType = BaseType->getPointeeType(); 571 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 572 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 573 ObjCInterfaceDecl *ClassDeclared = nullptr; 574 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 575 if (!ClassDeclared->getSuperClass() 576 && (*ClassDeclared->ivar_begin()) == IV) { 577 if (RHS) { 578 NamedDecl *ObjectSetClass = 579 S.LookupSingleName(S.TUScope, 580 &S.Context.Idents.get("object_setClass"), 581 SourceLocation(), S.LookupOrdinaryName); 582 if (ObjectSetClass) { 583 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 584 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 585 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 586 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 587 AssignLoc), ",") << 588 FixItHint::CreateInsertion(RHSLocEnd, ")"); 589 } 590 else 591 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 592 } else { 593 NamedDecl *ObjectGetClass = 594 S.LookupSingleName(S.TUScope, 595 &S.Context.Idents.get("object_getClass"), 596 SourceLocation(), S.LookupOrdinaryName); 597 if (ObjectGetClass) 598 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 599 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 600 FixItHint::CreateReplacement( 601 SourceRange(OIRE->getOpLoc(), 602 OIRE->getLocEnd()), ")"); 603 else 604 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 605 } 606 S.Diag(IV->getLocation(), diag::note_ivar_decl); 607 } 608 } 609 } 610 611 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 612 // Handle any placeholder expressions which made it here. 613 if (E->getType()->isPlaceholderType()) { 614 ExprResult result = CheckPlaceholderExpr(E); 615 if (result.isInvalid()) return ExprError(); 616 E = result.get(); 617 } 618 619 // C++ [conv.lval]p1: 620 // A glvalue of a non-function, non-array type T can be 621 // converted to a prvalue. 622 if (!E->isGLValue()) return E; 623 624 QualType T = E->getType(); 625 assert(!T.isNull() && "r-value conversion on typeless expression?"); 626 627 // We don't want to throw lvalue-to-rvalue casts on top of 628 // expressions of certain types in C++. 629 if (getLangOpts().CPlusPlus && 630 (E->getType() == Context.OverloadTy || 631 T->isDependentType() || 632 T->isRecordType())) 633 return E; 634 635 // The C standard is actually really unclear on this point, and 636 // DR106 tells us what the result should be but not why. It's 637 // generally best to say that void types just doesn't undergo 638 // lvalue-to-rvalue at all. Note that expressions of unqualified 639 // 'void' type are never l-values, but qualified void can be. 640 if (T->isVoidType()) 641 return E; 642 643 // OpenCL usually rejects direct accesses to values of 'half' type. 644 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 645 T->isHalfType()) { 646 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 647 << 0 << T; 648 return ExprError(); 649 } 650 651 CheckForNullPointerDereference(*this, E); 652 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 653 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 654 &Context.Idents.get("object_getClass"), 655 SourceLocation(), LookupOrdinaryName); 656 if (ObjectGetClass) 657 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 658 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 659 FixItHint::CreateReplacement( 660 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 661 else 662 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 663 } 664 else if (const ObjCIvarRefExpr *OIRE = 665 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 666 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 667 668 // C++ [conv.lval]p1: 669 // [...] If T is a non-class type, the type of the prvalue is the 670 // cv-unqualified version of T. Otherwise, the type of the 671 // rvalue is T. 672 // 673 // C99 6.3.2.1p2: 674 // If the lvalue has qualified type, the value has the unqualified 675 // version of the type of the lvalue; otherwise, the value has the 676 // type of the lvalue. 677 if (T.hasQualifiers()) 678 T = T.getUnqualifiedType(); 679 680 if (T->isMemberPointerType() && 681 Context.getTargetInfo().getCXXABI().isMicrosoft()) 682 RequireCompleteType(E->getExprLoc(), T, 0); 683 684 UpdateMarkingForLValueToRValue(E); 685 686 // Loading a __weak object implicitly retains the value, so we need a cleanup to 687 // balance that. 688 if (getLangOpts().ObjCAutoRefCount && 689 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 690 ExprNeedsCleanups = true; 691 692 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 693 nullptr, VK_RValue); 694 695 // C11 6.3.2.1p2: 696 // ... if the lvalue has atomic type, the value has the non-atomic version 697 // of the type of the lvalue ... 698 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 699 T = Atomic->getValueType().getUnqualifiedType(); 700 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 701 nullptr, VK_RValue); 702 } 703 704 return Res; 705 } 706 707 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 708 ExprResult Res = DefaultFunctionArrayConversion(E); 709 if (Res.isInvalid()) 710 return ExprError(); 711 Res = DefaultLvalueConversion(Res.get()); 712 if (Res.isInvalid()) 713 return ExprError(); 714 return Res; 715 } 716 717 /// CallExprUnaryConversions - a special case of an unary conversion 718 /// performed on a function designator of a call expression. 719 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 720 QualType Ty = E->getType(); 721 ExprResult Res = E; 722 // Only do implicit cast for a function type, but not for a pointer 723 // to function type. 724 if (Ty->isFunctionType()) { 725 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 726 CK_FunctionToPointerDecay).get(); 727 if (Res.isInvalid()) 728 return ExprError(); 729 } 730 Res = DefaultLvalueConversion(Res.get()); 731 if (Res.isInvalid()) 732 return ExprError(); 733 return Res.get(); 734 } 735 736 /// UsualUnaryConversions - Performs various conversions that are common to most 737 /// operators (C99 6.3). The conversions of array and function types are 738 /// sometimes suppressed. For example, the array->pointer conversion doesn't 739 /// apply if the array is an argument to the sizeof or address (&) operators. 740 /// In these instances, this routine should *not* be called. 741 ExprResult Sema::UsualUnaryConversions(Expr *E) { 742 // First, convert to an r-value. 743 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 744 if (Res.isInvalid()) 745 return ExprError(); 746 E = Res.get(); 747 748 QualType Ty = E->getType(); 749 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 750 751 // Half FP have to be promoted to float unless it is natively supported 752 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 753 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 754 755 // Try to perform integral promotions if the object has a theoretically 756 // promotable type. 757 if (Ty->isIntegralOrUnscopedEnumerationType()) { 758 // C99 6.3.1.1p2: 759 // 760 // The following may be used in an expression wherever an int or 761 // unsigned int may be used: 762 // - an object or expression with an integer type whose integer 763 // conversion rank is less than or equal to the rank of int 764 // and unsigned int. 765 // - A bit-field of type _Bool, int, signed int, or unsigned int. 766 // 767 // If an int can represent all values of the original type, the 768 // value is converted to an int; otherwise, it is converted to an 769 // unsigned int. These are called the integer promotions. All 770 // other types are unchanged by the integer promotions. 771 772 QualType PTy = Context.isPromotableBitField(E); 773 if (!PTy.isNull()) { 774 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 775 return E; 776 } 777 if (Ty->isPromotableIntegerType()) { 778 QualType PT = Context.getPromotedIntegerType(Ty); 779 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 780 return E; 781 } 782 } 783 return E; 784 } 785 786 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 787 /// do not have a prototype. Arguments that have type float or __fp16 788 /// are promoted to double. All other argument types are converted by 789 /// UsualUnaryConversions(). 790 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 791 QualType Ty = E->getType(); 792 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 793 794 ExprResult Res = UsualUnaryConversions(E); 795 if (Res.isInvalid()) 796 return ExprError(); 797 E = Res.get(); 798 799 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 800 // double. 801 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 802 if (BTy && (BTy->getKind() == BuiltinType::Half || 803 BTy->getKind() == BuiltinType::Float)) 804 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 805 806 // C++ performs lvalue-to-rvalue conversion as a default argument 807 // promotion, even on class types, but note: 808 // C++11 [conv.lval]p2: 809 // When an lvalue-to-rvalue conversion occurs in an unevaluated 810 // operand or a subexpression thereof the value contained in the 811 // referenced object is not accessed. Otherwise, if the glvalue 812 // has a class type, the conversion copy-initializes a temporary 813 // of type T from the glvalue and the result of the conversion 814 // is a prvalue for the temporary. 815 // FIXME: add some way to gate this entire thing for correctness in 816 // potentially potentially evaluated contexts. 817 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 818 ExprResult Temp = PerformCopyInitialization( 819 InitializedEntity::InitializeTemporary(E->getType()), 820 E->getExprLoc(), E); 821 if (Temp.isInvalid()) 822 return ExprError(); 823 E = Temp.get(); 824 } 825 826 return E; 827 } 828 829 /// Determine the degree of POD-ness for an expression. 830 /// Incomplete types are considered POD, since this check can be performed 831 /// when we're in an unevaluated context. 832 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 833 if (Ty->isIncompleteType()) { 834 // C++11 [expr.call]p7: 835 // After these conversions, if the argument does not have arithmetic, 836 // enumeration, pointer, pointer to member, or class type, the program 837 // is ill-formed. 838 // 839 // Since we've already performed array-to-pointer and function-to-pointer 840 // decay, the only such type in C++ is cv void. This also handles 841 // initializer lists as variadic arguments. 842 if (Ty->isVoidType()) 843 return VAK_Invalid; 844 845 if (Ty->isObjCObjectType()) 846 return VAK_Invalid; 847 return VAK_Valid; 848 } 849 850 if (Ty.isCXX98PODType(Context)) 851 return VAK_Valid; 852 853 // C++11 [expr.call]p7: 854 // Passing a potentially-evaluated argument of class type (Clause 9) 855 // having a non-trivial copy constructor, a non-trivial move constructor, 856 // or a non-trivial destructor, with no corresponding parameter, 857 // is conditionally-supported with implementation-defined semantics. 858 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 859 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 860 if (!Record->hasNonTrivialCopyConstructor() && 861 !Record->hasNonTrivialMoveConstructor() && 862 !Record->hasNonTrivialDestructor()) 863 return VAK_ValidInCXX11; 864 865 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 866 return VAK_Valid; 867 868 if (Ty->isObjCObjectType()) 869 return VAK_Invalid; 870 871 if (getLangOpts().MSVCCompat) 872 return VAK_MSVCUndefined; 873 874 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 875 // permitted to reject them. We should consider doing so. 876 return VAK_Undefined; 877 } 878 879 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 880 // Don't allow one to pass an Objective-C interface to a vararg. 881 const QualType &Ty = E->getType(); 882 VarArgKind VAK = isValidVarArgType(Ty); 883 884 // Complain about passing non-POD types through varargs. 885 switch (VAK) { 886 case VAK_ValidInCXX11: 887 DiagRuntimeBehavior( 888 E->getLocStart(), nullptr, 889 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 890 << Ty << CT); 891 // Fall through. 892 case VAK_Valid: 893 if (Ty->isRecordType()) { 894 // This is unlikely to be what the user intended. If the class has a 895 // 'c_str' member function, the user probably meant to call that. 896 DiagRuntimeBehavior(E->getLocStart(), nullptr, 897 PDiag(diag::warn_pass_class_arg_to_vararg) 898 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 899 } 900 break; 901 902 case VAK_Undefined: 903 case VAK_MSVCUndefined: 904 DiagRuntimeBehavior( 905 E->getLocStart(), nullptr, 906 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 907 << getLangOpts().CPlusPlus11 << Ty << CT); 908 break; 909 910 case VAK_Invalid: 911 if (Ty->isObjCObjectType()) 912 DiagRuntimeBehavior( 913 E->getLocStart(), nullptr, 914 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 915 << Ty << CT); 916 else 917 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 918 << isa<InitListExpr>(E) << Ty << CT; 919 break; 920 } 921 } 922 923 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 924 /// will create a trap if the resulting type is not a POD type. 925 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 926 FunctionDecl *FDecl) { 927 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 928 // Strip the unbridged-cast placeholder expression off, if applicable. 929 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 930 (CT == VariadicMethod || 931 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 932 E = stripARCUnbridgedCast(E); 933 934 // Otherwise, do normal placeholder checking. 935 } else { 936 ExprResult ExprRes = CheckPlaceholderExpr(E); 937 if (ExprRes.isInvalid()) 938 return ExprError(); 939 E = ExprRes.get(); 940 } 941 } 942 943 ExprResult ExprRes = DefaultArgumentPromotion(E); 944 if (ExprRes.isInvalid()) 945 return ExprError(); 946 E = ExprRes.get(); 947 948 // Diagnostics regarding non-POD argument types are 949 // emitted along with format string checking in Sema::CheckFunctionCall(). 950 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 951 // Turn this into a trap. 952 CXXScopeSpec SS; 953 SourceLocation TemplateKWLoc; 954 UnqualifiedId Name; 955 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 956 E->getLocStart()); 957 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 958 Name, true, false); 959 if (TrapFn.isInvalid()) 960 return ExprError(); 961 962 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 963 E->getLocStart(), None, 964 E->getLocEnd()); 965 if (Call.isInvalid()) 966 return ExprError(); 967 968 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 969 Call.get(), E); 970 if (Comma.isInvalid()) 971 return ExprError(); 972 return Comma.get(); 973 } 974 975 if (!getLangOpts().CPlusPlus && 976 RequireCompleteType(E->getExprLoc(), E->getType(), 977 diag::err_call_incomplete_argument)) 978 return ExprError(); 979 980 return E; 981 } 982 983 /// \brief Converts an integer to complex float type. Helper function of 984 /// UsualArithmeticConversions() 985 /// 986 /// \return false if the integer expression is an integer type and is 987 /// successfully converted to the complex type. 988 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 989 ExprResult &ComplexExpr, 990 QualType IntTy, 991 QualType ComplexTy, 992 bool SkipCast) { 993 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 994 if (SkipCast) return false; 995 if (IntTy->isIntegerType()) { 996 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 997 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 998 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 999 CK_FloatingRealToComplex); 1000 } else { 1001 assert(IntTy->isComplexIntegerType()); 1002 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1003 CK_IntegralComplexToFloatingComplex); 1004 } 1005 return false; 1006 } 1007 1008 /// \brief Handle arithmetic conversion with complex types. Helper function of 1009 /// UsualArithmeticConversions() 1010 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1011 ExprResult &RHS, QualType LHSType, 1012 QualType RHSType, 1013 bool IsCompAssign) { 1014 // if we have an integer operand, the result is the complex type. 1015 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1016 /*skipCast*/false)) 1017 return LHSType; 1018 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1019 /*skipCast*/IsCompAssign)) 1020 return RHSType; 1021 1022 // This handles complex/complex, complex/float, or float/complex. 1023 // When both operands are complex, the shorter operand is converted to the 1024 // type of the longer, and that is the type of the result. This corresponds 1025 // to what is done when combining two real floating-point operands. 1026 // The fun begins when size promotion occur across type domains. 1027 // From H&S 6.3.4: When one operand is complex and the other is a real 1028 // floating-point type, the less precise type is converted, within it's 1029 // real or complex domain, to the precision of the other type. For example, 1030 // when combining a "long double" with a "double _Complex", the 1031 // "double _Complex" is promoted to "long double _Complex". 1032 1033 // Compute the rank of the two types, regardless of whether they are complex. 1034 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1035 1036 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1037 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1038 QualType LHSElementType = 1039 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1040 QualType RHSElementType = 1041 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1042 1043 QualType ResultType = S.Context.getComplexType(LHSElementType); 1044 if (Order < 0) { 1045 // Promote the precision of the LHS if not an assignment. 1046 ResultType = S.Context.getComplexType(RHSElementType); 1047 if (!IsCompAssign) { 1048 if (LHSComplexType) 1049 LHS = 1050 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1051 else 1052 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1053 } 1054 } else if (Order > 0) { 1055 // Promote the precision of the RHS. 1056 if (RHSComplexType) 1057 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1058 else 1059 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1060 } 1061 return ResultType; 1062 } 1063 1064 /// \brief Hande arithmetic conversion from integer to float. Helper function 1065 /// of UsualArithmeticConversions() 1066 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1067 ExprResult &IntExpr, 1068 QualType FloatTy, QualType IntTy, 1069 bool ConvertFloat, bool ConvertInt) { 1070 if (IntTy->isIntegerType()) { 1071 if (ConvertInt) 1072 // Convert intExpr to the lhs floating point type. 1073 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1074 CK_IntegralToFloating); 1075 return FloatTy; 1076 } 1077 1078 // Convert both sides to the appropriate complex float. 1079 assert(IntTy->isComplexIntegerType()); 1080 QualType result = S.Context.getComplexType(FloatTy); 1081 1082 // _Complex int -> _Complex float 1083 if (ConvertInt) 1084 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1085 CK_IntegralComplexToFloatingComplex); 1086 1087 // float -> _Complex float 1088 if (ConvertFloat) 1089 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1090 CK_FloatingRealToComplex); 1091 1092 return result; 1093 } 1094 1095 /// \brief Handle arithmethic conversion with floating point types. Helper 1096 /// function of UsualArithmeticConversions() 1097 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1098 ExprResult &RHS, QualType LHSType, 1099 QualType RHSType, bool IsCompAssign) { 1100 bool LHSFloat = LHSType->isRealFloatingType(); 1101 bool RHSFloat = RHSType->isRealFloatingType(); 1102 1103 // If we have two real floating types, convert the smaller operand 1104 // to the bigger result. 1105 if (LHSFloat && RHSFloat) { 1106 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1107 if (order > 0) { 1108 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1109 return LHSType; 1110 } 1111 1112 assert(order < 0 && "illegal float comparison"); 1113 if (!IsCompAssign) 1114 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1115 return RHSType; 1116 } 1117 1118 if (LHSFloat) { 1119 // Half FP has to be promoted to float unless it is natively supported 1120 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1121 LHSType = S.Context.FloatTy; 1122 1123 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1124 /*convertFloat=*/!IsCompAssign, 1125 /*convertInt=*/ true); 1126 } 1127 assert(RHSFloat); 1128 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1129 /*convertInt=*/ true, 1130 /*convertFloat=*/!IsCompAssign); 1131 } 1132 1133 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1134 1135 namespace { 1136 /// These helper callbacks are placed in an anonymous namespace to 1137 /// permit their use as function template parameters. 1138 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1139 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1140 } 1141 1142 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1143 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1144 CK_IntegralComplexCast); 1145 } 1146 } 1147 1148 /// \brief Handle integer arithmetic conversions. Helper function of 1149 /// UsualArithmeticConversions() 1150 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1151 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1152 ExprResult &RHS, QualType LHSType, 1153 QualType RHSType, bool IsCompAssign) { 1154 // The rules for this case are in C99 6.3.1.8 1155 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1156 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1157 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1158 if (LHSSigned == RHSSigned) { 1159 // Same signedness; use the higher-ranked type 1160 if (order >= 0) { 1161 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1162 return LHSType; 1163 } else if (!IsCompAssign) 1164 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1165 return RHSType; 1166 } else if (order != (LHSSigned ? 1 : -1)) { 1167 // The unsigned type has greater than or equal rank to the 1168 // signed type, so use the unsigned type 1169 if (RHSSigned) { 1170 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1171 return LHSType; 1172 } else if (!IsCompAssign) 1173 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1174 return RHSType; 1175 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1176 // The two types are different widths; if we are here, that 1177 // means the signed type is larger than the unsigned type, so 1178 // use the signed type. 1179 if (LHSSigned) { 1180 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1181 return LHSType; 1182 } else if (!IsCompAssign) 1183 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1184 return RHSType; 1185 } else { 1186 // The signed type is higher-ranked than the unsigned type, 1187 // but isn't actually any bigger (like unsigned int and long 1188 // on most 32-bit systems). Use the unsigned type corresponding 1189 // to the signed type. 1190 QualType result = 1191 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1192 RHS = (*doRHSCast)(S, RHS.get(), result); 1193 if (!IsCompAssign) 1194 LHS = (*doLHSCast)(S, LHS.get(), result); 1195 return result; 1196 } 1197 } 1198 1199 /// \brief Handle conversions with GCC complex int extension. Helper function 1200 /// of UsualArithmeticConversions() 1201 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1202 ExprResult &RHS, QualType LHSType, 1203 QualType RHSType, 1204 bool IsCompAssign) { 1205 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1206 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1207 1208 if (LHSComplexInt && RHSComplexInt) { 1209 QualType LHSEltType = LHSComplexInt->getElementType(); 1210 QualType RHSEltType = RHSComplexInt->getElementType(); 1211 QualType ScalarType = 1212 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1213 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1214 1215 return S.Context.getComplexType(ScalarType); 1216 } 1217 1218 if (LHSComplexInt) { 1219 QualType LHSEltType = LHSComplexInt->getElementType(); 1220 QualType ScalarType = 1221 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1222 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1223 QualType ComplexType = S.Context.getComplexType(ScalarType); 1224 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1225 CK_IntegralRealToComplex); 1226 1227 return ComplexType; 1228 } 1229 1230 assert(RHSComplexInt); 1231 1232 QualType RHSEltType = RHSComplexInt->getElementType(); 1233 QualType ScalarType = 1234 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1235 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1236 QualType ComplexType = S.Context.getComplexType(ScalarType); 1237 1238 if (!IsCompAssign) 1239 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1240 CK_IntegralRealToComplex); 1241 return ComplexType; 1242 } 1243 1244 /// UsualArithmeticConversions - Performs various conversions that are common to 1245 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1246 /// routine returns the first non-arithmetic type found. The client is 1247 /// responsible for emitting appropriate error diagnostics. 1248 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1249 bool IsCompAssign) { 1250 if (!IsCompAssign) { 1251 LHS = UsualUnaryConversions(LHS.get()); 1252 if (LHS.isInvalid()) 1253 return QualType(); 1254 } 1255 1256 RHS = UsualUnaryConversions(RHS.get()); 1257 if (RHS.isInvalid()) 1258 return QualType(); 1259 1260 // For conversion purposes, we ignore any qualifiers. 1261 // For example, "const float" and "float" are equivalent. 1262 QualType LHSType = 1263 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1264 QualType RHSType = 1265 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1266 1267 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1268 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1269 LHSType = AtomicLHS->getValueType(); 1270 1271 // If both types are identical, no conversion is needed. 1272 if (LHSType == RHSType) 1273 return LHSType; 1274 1275 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1276 // The caller can deal with this (e.g. pointer + int). 1277 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1278 return QualType(); 1279 1280 // Apply unary and bitfield promotions to the LHS's type. 1281 QualType LHSUnpromotedType = LHSType; 1282 if (LHSType->isPromotableIntegerType()) 1283 LHSType = Context.getPromotedIntegerType(LHSType); 1284 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1285 if (!LHSBitfieldPromoteTy.isNull()) 1286 LHSType = LHSBitfieldPromoteTy; 1287 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1288 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1289 1290 // If both types are identical, no conversion is needed. 1291 if (LHSType == RHSType) 1292 return LHSType; 1293 1294 // At this point, we have two different arithmetic types. 1295 1296 // Handle complex types first (C99 6.3.1.8p1). 1297 if (LHSType->isComplexType() || RHSType->isComplexType()) 1298 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1299 IsCompAssign); 1300 1301 // Now handle "real" floating types (i.e. float, double, long double). 1302 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1303 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1304 IsCompAssign); 1305 1306 // Handle GCC complex int extension. 1307 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1308 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1309 IsCompAssign); 1310 1311 // Finally, we have two differing integer types. 1312 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1313 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1314 } 1315 1316 1317 //===----------------------------------------------------------------------===// 1318 // Semantic Analysis for various Expression Types 1319 //===----------------------------------------------------------------------===// 1320 1321 1322 ExprResult 1323 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1324 SourceLocation DefaultLoc, 1325 SourceLocation RParenLoc, 1326 Expr *ControllingExpr, 1327 ArrayRef<ParsedType> ArgTypes, 1328 ArrayRef<Expr *> ArgExprs) { 1329 unsigned NumAssocs = ArgTypes.size(); 1330 assert(NumAssocs == ArgExprs.size()); 1331 1332 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1333 for (unsigned i = 0; i < NumAssocs; ++i) { 1334 if (ArgTypes[i]) 1335 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1336 else 1337 Types[i] = nullptr; 1338 } 1339 1340 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1341 ControllingExpr, 1342 llvm::makeArrayRef(Types, NumAssocs), 1343 ArgExprs); 1344 delete [] Types; 1345 return ER; 1346 } 1347 1348 ExprResult 1349 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1350 SourceLocation DefaultLoc, 1351 SourceLocation RParenLoc, 1352 Expr *ControllingExpr, 1353 ArrayRef<TypeSourceInfo *> Types, 1354 ArrayRef<Expr *> Exprs) { 1355 unsigned NumAssocs = Types.size(); 1356 assert(NumAssocs == Exprs.size()); 1357 if (ControllingExpr->getType()->isPlaceholderType()) { 1358 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1359 if (result.isInvalid()) return ExprError(); 1360 ControllingExpr = result.get(); 1361 } 1362 1363 // The controlling expression is an unevaluated operand, so side effects are 1364 // likely unintended. 1365 if (ActiveTemplateInstantiations.empty() && 1366 ControllingExpr->HasSideEffects(Context, false)) 1367 Diag(ControllingExpr->getExprLoc(), 1368 diag::warn_side_effects_unevaluated_context); 1369 1370 bool TypeErrorFound = false, 1371 IsResultDependent = ControllingExpr->isTypeDependent(), 1372 ContainsUnexpandedParameterPack 1373 = ControllingExpr->containsUnexpandedParameterPack(); 1374 1375 for (unsigned i = 0; i < NumAssocs; ++i) { 1376 if (Exprs[i]->containsUnexpandedParameterPack()) 1377 ContainsUnexpandedParameterPack = true; 1378 1379 if (Types[i]) { 1380 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1381 ContainsUnexpandedParameterPack = true; 1382 1383 if (Types[i]->getType()->isDependentType()) { 1384 IsResultDependent = true; 1385 } else { 1386 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1387 // complete object type other than a variably modified type." 1388 unsigned D = 0; 1389 if (Types[i]->getType()->isIncompleteType()) 1390 D = diag::err_assoc_type_incomplete; 1391 else if (!Types[i]->getType()->isObjectType()) 1392 D = diag::err_assoc_type_nonobject; 1393 else if (Types[i]->getType()->isVariablyModifiedType()) 1394 D = diag::err_assoc_type_variably_modified; 1395 1396 if (D != 0) { 1397 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1398 << Types[i]->getTypeLoc().getSourceRange() 1399 << Types[i]->getType(); 1400 TypeErrorFound = true; 1401 } 1402 1403 // C11 6.5.1.1p2 "No two generic associations in the same generic 1404 // selection shall specify compatible types." 1405 for (unsigned j = i+1; j < NumAssocs; ++j) 1406 if (Types[j] && !Types[j]->getType()->isDependentType() && 1407 Context.typesAreCompatible(Types[i]->getType(), 1408 Types[j]->getType())) { 1409 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1410 diag::err_assoc_compatible_types) 1411 << Types[j]->getTypeLoc().getSourceRange() 1412 << Types[j]->getType() 1413 << Types[i]->getType(); 1414 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1415 diag::note_compat_assoc) 1416 << Types[i]->getTypeLoc().getSourceRange() 1417 << Types[i]->getType(); 1418 TypeErrorFound = true; 1419 } 1420 } 1421 } 1422 } 1423 if (TypeErrorFound) 1424 return ExprError(); 1425 1426 // If we determined that the generic selection is result-dependent, don't 1427 // try to compute the result expression. 1428 if (IsResultDependent) 1429 return new (Context) GenericSelectionExpr( 1430 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1431 ContainsUnexpandedParameterPack); 1432 1433 SmallVector<unsigned, 1> CompatIndices; 1434 unsigned DefaultIndex = -1U; 1435 for (unsigned i = 0; i < NumAssocs; ++i) { 1436 if (!Types[i]) 1437 DefaultIndex = i; 1438 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1439 Types[i]->getType())) 1440 CompatIndices.push_back(i); 1441 } 1442 1443 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1444 // type compatible with at most one of the types named in its generic 1445 // association list." 1446 if (CompatIndices.size() > 1) { 1447 // We strip parens here because the controlling expression is typically 1448 // parenthesized in macro definitions. 1449 ControllingExpr = ControllingExpr->IgnoreParens(); 1450 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1451 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1452 << (unsigned) CompatIndices.size(); 1453 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1454 E = CompatIndices.end(); I != E; ++I) { 1455 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1456 diag::note_compat_assoc) 1457 << Types[*I]->getTypeLoc().getSourceRange() 1458 << Types[*I]->getType(); 1459 } 1460 return ExprError(); 1461 } 1462 1463 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1464 // its controlling expression shall have type compatible with exactly one of 1465 // the types named in its generic association list." 1466 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1467 // We strip parens here because the controlling expression is typically 1468 // parenthesized in macro definitions. 1469 ControllingExpr = ControllingExpr->IgnoreParens(); 1470 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1471 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1472 return ExprError(); 1473 } 1474 1475 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1476 // type name that is compatible with the type of the controlling expression, 1477 // then the result expression of the generic selection is the expression 1478 // in that generic association. Otherwise, the result expression of the 1479 // generic selection is the expression in the default generic association." 1480 unsigned ResultIndex = 1481 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1482 1483 return new (Context) GenericSelectionExpr( 1484 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1485 ContainsUnexpandedParameterPack, ResultIndex); 1486 } 1487 1488 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1489 /// location of the token and the offset of the ud-suffix within it. 1490 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1491 unsigned Offset) { 1492 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1493 S.getLangOpts()); 1494 } 1495 1496 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1497 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1498 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1499 IdentifierInfo *UDSuffix, 1500 SourceLocation UDSuffixLoc, 1501 ArrayRef<Expr*> Args, 1502 SourceLocation LitEndLoc) { 1503 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1504 1505 QualType ArgTy[2]; 1506 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1507 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1508 if (ArgTy[ArgIdx]->isArrayType()) 1509 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1510 } 1511 1512 DeclarationName OpName = 1513 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1514 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1515 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1516 1517 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1518 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1519 /*AllowRaw*/false, /*AllowTemplate*/false, 1520 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1521 return ExprError(); 1522 1523 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1524 } 1525 1526 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1527 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1528 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1529 /// multiple tokens. However, the common case is that StringToks points to one 1530 /// string. 1531 /// 1532 ExprResult 1533 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1534 assert(!StringToks.empty() && "Must have at least one string!"); 1535 1536 StringLiteralParser Literal(StringToks, PP); 1537 if (Literal.hadError) 1538 return ExprError(); 1539 1540 SmallVector<SourceLocation, 4> StringTokLocs; 1541 for (unsigned i = 0; i != StringToks.size(); ++i) 1542 StringTokLocs.push_back(StringToks[i].getLocation()); 1543 1544 QualType CharTy = Context.CharTy; 1545 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1546 if (Literal.isWide()) { 1547 CharTy = Context.getWideCharType(); 1548 Kind = StringLiteral::Wide; 1549 } else if (Literal.isUTF8()) { 1550 Kind = StringLiteral::UTF8; 1551 } else if (Literal.isUTF16()) { 1552 CharTy = Context.Char16Ty; 1553 Kind = StringLiteral::UTF16; 1554 } else if (Literal.isUTF32()) { 1555 CharTy = Context.Char32Ty; 1556 Kind = StringLiteral::UTF32; 1557 } else if (Literal.isPascal()) { 1558 CharTy = Context.UnsignedCharTy; 1559 } 1560 1561 QualType CharTyConst = CharTy; 1562 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1563 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1564 CharTyConst.addConst(); 1565 1566 // Get an array type for the string, according to C99 6.4.5. This includes 1567 // the nul terminator character as well as the string length for pascal 1568 // strings. 1569 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1570 llvm::APInt(32, Literal.GetNumStringChars()+1), 1571 ArrayType::Normal, 0); 1572 1573 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1574 if (getLangOpts().OpenCL) { 1575 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1576 } 1577 1578 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1579 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1580 Kind, Literal.Pascal, StrTy, 1581 &StringTokLocs[0], 1582 StringTokLocs.size()); 1583 if (Literal.getUDSuffix().empty()) 1584 return Lit; 1585 1586 // We're building a user-defined literal. 1587 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1588 SourceLocation UDSuffixLoc = 1589 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1590 Literal.getUDSuffixOffset()); 1591 1592 // Make sure we're allowed user-defined literals here. 1593 if (!UDLScope) 1594 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1595 1596 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1597 // operator "" X (str, len) 1598 QualType SizeType = Context.getSizeType(); 1599 1600 DeclarationName OpName = 1601 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1602 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1603 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1604 1605 QualType ArgTy[] = { 1606 Context.getArrayDecayedType(StrTy), SizeType 1607 }; 1608 1609 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1610 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1611 /*AllowRaw*/false, /*AllowTemplate*/false, 1612 /*AllowStringTemplate*/true)) { 1613 1614 case LOLR_Cooked: { 1615 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1616 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1617 StringTokLocs[0]); 1618 Expr *Args[] = { Lit, LenArg }; 1619 1620 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1621 } 1622 1623 case LOLR_StringTemplate: { 1624 TemplateArgumentListInfo ExplicitArgs; 1625 1626 unsigned CharBits = Context.getIntWidth(CharTy); 1627 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1628 llvm::APSInt Value(CharBits, CharIsUnsigned); 1629 1630 TemplateArgument TypeArg(CharTy); 1631 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1632 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1633 1634 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1635 Value = Lit->getCodeUnit(I); 1636 TemplateArgument Arg(Context, Value, CharTy); 1637 TemplateArgumentLocInfo ArgInfo; 1638 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1639 } 1640 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1641 &ExplicitArgs); 1642 } 1643 case LOLR_Raw: 1644 case LOLR_Template: 1645 llvm_unreachable("unexpected literal operator lookup result"); 1646 case LOLR_Error: 1647 return ExprError(); 1648 } 1649 llvm_unreachable("unexpected literal operator lookup result"); 1650 } 1651 1652 ExprResult 1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1654 SourceLocation Loc, 1655 const CXXScopeSpec *SS) { 1656 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1657 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1658 } 1659 1660 /// BuildDeclRefExpr - Build an expression that references a 1661 /// declaration that does not require a closure capture. 1662 ExprResult 1663 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1664 const DeclarationNameInfo &NameInfo, 1665 const CXXScopeSpec *SS, NamedDecl *FoundD, 1666 const TemplateArgumentListInfo *TemplateArgs) { 1667 if (getLangOpts().CUDA) 1668 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1669 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1670 if (CheckCUDATarget(Caller, Callee)) { 1671 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1672 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1673 << IdentifyCUDATarget(Caller); 1674 Diag(D->getLocation(), diag::note_previous_decl) 1675 << D->getIdentifier(); 1676 return ExprError(); 1677 } 1678 } 1679 1680 bool RefersToCapturedVariable = 1681 isa<VarDecl>(D) && 1682 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1683 1684 DeclRefExpr *E; 1685 if (isa<VarTemplateSpecializationDecl>(D)) { 1686 VarTemplateSpecializationDecl *VarSpec = 1687 cast<VarTemplateSpecializationDecl>(D); 1688 1689 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1690 : NestedNameSpecifierLoc(), 1691 VarSpec->getTemplateKeywordLoc(), D, 1692 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1693 FoundD, TemplateArgs); 1694 } else { 1695 assert(!TemplateArgs && "No template arguments for non-variable" 1696 " template specialization references"); 1697 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1698 : NestedNameSpecifierLoc(), 1699 SourceLocation(), D, RefersToCapturedVariable, 1700 NameInfo, Ty, VK, FoundD); 1701 } 1702 1703 MarkDeclRefReferenced(E); 1704 1705 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1706 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1707 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1708 recordUseOfEvaluatedWeak(E); 1709 1710 // Just in case we're building an illegal pointer-to-member. 1711 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1712 if (FD && FD->isBitField()) 1713 E->setObjectKind(OK_BitField); 1714 1715 return E; 1716 } 1717 1718 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1719 /// possibly a list of template arguments. 1720 /// 1721 /// If this produces template arguments, it is permitted to call 1722 /// DecomposeTemplateName. 1723 /// 1724 /// This actually loses a lot of source location information for 1725 /// non-standard name kinds; we should consider preserving that in 1726 /// some way. 1727 void 1728 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1729 TemplateArgumentListInfo &Buffer, 1730 DeclarationNameInfo &NameInfo, 1731 const TemplateArgumentListInfo *&TemplateArgs) { 1732 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1733 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1734 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1735 1736 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1737 Id.TemplateId->NumArgs); 1738 translateTemplateArguments(TemplateArgsPtr, Buffer); 1739 1740 TemplateName TName = Id.TemplateId->Template.get(); 1741 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1742 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1743 TemplateArgs = &Buffer; 1744 } else { 1745 NameInfo = GetNameFromUnqualifiedId(Id); 1746 TemplateArgs = nullptr; 1747 } 1748 } 1749 1750 static void emitEmptyLookupTypoDiagnostic( 1751 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1752 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1753 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1754 DeclContext *Ctx = 1755 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1756 if (!TC) { 1757 // Emit a special diagnostic for failed member lookups. 1758 // FIXME: computing the declaration context might fail here (?) 1759 if (Ctx) 1760 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1761 << SS.getRange(); 1762 else 1763 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1764 return; 1765 } 1766 1767 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1768 bool DroppedSpecifier = 1769 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1770 unsigned NoteID = 1771 (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl())) 1772 ? diag::note_implicit_param_decl 1773 : diag::note_previous_decl; 1774 if (!Ctx) 1775 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1776 SemaRef.PDiag(NoteID)); 1777 else 1778 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1779 << Typo << Ctx << DroppedSpecifier 1780 << SS.getRange(), 1781 SemaRef.PDiag(NoteID)); 1782 } 1783 1784 /// Diagnose an empty lookup. 1785 /// 1786 /// \return false if new lookup candidates were found 1787 bool 1788 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1789 std::unique_ptr<CorrectionCandidateCallback> CCC, 1790 TemplateArgumentListInfo *ExplicitTemplateArgs, 1791 ArrayRef<Expr *> Args, TypoExpr **Out) { 1792 DeclarationName Name = R.getLookupName(); 1793 1794 unsigned diagnostic = diag::err_undeclared_var_use; 1795 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1796 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1797 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1798 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1799 diagnostic = diag::err_undeclared_use; 1800 diagnostic_suggest = diag::err_undeclared_use_suggest; 1801 } 1802 1803 // If the original lookup was an unqualified lookup, fake an 1804 // unqualified lookup. This is useful when (for example) the 1805 // original lookup would not have found something because it was a 1806 // dependent name. 1807 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1808 ? CurContext : nullptr; 1809 while (DC) { 1810 if (isa<CXXRecordDecl>(DC)) { 1811 LookupQualifiedName(R, DC); 1812 1813 if (!R.empty()) { 1814 // Don't give errors about ambiguities in this lookup. 1815 R.suppressDiagnostics(); 1816 1817 // During a default argument instantiation the CurContext points 1818 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1819 // function parameter list, hence add an explicit check. 1820 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1821 ActiveTemplateInstantiations.back().Kind == 1822 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1823 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1824 bool isInstance = CurMethod && 1825 CurMethod->isInstance() && 1826 DC == CurMethod->getParent() && !isDefaultArgument; 1827 1828 1829 // Give a code modification hint to insert 'this->'. 1830 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1831 // Actually quite difficult! 1832 if (getLangOpts().MSVCCompat) 1833 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1834 if (isInstance) { 1835 Diag(R.getNameLoc(), diagnostic) << Name 1836 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1837 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1838 CallsUndergoingInstantiation.back()->getCallee()); 1839 1840 CXXMethodDecl *DepMethod; 1841 if (CurMethod->isDependentContext()) 1842 DepMethod = CurMethod; 1843 else if (CurMethod->getTemplatedKind() == 1844 FunctionDecl::TK_FunctionTemplateSpecialization) 1845 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1846 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1847 else 1848 DepMethod = cast<CXXMethodDecl>( 1849 CurMethod->getInstantiatedFromMemberFunction()); 1850 assert(DepMethod && "No template pattern found"); 1851 1852 QualType DepThisType = DepMethod->getThisType(Context); 1853 CheckCXXThisCapture(R.getNameLoc()); 1854 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1855 R.getNameLoc(), DepThisType, false); 1856 TemplateArgumentListInfo TList; 1857 if (ULE->hasExplicitTemplateArgs()) 1858 ULE->copyTemplateArgumentsInto(TList); 1859 1860 CXXScopeSpec SS; 1861 SS.Adopt(ULE->getQualifierLoc()); 1862 CXXDependentScopeMemberExpr *DepExpr = 1863 CXXDependentScopeMemberExpr::Create( 1864 Context, DepThis, DepThisType, true, SourceLocation(), 1865 SS.getWithLocInContext(Context), 1866 ULE->getTemplateKeywordLoc(), nullptr, 1867 R.getLookupNameInfo(), 1868 ULE->hasExplicitTemplateArgs() ? &TList : nullptr); 1869 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1870 } else { 1871 Diag(R.getNameLoc(), diagnostic) << Name; 1872 } 1873 1874 // Do we really want to note all of these? 1875 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1876 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1877 1878 // Return true if we are inside a default argument instantiation 1879 // and the found name refers to an instance member function, otherwise 1880 // the function calling DiagnoseEmptyLookup will try to create an 1881 // implicit member call and this is wrong for default argument. 1882 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1883 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1884 return true; 1885 } 1886 1887 // Tell the callee to try to recover. 1888 return false; 1889 } 1890 1891 R.clear(); 1892 } 1893 1894 // In Microsoft mode, if we are performing lookup from within a friend 1895 // function definition declared at class scope then we must set 1896 // DC to the lexical parent to be able to search into the parent 1897 // class. 1898 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1899 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1900 DC->getLexicalParent()->isRecord()) 1901 DC = DC->getLexicalParent(); 1902 else 1903 DC = DC->getParent(); 1904 } 1905 1906 // We didn't find anything, so try to correct for a typo. 1907 TypoCorrection Corrected; 1908 if (S && Out) { 1909 SourceLocation TypoLoc = R.getNameLoc(); 1910 assert(!ExplicitTemplateArgs && 1911 "Diagnosing an empty lookup with explicit template args!"); 1912 *Out = CorrectTypoDelayed( 1913 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1914 [=](const TypoCorrection &TC) { 1915 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1916 diagnostic, diagnostic_suggest); 1917 }, 1918 nullptr, CTK_ErrorRecovery); 1919 if (*Out) 1920 return true; 1921 } else if (S && (Corrected = 1922 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1923 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1924 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1925 bool DroppedSpecifier = 1926 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1927 R.setLookupName(Corrected.getCorrection()); 1928 1929 bool AcceptableWithRecovery = false; 1930 bool AcceptableWithoutRecovery = false; 1931 NamedDecl *ND = Corrected.getCorrectionDecl(); 1932 if (ND) { 1933 if (Corrected.isOverloaded()) { 1934 OverloadCandidateSet OCS(R.getNameLoc(), 1935 OverloadCandidateSet::CSK_Normal); 1936 OverloadCandidateSet::iterator Best; 1937 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1938 CDEnd = Corrected.end(); 1939 CD != CDEnd; ++CD) { 1940 if (FunctionTemplateDecl *FTD = 1941 dyn_cast<FunctionTemplateDecl>(*CD)) 1942 AddTemplateOverloadCandidate( 1943 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1944 Args, OCS); 1945 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1946 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1947 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1948 Args, OCS); 1949 } 1950 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1951 case OR_Success: 1952 ND = Best->Function; 1953 Corrected.setCorrectionDecl(ND); 1954 break; 1955 default: 1956 // FIXME: Arbitrarily pick the first declaration for the note. 1957 Corrected.setCorrectionDecl(ND); 1958 break; 1959 } 1960 } 1961 R.addDecl(ND); 1962 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1963 CXXRecordDecl *Record = nullptr; 1964 if (Corrected.getCorrectionSpecifier()) { 1965 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1966 Record = Ty->getAsCXXRecordDecl(); 1967 } 1968 if (!Record) 1969 Record = cast<CXXRecordDecl>( 1970 ND->getDeclContext()->getRedeclContext()); 1971 R.setNamingClass(Record); 1972 } 1973 1974 AcceptableWithRecovery = 1975 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1976 // FIXME: If we ended up with a typo for a type name or 1977 // Objective-C class name, we're in trouble because the parser 1978 // is in the wrong place to recover. Suggest the typo 1979 // correction, but don't make it a fix-it since we're not going 1980 // to recover well anyway. 1981 AcceptableWithoutRecovery = 1982 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1983 } else { 1984 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1985 // because we aren't able to recover. 1986 AcceptableWithoutRecovery = true; 1987 } 1988 1989 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1990 unsigned NoteID = (Corrected.getCorrectionDecl() && 1991 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1992 ? diag::note_implicit_param_decl 1993 : diag::note_previous_decl; 1994 if (SS.isEmpty()) 1995 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1996 PDiag(NoteID), AcceptableWithRecovery); 1997 else 1998 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1999 << Name << computeDeclContext(SS, false) 2000 << DroppedSpecifier << SS.getRange(), 2001 PDiag(NoteID), AcceptableWithRecovery); 2002 2003 // Tell the callee whether to try to recover. 2004 return !AcceptableWithRecovery; 2005 } 2006 } 2007 R.clear(); 2008 2009 // Emit a special diagnostic for failed member lookups. 2010 // FIXME: computing the declaration context might fail here (?) 2011 if (!SS.isEmpty()) { 2012 Diag(R.getNameLoc(), diag::err_no_member) 2013 << Name << computeDeclContext(SS, false) 2014 << SS.getRange(); 2015 return true; 2016 } 2017 2018 // Give up, we can't recover. 2019 Diag(R.getNameLoc(), diagnostic) << Name; 2020 return true; 2021 } 2022 2023 /// In Microsoft mode, if we are inside a template class whose parent class has 2024 /// dependent base classes, and we can't resolve an unqualified identifier, then 2025 /// assume the identifier is a member of a dependent base class. We can only 2026 /// recover successfully in static methods, instance methods, and other contexts 2027 /// where 'this' is available. This doesn't precisely match MSVC's 2028 /// instantiation model, but it's close enough. 2029 static Expr * 2030 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2031 DeclarationNameInfo &NameInfo, 2032 SourceLocation TemplateKWLoc, 2033 const TemplateArgumentListInfo *TemplateArgs) { 2034 // Only try to recover from lookup into dependent bases in static methods or 2035 // contexts where 'this' is available. 2036 QualType ThisType = S.getCurrentThisType(); 2037 const CXXRecordDecl *RD = nullptr; 2038 if (!ThisType.isNull()) 2039 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2040 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2041 RD = MD->getParent(); 2042 if (!RD || !RD->hasAnyDependentBases()) 2043 return nullptr; 2044 2045 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2046 // is available, suggest inserting 'this->' as a fixit. 2047 SourceLocation Loc = NameInfo.getLoc(); 2048 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2049 DB << NameInfo.getName() << RD; 2050 2051 if (!ThisType.isNull()) { 2052 DB << FixItHint::CreateInsertion(Loc, "this->"); 2053 return CXXDependentScopeMemberExpr::Create( 2054 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2055 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2056 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2057 } 2058 2059 // Synthesize a fake NNS that points to the derived class. This will 2060 // perform name lookup during template instantiation. 2061 CXXScopeSpec SS; 2062 auto *NNS = 2063 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2064 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2065 return DependentScopeDeclRefExpr::Create( 2066 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2067 TemplateArgs); 2068 } 2069 2070 ExprResult 2071 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2072 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2073 bool HasTrailingLParen, bool IsAddressOfOperand, 2074 std::unique_ptr<CorrectionCandidateCallback> CCC, 2075 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2076 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2077 "cannot be direct & operand and have a trailing lparen"); 2078 if (SS.isInvalid()) 2079 return ExprError(); 2080 2081 TemplateArgumentListInfo TemplateArgsBuffer; 2082 2083 // Decompose the UnqualifiedId into the following data. 2084 DeclarationNameInfo NameInfo; 2085 const TemplateArgumentListInfo *TemplateArgs; 2086 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2087 2088 DeclarationName Name = NameInfo.getName(); 2089 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2090 SourceLocation NameLoc = NameInfo.getLoc(); 2091 2092 // C++ [temp.dep.expr]p3: 2093 // An id-expression is type-dependent if it contains: 2094 // -- an identifier that was declared with a dependent type, 2095 // (note: handled after lookup) 2096 // -- a template-id that is dependent, 2097 // (note: handled in BuildTemplateIdExpr) 2098 // -- a conversion-function-id that specifies a dependent type, 2099 // -- a nested-name-specifier that contains a class-name that 2100 // names a dependent type. 2101 // Determine whether this is a member of an unknown specialization; 2102 // we need to handle these differently. 2103 bool DependentID = false; 2104 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2105 Name.getCXXNameType()->isDependentType()) { 2106 DependentID = true; 2107 } else if (SS.isSet()) { 2108 if (DeclContext *DC = computeDeclContext(SS, false)) { 2109 if (RequireCompleteDeclContext(SS, DC)) 2110 return ExprError(); 2111 } else { 2112 DependentID = true; 2113 } 2114 } 2115 2116 if (DependentID) 2117 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2118 IsAddressOfOperand, TemplateArgs); 2119 2120 // Perform the required lookup. 2121 LookupResult R(*this, NameInfo, 2122 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2123 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2124 if (TemplateArgs) { 2125 // Lookup the template name again to correctly establish the context in 2126 // which it was found. This is really unfortunate as we already did the 2127 // lookup to determine that it was a template name in the first place. If 2128 // this becomes a performance hit, we can work harder to preserve those 2129 // results until we get here but it's likely not worth it. 2130 bool MemberOfUnknownSpecialization; 2131 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2132 MemberOfUnknownSpecialization); 2133 2134 if (MemberOfUnknownSpecialization || 2135 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2136 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2137 IsAddressOfOperand, TemplateArgs); 2138 } else { 2139 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2140 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2141 2142 // If the result might be in a dependent base class, this is a dependent 2143 // id-expression. 2144 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2145 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2146 IsAddressOfOperand, TemplateArgs); 2147 2148 // If this reference is in an Objective-C method, then we need to do 2149 // some special Objective-C lookup, too. 2150 if (IvarLookupFollowUp) { 2151 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2152 if (E.isInvalid()) 2153 return ExprError(); 2154 2155 if (Expr *Ex = E.getAs<Expr>()) 2156 return Ex; 2157 } 2158 } 2159 2160 if (R.isAmbiguous()) 2161 return ExprError(); 2162 2163 // This could be an implicitly declared function reference (legal in C90, 2164 // extension in C99, forbidden in C++). 2165 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2166 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2167 if (D) R.addDecl(D); 2168 } 2169 2170 // Determine whether this name might be a candidate for 2171 // argument-dependent lookup. 2172 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2173 2174 if (R.empty() && !ADL) { 2175 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2176 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2177 TemplateKWLoc, TemplateArgs)) 2178 return E; 2179 } 2180 2181 // Don't diagnose an empty lookup for inline assembly. 2182 if (IsInlineAsmIdentifier) 2183 return ExprError(); 2184 2185 // If this name wasn't predeclared and if this is not a function 2186 // call, diagnose the problem. 2187 TypoExpr *TE = nullptr; 2188 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2189 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2190 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2191 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2192 "Typo correction callback misconfigured"); 2193 if (CCC) { 2194 // Make sure the callback knows what the typo being diagnosed is. 2195 CCC->setTypoName(II); 2196 if (SS.isValid()) 2197 CCC->setTypoNNS(SS.getScopeRep()); 2198 } 2199 if (DiagnoseEmptyLookup(S, SS, R, 2200 CCC ? std::move(CCC) : std::move(DefaultValidator), 2201 nullptr, None, &TE)) { 2202 if (TE && KeywordReplacement) { 2203 auto &State = getTypoExprState(TE); 2204 auto BestTC = State.Consumer->getNextCorrection(); 2205 if (BestTC.isKeyword()) { 2206 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2207 if (State.DiagHandler) 2208 State.DiagHandler(BestTC); 2209 KeywordReplacement->startToken(); 2210 KeywordReplacement->setKind(II->getTokenID()); 2211 KeywordReplacement->setIdentifierInfo(II); 2212 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2213 // Clean up the state associated with the TypoExpr, since it has 2214 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2215 clearDelayedTypo(TE); 2216 // Signal that a correction to a keyword was performed by returning a 2217 // valid-but-null ExprResult. 2218 return (Expr*)nullptr; 2219 } 2220 State.Consumer->resetCorrectionStream(); 2221 } 2222 return TE ? TE : ExprError(); 2223 } 2224 2225 assert(!R.empty() && 2226 "DiagnoseEmptyLookup returned false but added no results"); 2227 2228 // If we found an Objective-C instance variable, let 2229 // LookupInObjCMethod build the appropriate expression to 2230 // reference the ivar. 2231 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2232 R.clear(); 2233 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2234 // In a hopelessly buggy code, Objective-C instance variable 2235 // lookup fails and no expression will be built to reference it. 2236 if (!E.isInvalid() && !E.get()) 2237 return ExprError(); 2238 return E; 2239 } 2240 } 2241 2242 // This is guaranteed from this point on. 2243 assert(!R.empty() || ADL); 2244 2245 // Check whether this might be a C++ implicit instance member access. 2246 // C++ [class.mfct.non-static]p3: 2247 // When an id-expression that is not part of a class member access 2248 // syntax and not used to form a pointer to member is used in the 2249 // body of a non-static member function of class X, if name lookup 2250 // resolves the name in the id-expression to a non-static non-type 2251 // member of some class C, the id-expression is transformed into a 2252 // class member access expression using (*this) as the 2253 // postfix-expression to the left of the . operator. 2254 // 2255 // But we don't actually need to do this for '&' operands if R 2256 // resolved to a function or overloaded function set, because the 2257 // expression is ill-formed if it actually works out to be a 2258 // non-static member function: 2259 // 2260 // C++ [expr.ref]p4: 2261 // Otherwise, if E1.E2 refers to a non-static member function. . . 2262 // [t]he expression can be used only as the left-hand operand of a 2263 // member function call. 2264 // 2265 // There are other safeguards against such uses, but it's important 2266 // to get this right here so that we don't end up making a 2267 // spuriously dependent expression if we're inside a dependent 2268 // instance method. 2269 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2270 bool MightBeImplicitMember; 2271 if (!IsAddressOfOperand) 2272 MightBeImplicitMember = true; 2273 else if (!SS.isEmpty()) 2274 MightBeImplicitMember = false; 2275 else if (R.isOverloadedResult()) 2276 MightBeImplicitMember = false; 2277 else if (R.isUnresolvableResult()) 2278 MightBeImplicitMember = true; 2279 else 2280 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2281 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2282 isa<MSPropertyDecl>(R.getFoundDecl()); 2283 2284 if (MightBeImplicitMember) 2285 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2286 R, TemplateArgs, S); 2287 } 2288 2289 if (TemplateArgs || TemplateKWLoc.isValid()) { 2290 2291 // In C++1y, if this is a variable template id, then check it 2292 // in BuildTemplateIdExpr(). 2293 // The single lookup result must be a variable template declaration. 2294 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2295 Id.TemplateId->Kind == TNK_Var_template) { 2296 assert(R.getAsSingle<VarTemplateDecl>() && 2297 "There should only be one declaration found."); 2298 } 2299 2300 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2301 } 2302 2303 return BuildDeclarationNameExpr(SS, R, ADL); 2304 } 2305 2306 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2307 /// declaration name, generally during template instantiation. 2308 /// There's a large number of things which don't need to be done along 2309 /// this path. 2310 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2311 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2312 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2313 DeclContext *DC = computeDeclContext(SS, false); 2314 if (!DC) 2315 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2316 NameInfo, /*TemplateArgs=*/nullptr); 2317 2318 if (RequireCompleteDeclContext(SS, DC)) 2319 return ExprError(); 2320 2321 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2322 LookupQualifiedName(R, DC); 2323 2324 if (R.isAmbiguous()) 2325 return ExprError(); 2326 2327 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2328 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2329 NameInfo, /*TemplateArgs=*/nullptr); 2330 2331 if (R.empty()) { 2332 Diag(NameInfo.getLoc(), diag::err_no_member) 2333 << NameInfo.getName() << DC << SS.getRange(); 2334 return ExprError(); 2335 } 2336 2337 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2338 // Diagnose a missing typename if this resolved unambiguously to a type in 2339 // a dependent context. If we can recover with a type, downgrade this to 2340 // a warning in Microsoft compatibility mode. 2341 unsigned DiagID = diag::err_typename_missing; 2342 if (RecoveryTSI && getLangOpts().MSVCCompat) 2343 DiagID = diag::ext_typename_missing; 2344 SourceLocation Loc = SS.getBeginLoc(); 2345 auto D = Diag(Loc, DiagID); 2346 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2347 << SourceRange(Loc, NameInfo.getEndLoc()); 2348 2349 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2350 // context. 2351 if (!RecoveryTSI) 2352 return ExprError(); 2353 2354 // Only issue the fixit if we're prepared to recover. 2355 D << FixItHint::CreateInsertion(Loc, "typename "); 2356 2357 // Recover by pretending this was an elaborated type. 2358 QualType Ty = Context.getTypeDeclType(TD); 2359 TypeLocBuilder TLB; 2360 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2361 2362 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2363 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2364 QTL.setElaboratedKeywordLoc(SourceLocation()); 2365 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2366 2367 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2368 2369 return ExprEmpty(); 2370 } 2371 2372 // Defend against this resolving to an implicit member access. We usually 2373 // won't get here if this might be a legitimate a class member (we end up in 2374 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2375 // a pointer-to-member or in an unevaluated context in C++11. 2376 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2377 return BuildPossibleImplicitMemberExpr(SS, 2378 /*TemplateKWLoc=*/SourceLocation(), 2379 R, /*TemplateArgs=*/nullptr, S); 2380 2381 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2382 } 2383 2384 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2385 /// detected that we're currently inside an ObjC method. Perform some 2386 /// additional lookup. 2387 /// 2388 /// Ideally, most of this would be done by lookup, but there's 2389 /// actually quite a lot of extra work involved. 2390 /// 2391 /// Returns a null sentinel to indicate trivial success. 2392 ExprResult 2393 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2394 IdentifierInfo *II, bool AllowBuiltinCreation) { 2395 SourceLocation Loc = Lookup.getNameLoc(); 2396 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2397 2398 // Check for error condition which is already reported. 2399 if (!CurMethod) 2400 return ExprError(); 2401 2402 // There are two cases to handle here. 1) scoped lookup could have failed, 2403 // in which case we should look for an ivar. 2) scoped lookup could have 2404 // found a decl, but that decl is outside the current instance method (i.e. 2405 // a global variable). In these two cases, we do a lookup for an ivar with 2406 // this name, if the lookup sucedes, we replace it our current decl. 2407 2408 // If we're in a class method, we don't normally want to look for 2409 // ivars. But if we don't find anything else, and there's an 2410 // ivar, that's an error. 2411 bool IsClassMethod = CurMethod->isClassMethod(); 2412 2413 bool LookForIvars; 2414 if (Lookup.empty()) 2415 LookForIvars = true; 2416 else if (IsClassMethod) 2417 LookForIvars = false; 2418 else 2419 LookForIvars = (Lookup.isSingleResult() && 2420 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2421 ObjCInterfaceDecl *IFace = nullptr; 2422 if (LookForIvars) { 2423 IFace = CurMethod->getClassInterface(); 2424 ObjCInterfaceDecl *ClassDeclared; 2425 ObjCIvarDecl *IV = nullptr; 2426 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2427 // Diagnose using an ivar in a class method. 2428 if (IsClassMethod) 2429 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2430 << IV->getDeclName()); 2431 2432 // If we're referencing an invalid decl, just return this as a silent 2433 // error node. The error diagnostic was already emitted on the decl. 2434 if (IV->isInvalidDecl()) 2435 return ExprError(); 2436 2437 // Check if referencing a field with __attribute__((deprecated)). 2438 if (DiagnoseUseOfDecl(IV, Loc)) 2439 return ExprError(); 2440 2441 // Diagnose the use of an ivar outside of the declaring class. 2442 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2443 !declaresSameEntity(ClassDeclared, IFace) && 2444 !getLangOpts().DebuggerSupport) 2445 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2446 2447 // FIXME: This should use a new expr for a direct reference, don't 2448 // turn this into Self->ivar, just return a BareIVarExpr or something. 2449 IdentifierInfo &II = Context.Idents.get("self"); 2450 UnqualifiedId SelfName; 2451 SelfName.setIdentifier(&II, SourceLocation()); 2452 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2453 CXXScopeSpec SelfScopeSpec; 2454 SourceLocation TemplateKWLoc; 2455 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2456 SelfName, false, false); 2457 if (SelfExpr.isInvalid()) 2458 return ExprError(); 2459 2460 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2461 if (SelfExpr.isInvalid()) 2462 return ExprError(); 2463 2464 MarkAnyDeclReferenced(Loc, IV, true); 2465 2466 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2467 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2468 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2469 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2470 2471 ObjCIvarRefExpr *Result = new (Context) 2472 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2473 IV->getLocation(), SelfExpr.get(), true, true); 2474 2475 if (getLangOpts().ObjCAutoRefCount) { 2476 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2477 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2478 recordUseOfEvaluatedWeak(Result); 2479 } 2480 if (CurContext->isClosure()) 2481 Diag(Loc, diag::warn_implicitly_retains_self) 2482 << FixItHint::CreateInsertion(Loc, "self->"); 2483 } 2484 2485 return Result; 2486 } 2487 } else if (CurMethod->isInstanceMethod()) { 2488 // We should warn if a local variable hides an ivar. 2489 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2490 ObjCInterfaceDecl *ClassDeclared; 2491 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2492 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2493 declaresSameEntity(IFace, ClassDeclared)) 2494 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2495 } 2496 } 2497 } else if (Lookup.isSingleResult() && 2498 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2499 // If accessing a stand-alone ivar in a class method, this is an error. 2500 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2501 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2502 << IV->getDeclName()); 2503 } 2504 2505 if (Lookup.empty() && II && AllowBuiltinCreation) { 2506 // FIXME. Consolidate this with similar code in LookupName. 2507 if (unsigned BuiltinID = II->getBuiltinID()) { 2508 if (!(getLangOpts().CPlusPlus && 2509 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2510 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2511 S, Lookup.isForRedeclaration(), 2512 Lookup.getNameLoc()); 2513 if (D) Lookup.addDecl(D); 2514 } 2515 } 2516 } 2517 // Sentinel value saying that we didn't do anything special. 2518 return ExprResult((Expr *)nullptr); 2519 } 2520 2521 /// \brief Cast a base object to a member's actual type. 2522 /// 2523 /// Logically this happens in three phases: 2524 /// 2525 /// * First we cast from the base type to the naming class. 2526 /// The naming class is the class into which we were looking 2527 /// when we found the member; it's the qualifier type if a 2528 /// qualifier was provided, and otherwise it's the base type. 2529 /// 2530 /// * Next we cast from the naming class to the declaring class. 2531 /// If the member we found was brought into a class's scope by 2532 /// a using declaration, this is that class; otherwise it's 2533 /// the class declaring the member. 2534 /// 2535 /// * Finally we cast from the declaring class to the "true" 2536 /// declaring class of the member. This conversion does not 2537 /// obey access control. 2538 ExprResult 2539 Sema::PerformObjectMemberConversion(Expr *From, 2540 NestedNameSpecifier *Qualifier, 2541 NamedDecl *FoundDecl, 2542 NamedDecl *Member) { 2543 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2544 if (!RD) 2545 return From; 2546 2547 QualType DestRecordType; 2548 QualType DestType; 2549 QualType FromRecordType; 2550 QualType FromType = From->getType(); 2551 bool PointerConversions = false; 2552 if (isa<FieldDecl>(Member)) { 2553 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2554 2555 if (FromType->getAs<PointerType>()) { 2556 DestType = Context.getPointerType(DestRecordType); 2557 FromRecordType = FromType->getPointeeType(); 2558 PointerConversions = true; 2559 } else { 2560 DestType = DestRecordType; 2561 FromRecordType = FromType; 2562 } 2563 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2564 if (Method->isStatic()) 2565 return From; 2566 2567 DestType = Method->getThisType(Context); 2568 DestRecordType = DestType->getPointeeType(); 2569 2570 if (FromType->getAs<PointerType>()) { 2571 FromRecordType = FromType->getPointeeType(); 2572 PointerConversions = true; 2573 } else { 2574 FromRecordType = FromType; 2575 DestType = DestRecordType; 2576 } 2577 } else { 2578 // No conversion necessary. 2579 return From; 2580 } 2581 2582 if (DestType->isDependentType() || FromType->isDependentType()) 2583 return From; 2584 2585 // If the unqualified types are the same, no conversion is necessary. 2586 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2587 return From; 2588 2589 SourceRange FromRange = From->getSourceRange(); 2590 SourceLocation FromLoc = FromRange.getBegin(); 2591 2592 ExprValueKind VK = From->getValueKind(); 2593 2594 // C++ [class.member.lookup]p8: 2595 // [...] Ambiguities can often be resolved by qualifying a name with its 2596 // class name. 2597 // 2598 // If the member was a qualified name and the qualified referred to a 2599 // specific base subobject type, we'll cast to that intermediate type 2600 // first and then to the object in which the member is declared. That allows 2601 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2602 // 2603 // class Base { public: int x; }; 2604 // class Derived1 : public Base { }; 2605 // class Derived2 : public Base { }; 2606 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2607 // 2608 // void VeryDerived::f() { 2609 // x = 17; // error: ambiguous base subobjects 2610 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2611 // } 2612 if (Qualifier && Qualifier->getAsType()) { 2613 QualType QType = QualType(Qualifier->getAsType(), 0); 2614 assert(QType->isRecordType() && "lookup done with non-record type"); 2615 2616 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2617 2618 // In C++98, the qualifier type doesn't actually have to be a base 2619 // type of the object type, in which case we just ignore it. 2620 // Otherwise build the appropriate casts. 2621 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2622 CXXCastPath BasePath; 2623 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2624 FromLoc, FromRange, &BasePath)) 2625 return ExprError(); 2626 2627 if (PointerConversions) 2628 QType = Context.getPointerType(QType); 2629 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2630 VK, &BasePath).get(); 2631 2632 FromType = QType; 2633 FromRecordType = QRecordType; 2634 2635 // If the qualifier type was the same as the destination type, 2636 // we're done. 2637 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2638 return From; 2639 } 2640 } 2641 2642 bool IgnoreAccess = false; 2643 2644 // If we actually found the member through a using declaration, cast 2645 // down to the using declaration's type. 2646 // 2647 // Pointer equality is fine here because only one declaration of a 2648 // class ever has member declarations. 2649 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2650 assert(isa<UsingShadowDecl>(FoundDecl)); 2651 QualType URecordType = Context.getTypeDeclType( 2652 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2653 2654 // We only need to do this if the naming-class to declaring-class 2655 // conversion is non-trivial. 2656 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2657 assert(IsDerivedFrom(FromRecordType, URecordType)); 2658 CXXCastPath BasePath; 2659 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2660 FromLoc, FromRange, &BasePath)) 2661 return ExprError(); 2662 2663 QualType UType = URecordType; 2664 if (PointerConversions) 2665 UType = Context.getPointerType(UType); 2666 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2667 VK, &BasePath).get(); 2668 FromType = UType; 2669 FromRecordType = URecordType; 2670 } 2671 2672 // We don't do access control for the conversion from the 2673 // declaring class to the true declaring class. 2674 IgnoreAccess = true; 2675 } 2676 2677 CXXCastPath BasePath; 2678 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2679 FromLoc, FromRange, &BasePath, 2680 IgnoreAccess)) 2681 return ExprError(); 2682 2683 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2684 VK, &BasePath); 2685 } 2686 2687 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2688 const LookupResult &R, 2689 bool HasTrailingLParen) { 2690 // Only when used directly as the postfix-expression of a call. 2691 if (!HasTrailingLParen) 2692 return false; 2693 2694 // Never if a scope specifier was provided. 2695 if (SS.isSet()) 2696 return false; 2697 2698 // Only in C++ or ObjC++. 2699 if (!getLangOpts().CPlusPlus) 2700 return false; 2701 2702 // Turn off ADL when we find certain kinds of declarations during 2703 // normal lookup: 2704 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2705 NamedDecl *D = *I; 2706 2707 // C++0x [basic.lookup.argdep]p3: 2708 // -- a declaration of a class member 2709 // Since using decls preserve this property, we check this on the 2710 // original decl. 2711 if (D->isCXXClassMember()) 2712 return false; 2713 2714 // C++0x [basic.lookup.argdep]p3: 2715 // -- a block-scope function declaration that is not a 2716 // using-declaration 2717 // NOTE: we also trigger this for function templates (in fact, we 2718 // don't check the decl type at all, since all other decl types 2719 // turn off ADL anyway). 2720 if (isa<UsingShadowDecl>(D)) 2721 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2722 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2723 return false; 2724 2725 // C++0x [basic.lookup.argdep]p3: 2726 // -- a declaration that is neither a function or a function 2727 // template 2728 // And also for builtin functions. 2729 if (isa<FunctionDecl>(D)) { 2730 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2731 2732 // But also builtin functions. 2733 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2734 return false; 2735 } else if (!isa<FunctionTemplateDecl>(D)) 2736 return false; 2737 } 2738 2739 return true; 2740 } 2741 2742 2743 /// Diagnoses obvious problems with the use of the given declaration 2744 /// as an expression. This is only actually called for lookups that 2745 /// were not overloaded, and it doesn't promise that the declaration 2746 /// will in fact be used. 2747 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2748 if (isa<TypedefNameDecl>(D)) { 2749 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2750 return true; 2751 } 2752 2753 if (isa<ObjCInterfaceDecl>(D)) { 2754 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2755 return true; 2756 } 2757 2758 if (isa<NamespaceDecl>(D)) { 2759 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2760 return true; 2761 } 2762 2763 return false; 2764 } 2765 2766 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2767 LookupResult &R, bool NeedsADL, 2768 bool AcceptInvalidDecl) { 2769 // If this is a single, fully-resolved result and we don't need ADL, 2770 // just build an ordinary singleton decl ref. 2771 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2772 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2773 R.getRepresentativeDecl(), nullptr, 2774 AcceptInvalidDecl); 2775 2776 // We only need to check the declaration if there's exactly one 2777 // result, because in the overloaded case the results can only be 2778 // functions and function templates. 2779 if (R.isSingleResult() && 2780 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2781 return ExprError(); 2782 2783 // Otherwise, just build an unresolved lookup expression. Suppress 2784 // any lookup-related diagnostics; we'll hash these out later, when 2785 // we've picked a target. 2786 R.suppressDiagnostics(); 2787 2788 UnresolvedLookupExpr *ULE 2789 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2790 SS.getWithLocInContext(Context), 2791 R.getLookupNameInfo(), 2792 NeedsADL, R.isOverloadedResult(), 2793 R.begin(), R.end()); 2794 2795 return ULE; 2796 } 2797 2798 /// \brief Complete semantic analysis for a reference to the given declaration. 2799 ExprResult Sema::BuildDeclarationNameExpr( 2800 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2801 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2802 bool AcceptInvalidDecl) { 2803 assert(D && "Cannot refer to a NULL declaration"); 2804 assert(!isa<FunctionTemplateDecl>(D) && 2805 "Cannot refer unambiguously to a function template"); 2806 2807 SourceLocation Loc = NameInfo.getLoc(); 2808 if (CheckDeclInExpr(*this, Loc, D)) 2809 return ExprError(); 2810 2811 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2812 // Specifically diagnose references to class templates that are missing 2813 // a template argument list. 2814 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2815 << Template << SS.getRange(); 2816 Diag(Template->getLocation(), diag::note_template_decl_here); 2817 return ExprError(); 2818 } 2819 2820 // Make sure that we're referring to a value. 2821 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2822 if (!VD) { 2823 Diag(Loc, diag::err_ref_non_value) 2824 << D << SS.getRange(); 2825 Diag(D->getLocation(), diag::note_declared_at); 2826 return ExprError(); 2827 } 2828 2829 // Check whether this declaration can be used. Note that we suppress 2830 // this check when we're going to perform argument-dependent lookup 2831 // on this function name, because this might not be the function 2832 // that overload resolution actually selects. 2833 if (DiagnoseUseOfDecl(VD, Loc)) 2834 return ExprError(); 2835 2836 // Only create DeclRefExpr's for valid Decl's. 2837 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2838 return ExprError(); 2839 2840 // Handle members of anonymous structs and unions. If we got here, 2841 // and the reference is to a class member indirect field, then this 2842 // must be the subject of a pointer-to-member expression. 2843 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2844 if (!indirectField->isCXXClassMember()) 2845 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2846 indirectField); 2847 2848 { 2849 QualType type = VD->getType(); 2850 ExprValueKind valueKind = VK_RValue; 2851 2852 switch (D->getKind()) { 2853 // Ignore all the non-ValueDecl kinds. 2854 #define ABSTRACT_DECL(kind) 2855 #define VALUE(type, base) 2856 #define DECL(type, base) \ 2857 case Decl::type: 2858 #include "clang/AST/DeclNodes.inc" 2859 llvm_unreachable("invalid value decl kind"); 2860 2861 // These shouldn't make it here. 2862 case Decl::ObjCAtDefsField: 2863 case Decl::ObjCIvar: 2864 llvm_unreachable("forming non-member reference to ivar?"); 2865 2866 // Enum constants are always r-values and never references. 2867 // Unresolved using declarations are dependent. 2868 case Decl::EnumConstant: 2869 case Decl::UnresolvedUsingValue: 2870 valueKind = VK_RValue; 2871 break; 2872 2873 // Fields and indirect fields that got here must be for 2874 // pointer-to-member expressions; we just call them l-values for 2875 // internal consistency, because this subexpression doesn't really 2876 // exist in the high-level semantics. 2877 case Decl::Field: 2878 case Decl::IndirectField: 2879 assert(getLangOpts().CPlusPlus && 2880 "building reference to field in C?"); 2881 2882 // These can't have reference type in well-formed programs, but 2883 // for internal consistency we do this anyway. 2884 type = type.getNonReferenceType(); 2885 valueKind = VK_LValue; 2886 break; 2887 2888 // Non-type template parameters are either l-values or r-values 2889 // depending on the type. 2890 case Decl::NonTypeTemplateParm: { 2891 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2892 type = reftype->getPointeeType(); 2893 valueKind = VK_LValue; // even if the parameter is an r-value reference 2894 break; 2895 } 2896 2897 // For non-references, we need to strip qualifiers just in case 2898 // the template parameter was declared as 'const int' or whatever. 2899 valueKind = VK_RValue; 2900 type = type.getUnqualifiedType(); 2901 break; 2902 } 2903 2904 case Decl::Var: 2905 case Decl::VarTemplateSpecialization: 2906 case Decl::VarTemplatePartialSpecialization: 2907 // In C, "extern void blah;" is valid and is an r-value. 2908 if (!getLangOpts().CPlusPlus && 2909 !type.hasQualifiers() && 2910 type->isVoidType()) { 2911 valueKind = VK_RValue; 2912 break; 2913 } 2914 // fallthrough 2915 2916 case Decl::ImplicitParam: 2917 case Decl::ParmVar: { 2918 // These are always l-values. 2919 valueKind = VK_LValue; 2920 type = type.getNonReferenceType(); 2921 2922 // FIXME: Does the addition of const really only apply in 2923 // potentially-evaluated contexts? Since the variable isn't actually 2924 // captured in an unevaluated context, it seems that the answer is no. 2925 if (!isUnevaluatedContext()) { 2926 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2927 if (!CapturedType.isNull()) 2928 type = CapturedType; 2929 } 2930 2931 break; 2932 } 2933 2934 case Decl::Function: { 2935 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2936 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2937 type = Context.BuiltinFnTy; 2938 valueKind = VK_RValue; 2939 break; 2940 } 2941 } 2942 2943 const FunctionType *fty = type->castAs<FunctionType>(); 2944 2945 // If we're referring to a function with an __unknown_anytype 2946 // result type, make the entire expression __unknown_anytype. 2947 if (fty->getReturnType() == Context.UnknownAnyTy) { 2948 type = Context.UnknownAnyTy; 2949 valueKind = VK_RValue; 2950 break; 2951 } 2952 2953 // Functions are l-values in C++. 2954 if (getLangOpts().CPlusPlus) { 2955 valueKind = VK_LValue; 2956 break; 2957 } 2958 2959 // C99 DR 316 says that, if a function type comes from a 2960 // function definition (without a prototype), that type is only 2961 // used for checking compatibility. Therefore, when referencing 2962 // the function, we pretend that we don't have the full function 2963 // type. 2964 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2965 isa<FunctionProtoType>(fty)) 2966 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2967 fty->getExtInfo()); 2968 2969 // Functions are r-values in C. 2970 valueKind = VK_RValue; 2971 break; 2972 } 2973 2974 case Decl::MSProperty: 2975 valueKind = VK_LValue; 2976 break; 2977 2978 case Decl::CXXMethod: 2979 // If we're referring to a method with an __unknown_anytype 2980 // result type, make the entire expression __unknown_anytype. 2981 // This should only be possible with a type written directly. 2982 if (const FunctionProtoType *proto 2983 = dyn_cast<FunctionProtoType>(VD->getType())) 2984 if (proto->getReturnType() == Context.UnknownAnyTy) { 2985 type = Context.UnknownAnyTy; 2986 valueKind = VK_RValue; 2987 break; 2988 } 2989 2990 // C++ methods are l-values if static, r-values if non-static. 2991 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2992 valueKind = VK_LValue; 2993 break; 2994 } 2995 // fallthrough 2996 2997 case Decl::CXXConversion: 2998 case Decl::CXXDestructor: 2999 case Decl::CXXConstructor: 3000 valueKind = VK_RValue; 3001 break; 3002 } 3003 3004 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3005 TemplateArgs); 3006 } 3007 } 3008 3009 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3010 SmallString<32> &Target) { 3011 Target.resize(CharByteWidth * (Source.size() + 1)); 3012 char *ResultPtr = &Target[0]; 3013 const UTF8 *ErrorPtr; 3014 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3015 (void)success; 3016 assert(success); 3017 Target.resize(ResultPtr - &Target[0]); 3018 } 3019 3020 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3021 PredefinedExpr::IdentType IT) { 3022 // Pick the current block, lambda, captured statement or function. 3023 Decl *currentDecl = nullptr; 3024 if (const BlockScopeInfo *BSI = getCurBlock()) 3025 currentDecl = BSI->TheDecl; 3026 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3027 currentDecl = LSI->CallOperator; 3028 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3029 currentDecl = CSI->TheCapturedDecl; 3030 else 3031 currentDecl = getCurFunctionOrMethodDecl(); 3032 3033 if (!currentDecl) { 3034 Diag(Loc, diag::ext_predef_outside_function); 3035 currentDecl = Context.getTranslationUnitDecl(); 3036 } 3037 3038 QualType ResTy; 3039 StringLiteral *SL = nullptr; 3040 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3041 ResTy = Context.DependentTy; 3042 else { 3043 // Pre-defined identifiers are of type char[x], where x is the length of 3044 // the string. 3045 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3046 unsigned Length = Str.length(); 3047 3048 llvm::APInt LengthI(32, Length + 1); 3049 if (IT == PredefinedExpr::LFunction) { 3050 ResTy = Context.WideCharTy.withConst(); 3051 SmallString<32> RawChars; 3052 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3053 Str, RawChars); 3054 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3055 /*IndexTypeQuals*/ 0); 3056 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3057 /*Pascal*/ false, ResTy, Loc); 3058 } else { 3059 ResTy = Context.CharTy.withConst(); 3060 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3061 /*IndexTypeQuals*/ 0); 3062 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3063 /*Pascal*/ false, ResTy, Loc); 3064 } 3065 } 3066 3067 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3068 } 3069 3070 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3071 PredefinedExpr::IdentType IT; 3072 3073 switch (Kind) { 3074 default: llvm_unreachable("Unknown simple primary expr!"); 3075 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3076 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3077 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3078 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3079 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3080 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3081 } 3082 3083 return BuildPredefinedExpr(Loc, IT); 3084 } 3085 3086 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3087 SmallString<16> CharBuffer; 3088 bool Invalid = false; 3089 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3090 if (Invalid) 3091 return ExprError(); 3092 3093 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3094 PP, Tok.getKind()); 3095 if (Literal.hadError()) 3096 return ExprError(); 3097 3098 QualType Ty; 3099 if (Literal.isWide()) 3100 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3101 else if (Literal.isUTF16()) 3102 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3103 else if (Literal.isUTF32()) 3104 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3105 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3106 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3107 else 3108 Ty = Context.CharTy; // 'x' -> char in C++ 3109 3110 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3111 if (Literal.isWide()) 3112 Kind = CharacterLiteral::Wide; 3113 else if (Literal.isUTF16()) 3114 Kind = CharacterLiteral::UTF16; 3115 else if (Literal.isUTF32()) 3116 Kind = CharacterLiteral::UTF32; 3117 3118 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3119 Tok.getLocation()); 3120 3121 if (Literal.getUDSuffix().empty()) 3122 return Lit; 3123 3124 // We're building a user-defined literal. 3125 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3126 SourceLocation UDSuffixLoc = 3127 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3128 3129 // Make sure we're allowed user-defined literals here. 3130 if (!UDLScope) 3131 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3132 3133 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3134 // operator "" X (ch) 3135 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3136 Lit, Tok.getLocation()); 3137 } 3138 3139 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3140 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3141 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3142 Context.IntTy, Loc); 3143 } 3144 3145 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3146 QualType Ty, SourceLocation Loc) { 3147 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3148 3149 using llvm::APFloat; 3150 APFloat Val(Format); 3151 3152 APFloat::opStatus result = Literal.GetFloatValue(Val); 3153 3154 // Overflow is always an error, but underflow is only an error if 3155 // we underflowed to zero (APFloat reports denormals as underflow). 3156 if ((result & APFloat::opOverflow) || 3157 ((result & APFloat::opUnderflow) && Val.isZero())) { 3158 unsigned diagnostic; 3159 SmallString<20> buffer; 3160 if (result & APFloat::opOverflow) { 3161 diagnostic = diag::warn_float_overflow; 3162 APFloat::getLargest(Format).toString(buffer); 3163 } else { 3164 diagnostic = diag::warn_float_underflow; 3165 APFloat::getSmallest(Format).toString(buffer); 3166 } 3167 3168 S.Diag(Loc, diagnostic) 3169 << Ty 3170 << StringRef(buffer.data(), buffer.size()); 3171 } 3172 3173 bool isExact = (result == APFloat::opOK); 3174 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3175 } 3176 3177 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3178 assert(E && "Invalid expression"); 3179 3180 if (E->isValueDependent()) 3181 return false; 3182 3183 QualType QT = E->getType(); 3184 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3185 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3186 return true; 3187 } 3188 3189 llvm::APSInt ValueAPS; 3190 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3191 3192 if (R.isInvalid()) 3193 return true; 3194 3195 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3196 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3197 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3198 << ValueAPS.toString(10) << ValueIsPositive; 3199 return true; 3200 } 3201 3202 return false; 3203 } 3204 3205 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3206 // Fast path for a single digit (which is quite common). A single digit 3207 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3208 if (Tok.getLength() == 1) { 3209 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3210 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3211 } 3212 3213 SmallString<128> SpellingBuffer; 3214 // NumericLiteralParser wants to overread by one character. Add padding to 3215 // the buffer in case the token is copied to the buffer. If getSpelling() 3216 // returns a StringRef to the memory buffer, it should have a null char at 3217 // the EOF, so it is also safe. 3218 SpellingBuffer.resize(Tok.getLength() + 1); 3219 3220 // Get the spelling of the token, which eliminates trigraphs, etc. 3221 bool Invalid = false; 3222 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3223 if (Invalid) 3224 return ExprError(); 3225 3226 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3227 if (Literal.hadError) 3228 return ExprError(); 3229 3230 if (Literal.hasUDSuffix()) { 3231 // We're building a user-defined literal. 3232 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3233 SourceLocation UDSuffixLoc = 3234 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3235 3236 // Make sure we're allowed user-defined literals here. 3237 if (!UDLScope) 3238 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3239 3240 QualType CookedTy; 3241 if (Literal.isFloatingLiteral()) { 3242 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3243 // long double, the literal is treated as a call of the form 3244 // operator "" X (f L) 3245 CookedTy = Context.LongDoubleTy; 3246 } else { 3247 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3248 // unsigned long long, the literal is treated as a call of the form 3249 // operator "" X (n ULL) 3250 CookedTy = Context.UnsignedLongLongTy; 3251 } 3252 3253 DeclarationName OpName = 3254 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3255 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3256 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3257 3258 SourceLocation TokLoc = Tok.getLocation(); 3259 3260 // Perform literal operator lookup to determine if we're building a raw 3261 // literal or a cooked one. 3262 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3263 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3264 /*AllowRaw*/true, /*AllowTemplate*/true, 3265 /*AllowStringTemplate*/false)) { 3266 case LOLR_Error: 3267 return ExprError(); 3268 3269 case LOLR_Cooked: { 3270 Expr *Lit; 3271 if (Literal.isFloatingLiteral()) { 3272 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3273 } else { 3274 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3275 if (Literal.GetIntegerValue(ResultVal)) 3276 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3277 << /* Unsigned */ 1; 3278 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3279 Tok.getLocation()); 3280 } 3281 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3282 } 3283 3284 case LOLR_Raw: { 3285 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3286 // literal is treated as a call of the form 3287 // operator "" X ("n") 3288 unsigned Length = Literal.getUDSuffixOffset(); 3289 QualType StrTy = Context.getConstantArrayType( 3290 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3291 ArrayType::Normal, 0); 3292 Expr *Lit = StringLiteral::Create( 3293 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3294 /*Pascal*/false, StrTy, &TokLoc, 1); 3295 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3296 } 3297 3298 case LOLR_Template: { 3299 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3300 // template), L is treated as a call fo the form 3301 // operator "" X <'c1', 'c2', ... 'ck'>() 3302 // where n is the source character sequence c1 c2 ... ck. 3303 TemplateArgumentListInfo ExplicitArgs; 3304 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3305 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3306 llvm::APSInt Value(CharBits, CharIsUnsigned); 3307 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3308 Value = TokSpelling[I]; 3309 TemplateArgument Arg(Context, Value, Context.CharTy); 3310 TemplateArgumentLocInfo ArgInfo; 3311 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3312 } 3313 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3314 &ExplicitArgs); 3315 } 3316 case LOLR_StringTemplate: 3317 llvm_unreachable("unexpected literal operator lookup result"); 3318 } 3319 } 3320 3321 Expr *Res; 3322 3323 if (Literal.isFloatingLiteral()) { 3324 QualType Ty; 3325 if (Literal.isFloat) 3326 Ty = Context.FloatTy; 3327 else if (!Literal.isLong) 3328 Ty = Context.DoubleTy; 3329 else 3330 Ty = Context.LongDoubleTy; 3331 3332 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3333 3334 if (Ty == Context.DoubleTy) { 3335 if (getLangOpts().SinglePrecisionConstants) { 3336 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3337 } else if (getLangOpts().OpenCL && 3338 !((getLangOpts().OpenCLVersion >= 120) || 3339 getOpenCLOptions().cl_khr_fp64)) { 3340 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3341 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3342 } 3343 } 3344 } else if (!Literal.isIntegerLiteral()) { 3345 return ExprError(); 3346 } else { 3347 QualType Ty; 3348 3349 // 'long long' is a C99 or C++11 feature. 3350 if (!getLangOpts().C99 && Literal.isLongLong) { 3351 if (getLangOpts().CPlusPlus) 3352 Diag(Tok.getLocation(), 3353 getLangOpts().CPlusPlus11 ? 3354 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3355 else 3356 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3357 } 3358 3359 // Get the value in the widest-possible width. 3360 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3361 llvm::APInt ResultVal(MaxWidth, 0); 3362 3363 if (Literal.GetIntegerValue(ResultVal)) { 3364 // If this value didn't fit into uintmax_t, error and force to ull. 3365 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3366 << /* Unsigned */ 1; 3367 Ty = Context.UnsignedLongLongTy; 3368 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3369 "long long is not intmax_t?"); 3370 } else { 3371 // If this value fits into a ULL, try to figure out what else it fits into 3372 // according to the rules of C99 6.4.4.1p5. 3373 3374 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3375 // be an unsigned int. 3376 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3377 3378 // Check from smallest to largest, picking the smallest type we can. 3379 unsigned Width = 0; 3380 3381 // Microsoft specific integer suffixes are explicitly sized. 3382 if (Literal.MicrosoftInteger) { 3383 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3384 Width = 8; 3385 Ty = Context.CharTy; 3386 } else { 3387 Width = Literal.MicrosoftInteger; 3388 Ty = Context.getIntTypeForBitwidth(Width, 3389 /*Signed=*/!Literal.isUnsigned); 3390 } 3391 } 3392 3393 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3394 // Are int/unsigned possibilities? 3395 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3396 3397 // Does it fit in a unsigned int? 3398 if (ResultVal.isIntN(IntSize)) { 3399 // Does it fit in a signed int? 3400 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3401 Ty = Context.IntTy; 3402 else if (AllowUnsigned) 3403 Ty = Context.UnsignedIntTy; 3404 Width = IntSize; 3405 } 3406 } 3407 3408 // Are long/unsigned long possibilities? 3409 if (Ty.isNull() && !Literal.isLongLong) { 3410 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3411 3412 // Does it fit in a unsigned long? 3413 if (ResultVal.isIntN(LongSize)) { 3414 // Does it fit in a signed long? 3415 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3416 Ty = Context.LongTy; 3417 else if (AllowUnsigned) 3418 Ty = Context.UnsignedLongTy; 3419 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3420 // is compatible. 3421 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3422 const unsigned LongLongSize = 3423 Context.getTargetInfo().getLongLongWidth(); 3424 Diag(Tok.getLocation(), 3425 getLangOpts().CPlusPlus 3426 ? Literal.isLong 3427 ? diag::warn_old_implicitly_unsigned_long_cxx 3428 : /*C++98 UB*/ diag:: 3429 ext_old_implicitly_unsigned_long_cxx 3430 : diag::warn_old_implicitly_unsigned_long) 3431 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3432 : /*will be ill-formed*/ 1); 3433 Ty = Context.UnsignedLongTy; 3434 } 3435 Width = LongSize; 3436 } 3437 } 3438 3439 // Check long long if needed. 3440 if (Ty.isNull()) { 3441 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3442 3443 // Does it fit in a unsigned long long? 3444 if (ResultVal.isIntN(LongLongSize)) { 3445 // Does it fit in a signed long long? 3446 // To be compatible with MSVC, hex integer literals ending with the 3447 // LL or i64 suffix are always signed in Microsoft mode. 3448 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3449 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3450 Ty = Context.LongLongTy; 3451 else if (AllowUnsigned) 3452 Ty = Context.UnsignedLongLongTy; 3453 Width = LongLongSize; 3454 } 3455 } 3456 3457 // If we still couldn't decide a type, we probably have something that 3458 // does not fit in a signed long long, but has no U suffix. 3459 if (Ty.isNull()) { 3460 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3461 Ty = Context.UnsignedLongLongTy; 3462 Width = Context.getTargetInfo().getLongLongWidth(); 3463 } 3464 3465 if (ResultVal.getBitWidth() != Width) 3466 ResultVal = ResultVal.trunc(Width); 3467 } 3468 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3469 } 3470 3471 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3472 if (Literal.isImaginary) 3473 Res = new (Context) ImaginaryLiteral(Res, 3474 Context.getComplexType(Res->getType())); 3475 3476 return Res; 3477 } 3478 3479 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3480 assert(E && "ActOnParenExpr() missing expr"); 3481 return new (Context) ParenExpr(L, R, E); 3482 } 3483 3484 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3485 SourceLocation Loc, 3486 SourceRange ArgRange) { 3487 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3488 // scalar or vector data type argument..." 3489 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3490 // type (C99 6.2.5p18) or void. 3491 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3492 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3493 << T << ArgRange; 3494 return true; 3495 } 3496 3497 assert((T->isVoidType() || !T->isIncompleteType()) && 3498 "Scalar types should always be complete"); 3499 return false; 3500 } 3501 3502 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3503 SourceLocation Loc, 3504 SourceRange ArgRange, 3505 UnaryExprOrTypeTrait TraitKind) { 3506 // Invalid types must be hard errors for SFINAE in C++. 3507 if (S.LangOpts.CPlusPlus) 3508 return true; 3509 3510 // C99 6.5.3.4p1: 3511 if (T->isFunctionType() && 3512 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3513 // sizeof(function)/alignof(function) is allowed as an extension. 3514 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3515 << TraitKind << ArgRange; 3516 return false; 3517 } 3518 3519 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3520 // this is an error (OpenCL v1.1 s6.3.k) 3521 if (T->isVoidType()) { 3522 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3523 : diag::ext_sizeof_alignof_void_type; 3524 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3525 return false; 3526 } 3527 3528 return true; 3529 } 3530 3531 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3532 SourceLocation Loc, 3533 SourceRange ArgRange, 3534 UnaryExprOrTypeTrait TraitKind) { 3535 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3536 // runtime doesn't allow it. 3537 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3538 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3539 << T << (TraitKind == UETT_SizeOf) 3540 << ArgRange; 3541 return true; 3542 } 3543 3544 return false; 3545 } 3546 3547 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3548 /// pointer type is equal to T) and emit a warning if it is. 3549 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3550 Expr *E) { 3551 // Don't warn if the operation changed the type. 3552 if (T != E->getType()) 3553 return; 3554 3555 // Now look for array decays. 3556 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3557 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3558 return; 3559 3560 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3561 << ICE->getType() 3562 << ICE->getSubExpr()->getType(); 3563 } 3564 3565 /// \brief Check the constraints on expression operands to unary type expression 3566 /// and type traits. 3567 /// 3568 /// Completes any types necessary and validates the constraints on the operand 3569 /// expression. The logic mostly mirrors the type-based overload, but may modify 3570 /// the expression as it completes the type for that expression through template 3571 /// instantiation, etc. 3572 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3573 UnaryExprOrTypeTrait ExprKind) { 3574 QualType ExprTy = E->getType(); 3575 assert(!ExprTy->isReferenceType()); 3576 3577 if (ExprKind == UETT_VecStep) 3578 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3579 E->getSourceRange()); 3580 3581 // Whitelist some types as extensions 3582 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3583 E->getSourceRange(), ExprKind)) 3584 return false; 3585 3586 // 'alignof' applied to an expression only requires the base element type of 3587 // the expression to be complete. 'sizeof' requires the expression's type to 3588 // be complete (and will attempt to complete it if it's an array of unknown 3589 // bound). 3590 if (ExprKind == UETT_AlignOf) { 3591 if (RequireCompleteType(E->getExprLoc(), 3592 Context.getBaseElementType(E->getType()), 3593 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3594 E->getSourceRange())) 3595 return true; 3596 } else { 3597 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3598 ExprKind, E->getSourceRange())) 3599 return true; 3600 } 3601 3602 // Completing the expression's type may have changed it. 3603 ExprTy = E->getType(); 3604 assert(!ExprTy->isReferenceType()); 3605 3606 if (ExprTy->isFunctionType()) { 3607 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3608 << ExprKind << E->getSourceRange(); 3609 return true; 3610 } 3611 3612 // The operand for sizeof and alignof is in an unevaluated expression context, 3613 // so side effects could result in unintended consequences. 3614 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3615 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3616 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3617 3618 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3619 E->getSourceRange(), ExprKind)) 3620 return true; 3621 3622 if (ExprKind == UETT_SizeOf) { 3623 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3624 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3625 QualType OType = PVD->getOriginalType(); 3626 QualType Type = PVD->getType(); 3627 if (Type->isPointerType() && OType->isArrayType()) { 3628 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3629 << Type << OType; 3630 Diag(PVD->getLocation(), diag::note_declared_at); 3631 } 3632 } 3633 } 3634 3635 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3636 // decays into a pointer and returns an unintended result. This is most 3637 // likely a typo for "sizeof(array) op x". 3638 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3639 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3640 BO->getLHS()); 3641 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3642 BO->getRHS()); 3643 } 3644 } 3645 3646 return false; 3647 } 3648 3649 /// \brief Check the constraints on operands to unary expression and type 3650 /// traits. 3651 /// 3652 /// This will complete any types necessary, and validate the various constraints 3653 /// on those operands. 3654 /// 3655 /// The UsualUnaryConversions() function is *not* called by this routine. 3656 /// C99 6.3.2.1p[2-4] all state: 3657 /// Except when it is the operand of the sizeof operator ... 3658 /// 3659 /// C++ [expr.sizeof]p4 3660 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3661 /// standard conversions are not applied to the operand of sizeof. 3662 /// 3663 /// This policy is followed for all of the unary trait expressions. 3664 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3665 SourceLocation OpLoc, 3666 SourceRange ExprRange, 3667 UnaryExprOrTypeTrait ExprKind) { 3668 if (ExprType->isDependentType()) 3669 return false; 3670 3671 // C++ [expr.sizeof]p2: 3672 // When applied to a reference or a reference type, the result 3673 // is the size of the referenced type. 3674 // C++11 [expr.alignof]p3: 3675 // When alignof is applied to a reference type, the result 3676 // shall be the alignment of the referenced type. 3677 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3678 ExprType = Ref->getPointeeType(); 3679 3680 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3681 // When alignof or _Alignof is applied to an array type, the result 3682 // is the alignment of the element type. 3683 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3684 ExprType = Context.getBaseElementType(ExprType); 3685 3686 if (ExprKind == UETT_VecStep) 3687 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3688 3689 // Whitelist some types as extensions 3690 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3691 ExprKind)) 3692 return false; 3693 3694 if (RequireCompleteType(OpLoc, ExprType, 3695 diag::err_sizeof_alignof_incomplete_type, 3696 ExprKind, ExprRange)) 3697 return true; 3698 3699 if (ExprType->isFunctionType()) { 3700 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3701 << ExprKind << ExprRange; 3702 return true; 3703 } 3704 3705 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3706 ExprKind)) 3707 return true; 3708 3709 return false; 3710 } 3711 3712 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3713 E = E->IgnoreParens(); 3714 3715 // Cannot know anything else if the expression is dependent. 3716 if (E->isTypeDependent()) 3717 return false; 3718 3719 if (E->getObjectKind() == OK_BitField) { 3720 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3721 << 1 << E->getSourceRange(); 3722 return true; 3723 } 3724 3725 ValueDecl *D = nullptr; 3726 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3727 D = DRE->getDecl(); 3728 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3729 D = ME->getMemberDecl(); 3730 } 3731 3732 // If it's a field, require the containing struct to have a 3733 // complete definition so that we can compute the layout. 3734 // 3735 // This can happen in C++11 onwards, either by naming the member 3736 // in a way that is not transformed into a member access expression 3737 // (in an unevaluated operand, for instance), or by naming the member 3738 // in a trailing-return-type. 3739 // 3740 // For the record, since __alignof__ on expressions is a GCC 3741 // extension, GCC seems to permit this but always gives the 3742 // nonsensical answer 0. 3743 // 3744 // We don't really need the layout here --- we could instead just 3745 // directly check for all the appropriate alignment-lowing 3746 // attributes --- but that would require duplicating a lot of 3747 // logic that just isn't worth duplicating for such a marginal 3748 // use-case. 3749 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3750 // Fast path this check, since we at least know the record has a 3751 // definition if we can find a member of it. 3752 if (!FD->getParent()->isCompleteDefinition()) { 3753 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3754 << E->getSourceRange(); 3755 return true; 3756 } 3757 3758 // Otherwise, if it's a field, and the field doesn't have 3759 // reference type, then it must have a complete type (or be a 3760 // flexible array member, which we explicitly want to 3761 // white-list anyway), which makes the following checks trivial. 3762 if (!FD->getType()->isReferenceType()) 3763 return false; 3764 } 3765 3766 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3767 } 3768 3769 bool Sema::CheckVecStepExpr(Expr *E) { 3770 E = E->IgnoreParens(); 3771 3772 // Cannot know anything else if the expression is dependent. 3773 if (E->isTypeDependent()) 3774 return false; 3775 3776 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3777 } 3778 3779 /// \brief Build a sizeof or alignof expression given a type operand. 3780 ExprResult 3781 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3782 SourceLocation OpLoc, 3783 UnaryExprOrTypeTrait ExprKind, 3784 SourceRange R) { 3785 if (!TInfo) 3786 return ExprError(); 3787 3788 QualType T = TInfo->getType(); 3789 3790 if (!T->isDependentType() && 3791 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3792 return ExprError(); 3793 3794 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3795 return new (Context) UnaryExprOrTypeTraitExpr( 3796 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3797 } 3798 3799 /// \brief Build a sizeof or alignof expression given an expression 3800 /// operand. 3801 ExprResult 3802 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3803 UnaryExprOrTypeTrait ExprKind) { 3804 ExprResult PE = CheckPlaceholderExpr(E); 3805 if (PE.isInvalid()) 3806 return ExprError(); 3807 3808 E = PE.get(); 3809 3810 // Verify that the operand is valid. 3811 bool isInvalid = false; 3812 if (E->isTypeDependent()) { 3813 // Delay type-checking for type-dependent expressions. 3814 } else if (ExprKind == UETT_AlignOf) { 3815 isInvalid = CheckAlignOfExpr(*this, E); 3816 } else if (ExprKind == UETT_VecStep) { 3817 isInvalid = CheckVecStepExpr(E); 3818 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3819 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3820 isInvalid = true; 3821 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3822 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3823 isInvalid = true; 3824 } else { 3825 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3826 } 3827 3828 if (isInvalid) 3829 return ExprError(); 3830 3831 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3832 PE = TransformToPotentiallyEvaluated(E); 3833 if (PE.isInvalid()) return ExprError(); 3834 E = PE.get(); 3835 } 3836 3837 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3838 return new (Context) UnaryExprOrTypeTraitExpr( 3839 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3840 } 3841 3842 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3843 /// expr and the same for @c alignof and @c __alignof 3844 /// Note that the ArgRange is invalid if isType is false. 3845 ExprResult 3846 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3847 UnaryExprOrTypeTrait ExprKind, bool IsType, 3848 void *TyOrEx, const SourceRange &ArgRange) { 3849 // If error parsing type, ignore. 3850 if (!TyOrEx) return ExprError(); 3851 3852 if (IsType) { 3853 TypeSourceInfo *TInfo; 3854 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3855 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3856 } 3857 3858 Expr *ArgEx = (Expr *)TyOrEx; 3859 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3860 return Result; 3861 } 3862 3863 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3864 bool IsReal) { 3865 if (V.get()->isTypeDependent()) 3866 return S.Context.DependentTy; 3867 3868 // _Real and _Imag are only l-values for normal l-values. 3869 if (V.get()->getObjectKind() != OK_Ordinary) { 3870 V = S.DefaultLvalueConversion(V.get()); 3871 if (V.isInvalid()) 3872 return QualType(); 3873 } 3874 3875 // These operators return the element type of a complex type. 3876 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3877 return CT->getElementType(); 3878 3879 // Otherwise they pass through real integer and floating point types here. 3880 if (V.get()->getType()->isArithmeticType()) 3881 return V.get()->getType(); 3882 3883 // Test for placeholders. 3884 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3885 if (PR.isInvalid()) return QualType(); 3886 if (PR.get() != V.get()) { 3887 V = PR; 3888 return CheckRealImagOperand(S, V, Loc, IsReal); 3889 } 3890 3891 // Reject anything else. 3892 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3893 << (IsReal ? "__real" : "__imag"); 3894 return QualType(); 3895 } 3896 3897 3898 3899 ExprResult 3900 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3901 tok::TokenKind Kind, Expr *Input) { 3902 UnaryOperatorKind Opc; 3903 switch (Kind) { 3904 default: llvm_unreachable("Unknown unary op!"); 3905 case tok::plusplus: Opc = UO_PostInc; break; 3906 case tok::minusminus: Opc = UO_PostDec; break; 3907 } 3908 3909 // Since this might is a postfix expression, get rid of ParenListExprs. 3910 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3911 if (Result.isInvalid()) return ExprError(); 3912 Input = Result.get(); 3913 3914 return BuildUnaryOp(S, OpLoc, Opc, Input); 3915 } 3916 3917 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3918 /// 3919 /// \return true on error 3920 static bool checkArithmeticOnObjCPointer(Sema &S, 3921 SourceLocation opLoc, 3922 Expr *op) { 3923 assert(op->getType()->isObjCObjectPointerType()); 3924 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3925 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3926 return false; 3927 3928 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3929 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3930 << op->getSourceRange(); 3931 return true; 3932 } 3933 3934 ExprResult 3935 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3936 Expr *idx, SourceLocation rbLoc) { 3937 if (base && !base->getType().isNull() && 3938 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 3939 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 3940 /*Length=*/nullptr, rbLoc); 3941 3942 // Since this might be a postfix expression, get rid of ParenListExprs. 3943 if (isa<ParenListExpr>(base)) { 3944 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3945 if (result.isInvalid()) return ExprError(); 3946 base = result.get(); 3947 } 3948 3949 // Handle any non-overload placeholder types in the base and index 3950 // expressions. We can't handle overloads here because the other 3951 // operand might be an overloadable type, in which case the overload 3952 // resolution for the operator overload should get the first crack 3953 // at the overload. 3954 if (base->getType()->isNonOverloadPlaceholderType()) { 3955 ExprResult result = CheckPlaceholderExpr(base); 3956 if (result.isInvalid()) return ExprError(); 3957 base = result.get(); 3958 } 3959 if (idx->getType()->isNonOverloadPlaceholderType()) { 3960 ExprResult result = CheckPlaceholderExpr(idx); 3961 if (result.isInvalid()) return ExprError(); 3962 idx = result.get(); 3963 } 3964 3965 // Build an unanalyzed expression if either operand is type-dependent. 3966 if (getLangOpts().CPlusPlus && 3967 (base->isTypeDependent() || idx->isTypeDependent())) { 3968 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3969 VK_LValue, OK_Ordinary, rbLoc); 3970 } 3971 3972 // Use C++ overloaded-operator rules if either operand has record 3973 // type. The spec says to do this if either type is *overloadable*, 3974 // but enum types can't declare subscript operators or conversion 3975 // operators, so there's nothing interesting for overload resolution 3976 // to do if there aren't any record types involved. 3977 // 3978 // ObjC pointers have their own subscripting logic that is not tied 3979 // to overload resolution and so should not take this path. 3980 if (getLangOpts().CPlusPlus && 3981 (base->getType()->isRecordType() || 3982 (!base->getType()->isObjCObjectPointerType() && 3983 idx->getType()->isRecordType()))) { 3984 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3985 } 3986 3987 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3988 } 3989 3990 static QualType getNonOMPArraySectionType(Expr *Base) { 3991 unsigned ArraySectionCount = 0; 3992 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) { 3993 Base = OASE->getBase(); 3994 ++ArraySectionCount; 3995 } 3996 auto OriginalTy = Base->getType(); 3997 if (auto *DRE = dyn_cast<DeclRefExpr>(Base)) 3998 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3999 OriginalTy = PVD->getOriginalType().getNonReferenceType(); 4000 4001 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) { 4002 if (OriginalTy->isAnyPointerType()) 4003 OriginalTy = OriginalTy->getPointeeType(); 4004 else { 4005 assert (OriginalTy->isArrayType()); 4006 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType(); 4007 } 4008 } 4009 return OriginalTy; 4010 } 4011 4012 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4013 Expr *LowerBound, 4014 SourceLocation ColonLoc, Expr *Length, 4015 SourceLocation RBLoc) { 4016 if (Base->getType()->isPlaceholderType() && 4017 !Base->getType()->isSpecificPlaceholderType( 4018 BuiltinType::OMPArraySection)) { 4019 ExprResult Result = CheckPlaceholderExpr(Base); 4020 if (Result.isInvalid()) 4021 return ExprError(); 4022 Base = Result.get(); 4023 } 4024 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4025 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4026 if (Result.isInvalid()) 4027 return ExprError(); 4028 LowerBound = Result.get(); 4029 } 4030 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4031 ExprResult Result = CheckPlaceholderExpr(Length); 4032 if (Result.isInvalid()) 4033 return ExprError(); 4034 Length = Result.get(); 4035 } 4036 4037 // Build an unanalyzed expression if either operand is type-dependent. 4038 if (Base->isTypeDependent() || 4039 (LowerBound && 4040 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4041 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4042 return new (Context) 4043 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4044 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4045 } 4046 4047 // Perform default conversions. 4048 QualType OriginalTy = getNonOMPArraySectionType(Base); 4049 QualType ResultTy; 4050 if (OriginalTy->isAnyPointerType()) { 4051 ResultTy = OriginalTy->getPointeeType(); 4052 } else if (OriginalTy->isArrayType()) { 4053 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4054 } else { 4055 return ExprError( 4056 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4057 << Base->getSourceRange()); 4058 } 4059 // C99 6.5.2.1p1 4060 if (LowerBound) { 4061 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4062 LowerBound); 4063 if (Res.isInvalid()) 4064 return ExprError(Diag(LowerBound->getExprLoc(), 4065 diag::err_omp_typecheck_section_not_integer) 4066 << 0 << LowerBound->getSourceRange()); 4067 LowerBound = Res.get(); 4068 4069 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4070 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4071 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4072 << 0 << LowerBound->getSourceRange(); 4073 } 4074 if (Length) { 4075 auto Res = 4076 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4077 if (Res.isInvalid()) 4078 return ExprError(Diag(Length->getExprLoc(), 4079 diag::err_omp_typecheck_section_not_integer) 4080 << 1 << Length->getSourceRange()); 4081 Length = Res.get(); 4082 4083 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4084 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4085 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4086 << 1 << Length->getSourceRange(); 4087 } 4088 4089 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4090 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4091 // type. Note that functions are not objects, and that (in C99 parlance) 4092 // incomplete types are not object types. 4093 if (ResultTy->isFunctionType()) { 4094 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4095 << ResultTy << Base->getSourceRange(); 4096 return ExprError(); 4097 } 4098 4099 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4100 diag::err_omp_section_incomplete_type, Base)) 4101 return ExprError(); 4102 4103 if (LowerBound) { 4104 llvm::APSInt LowerBoundValue; 4105 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4106 // OpenMP 4.0, [2.4 Array Sections] 4107 // The lower-bound and length must evaluate to non-negative integers. 4108 if (LowerBoundValue.isNegative()) { 4109 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4110 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4111 << LowerBound->getSourceRange(); 4112 return ExprError(); 4113 } 4114 } 4115 } 4116 4117 if (Length) { 4118 llvm::APSInt LengthValue; 4119 if (Length->EvaluateAsInt(LengthValue, Context)) { 4120 // OpenMP 4.0, [2.4 Array Sections] 4121 // The lower-bound and length must evaluate to non-negative integers. 4122 if (LengthValue.isNegative()) { 4123 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4124 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4125 << Length->getSourceRange(); 4126 return ExprError(); 4127 } 4128 } 4129 } else if (ColonLoc.isValid() && 4130 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4131 !OriginalTy->isVariableArrayType()))) { 4132 // OpenMP 4.0, [2.4 Array Sections] 4133 // When the size of the array dimension is not known, the length must be 4134 // specified explicitly. 4135 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4136 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4137 return ExprError(); 4138 } 4139 4140 return new (Context) 4141 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4142 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4143 } 4144 4145 ExprResult 4146 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4147 Expr *Idx, SourceLocation RLoc) { 4148 Expr *LHSExp = Base; 4149 Expr *RHSExp = Idx; 4150 4151 // Perform default conversions. 4152 if (!LHSExp->getType()->getAs<VectorType>()) { 4153 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4154 if (Result.isInvalid()) 4155 return ExprError(); 4156 LHSExp = Result.get(); 4157 } 4158 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4159 if (Result.isInvalid()) 4160 return ExprError(); 4161 RHSExp = Result.get(); 4162 4163 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4164 ExprValueKind VK = VK_LValue; 4165 ExprObjectKind OK = OK_Ordinary; 4166 4167 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4168 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4169 // in the subscript position. As a result, we need to derive the array base 4170 // and index from the expression types. 4171 Expr *BaseExpr, *IndexExpr; 4172 QualType ResultType; 4173 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4174 BaseExpr = LHSExp; 4175 IndexExpr = RHSExp; 4176 ResultType = Context.DependentTy; 4177 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4178 BaseExpr = LHSExp; 4179 IndexExpr = RHSExp; 4180 ResultType = PTy->getPointeeType(); 4181 } else if (const ObjCObjectPointerType *PTy = 4182 LHSTy->getAs<ObjCObjectPointerType>()) { 4183 BaseExpr = LHSExp; 4184 IndexExpr = RHSExp; 4185 4186 // Use custom logic if this should be the pseudo-object subscript 4187 // expression. 4188 if (!LangOpts.isSubscriptPointerArithmetic()) 4189 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4190 nullptr); 4191 4192 ResultType = PTy->getPointeeType(); 4193 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4194 // Handle the uncommon case of "123[Ptr]". 4195 BaseExpr = RHSExp; 4196 IndexExpr = LHSExp; 4197 ResultType = PTy->getPointeeType(); 4198 } else if (const ObjCObjectPointerType *PTy = 4199 RHSTy->getAs<ObjCObjectPointerType>()) { 4200 // Handle the uncommon case of "123[Ptr]". 4201 BaseExpr = RHSExp; 4202 IndexExpr = LHSExp; 4203 ResultType = PTy->getPointeeType(); 4204 if (!LangOpts.isSubscriptPointerArithmetic()) { 4205 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4206 << ResultType << BaseExpr->getSourceRange(); 4207 return ExprError(); 4208 } 4209 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4210 BaseExpr = LHSExp; // vectors: V[123] 4211 IndexExpr = RHSExp; 4212 VK = LHSExp->getValueKind(); 4213 if (VK != VK_RValue) 4214 OK = OK_VectorComponent; 4215 4216 // FIXME: need to deal with const... 4217 ResultType = VTy->getElementType(); 4218 } else if (LHSTy->isArrayType()) { 4219 // If we see an array that wasn't promoted by 4220 // DefaultFunctionArrayLvalueConversion, it must be an array that 4221 // wasn't promoted because of the C90 rule that doesn't 4222 // allow promoting non-lvalue arrays. Warn, then 4223 // force the promotion here. 4224 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4225 LHSExp->getSourceRange(); 4226 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4227 CK_ArrayToPointerDecay).get(); 4228 LHSTy = LHSExp->getType(); 4229 4230 BaseExpr = LHSExp; 4231 IndexExpr = RHSExp; 4232 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4233 } else if (RHSTy->isArrayType()) { 4234 // Same as previous, except for 123[f().a] case 4235 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4236 RHSExp->getSourceRange(); 4237 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4238 CK_ArrayToPointerDecay).get(); 4239 RHSTy = RHSExp->getType(); 4240 4241 BaseExpr = RHSExp; 4242 IndexExpr = LHSExp; 4243 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4244 } else { 4245 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4246 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4247 } 4248 // C99 6.5.2.1p1 4249 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4250 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4251 << IndexExpr->getSourceRange()); 4252 4253 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4254 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4255 && !IndexExpr->isTypeDependent()) 4256 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4257 4258 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4259 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4260 // type. Note that Functions are not objects, and that (in C99 parlance) 4261 // incomplete types are not object types. 4262 if (ResultType->isFunctionType()) { 4263 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4264 << ResultType << BaseExpr->getSourceRange(); 4265 return ExprError(); 4266 } 4267 4268 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4269 // GNU extension: subscripting on pointer to void 4270 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4271 << BaseExpr->getSourceRange(); 4272 4273 // C forbids expressions of unqualified void type from being l-values. 4274 // See IsCForbiddenLValueType. 4275 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4276 } else if (!ResultType->isDependentType() && 4277 RequireCompleteType(LLoc, ResultType, 4278 diag::err_subscript_incomplete_type, BaseExpr)) 4279 return ExprError(); 4280 4281 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4282 !ResultType.isCForbiddenLValueType()); 4283 4284 return new (Context) 4285 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4286 } 4287 4288 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4289 FunctionDecl *FD, 4290 ParmVarDecl *Param) { 4291 if (Param->hasUnparsedDefaultArg()) { 4292 Diag(CallLoc, 4293 diag::err_use_of_default_argument_to_function_declared_later) << 4294 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4295 Diag(UnparsedDefaultArgLocs[Param], 4296 diag::note_default_argument_declared_here); 4297 return ExprError(); 4298 } 4299 4300 if (Param->hasUninstantiatedDefaultArg()) { 4301 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4302 4303 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4304 Param); 4305 4306 // Instantiate the expression. 4307 MultiLevelTemplateArgumentList MutiLevelArgList 4308 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4309 4310 InstantiatingTemplate Inst(*this, CallLoc, Param, 4311 MutiLevelArgList.getInnermost()); 4312 if (Inst.isInvalid()) 4313 return ExprError(); 4314 4315 ExprResult Result; 4316 { 4317 // C++ [dcl.fct.default]p5: 4318 // The names in the [default argument] expression are bound, and 4319 // the semantic constraints are checked, at the point where the 4320 // default argument expression appears. 4321 ContextRAII SavedContext(*this, FD); 4322 LocalInstantiationScope Local(*this); 4323 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4324 } 4325 if (Result.isInvalid()) 4326 return ExprError(); 4327 4328 // Check the expression as an initializer for the parameter. 4329 InitializedEntity Entity 4330 = InitializedEntity::InitializeParameter(Context, Param); 4331 InitializationKind Kind 4332 = InitializationKind::CreateCopy(Param->getLocation(), 4333 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4334 Expr *ResultE = Result.getAs<Expr>(); 4335 4336 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4337 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4338 if (Result.isInvalid()) 4339 return ExprError(); 4340 4341 Expr *Arg = Result.getAs<Expr>(); 4342 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4343 // Build the default argument expression. 4344 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4345 } 4346 4347 // If the default expression creates temporaries, we need to 4348 // push them to the current stack of expression temporaries so they'll 4349 // be properly destroyed. 4350 // FIXME: We should really be rebuilding the default argument with new 4351 // bound temporaries; see the comment in PR5810. 4352 // We don't need to do that with block decls, though, because 4353 // blocks in default argument expression can never capture anything. 4354 if (isa<ExprWithCleanups>(Param->getInit())) { 4355 // Set the "needs cleanups" bit regardless of whether there are 4356 // any explicit objects. 4357 ExprNeedsCleanups = true; 4358 4359 // Append all the objects to the cleanup list. Right now, this 4360 // should always be a no-op, because blocks in default argument 4361 // expressions should never be able to capture anything. 4362 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4363 "default argument expression has capturing blocks?"); 4364 } 4365 4366 // We already type-checked the argument, so we know it works. 4367 // Just mark all of the declarations in this potentially-evaluated expression 4368 // as being "referenced". 4369 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4370 /*SkipLocalVariables=*/true); 4371 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4372 } 4373 4374 4375 Sema::VariadicCallType 4376 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4377 Expr *Fn) { 4378 if (Proto && Proto->isVariadic()) { 4379 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4380 return VariadicConstructor; 4381 else if (Fn && Fn->getType()->isBlockPointerType()) 4382 return VariadicBlock; 4383 else if (FDecl) { 4384 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4385 if (Method->isInstance()) 4386 return VariadicMethod; 4387 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4388 return VariadicMethod; 4389 return VariadicFunction; 4390 } 4391 return VariadicDoesNotApply; 4392 } 4393 4394 namespace { 4395 class FunctionCallCCC : public FunctionCallFilterCCC { 4396 public: 4397 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4398 unsigned NumArgs, MemberExpr *ME) 4399 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4400 FunctionName(FuncName) {} 4401 4402 bool ValidateCandidate(const TypoCorrection &candidate) override { 4403 if (!candidate.getCorrectionSpecifier() || 4404 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4405 return false; 4406 } 4407 4408 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4409 } 4410 4411 private: 4412 const IdentifierInfo *const FunctionName; 4413 }; 4414 } 4415 4416 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4417 FunctionDecl *FDecl, 4418 ArrayRef<Expr *> Args) { 4419 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4420 DeclarationName FuncName = FDecl->getDeclName(); 4421 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4422 4423 if (TypoCorrection Corrected = S.CorrectTypo( 4424 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4425 S.getScopeForContext(S.CurContext), nullptr, 4426 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4427 Args.size(), ME), 4428 Sema::CTK_ErrorRecovery)) { 4429 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4430 if (Corrected.isOverloaded()) { 4431 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4432 OverloadCandidateSet::iterator Best; 4433 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4434 CDEnd = Corrected.end(); 4435 CD != CDEnd; ++CD) { 4436 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4437 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4438 OCS); 4439 } 4440 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4441 case OR_Success: 4442 ND = Best->Function; 4443 Corrected.setCorrectionDecl(ND); 4444 break; 4445 default: 4446 break; 4447 } 4448 } 4449 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4450 return Corrected; 4451 } 4452 } 4453 } 4454 return TypoCorrection(); 4455 } 4456 4457 /// ConvertArgumentsForCall - Converts the arguments specified in 4458 /// Args/NumArgs to the parameter types of the function FDecl with 4459 /// function prototype Proto. Call is the call expression itself, and 4460 /// Fn is the function expression. For a C++ member function, this 4461 /// routine does not attempt to convert the object argument. Returns 4462 /// true if the call is ill-formed. 4463 bool 4464 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4465 FunctionDecl *FDecl, 4466 const FunctionProtoType *Proto, 4467 ArrayRef<Expr *> Args, 4468 SourceLocation RParenLoc, 4469 bool IsExecConfig) { 4470 // Bail out early if calling a builtin with custom typechecking. 4471 if (FDecl) 4472 if (unsigned ID = FDecl->getBuiltinID()) 4473 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4474 return false; 4475 4476 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4477 // assignment, to the types of the corresponding parameter, ... 4478 unsigned NumParams = Proto->getNumParams(); 4479 bool Invalid = false; 4480 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4481 unsigned FnKind = Fn->getType()->isBlockPointerType() 4482 ? 1 /* block */ 4483 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4484 : 0 /* function */); 4485 4486 // If too few arguments are available (and we don't have default 4487 // arguments for the remaining parameters), don't make the call. 4488 if (Args.size() < NumParams) { 4489 if (Args.size() < MinArgs) { 4490 TypoCorrection TC; 4491 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4492 unsigned diag_id = 4493 MinArgs == NumParams && !Proto->isVariadic() 4494 ? diag::err_typecheck_call_too_few_args_suggest 4495 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4496 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4497 << static_cast<unsigned>(Args.size()) 4498 << TC.getCorrectionRange()); 4499 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4500 Diag(RParenLoc, 4501 MinArgs == NumParams && !Proto->isVariadic() 4502 ? diag::err_typecheck_call_too_few_args_one 4503 : diag::err_typecheck_call_too_few_args_at_least_one) 4504 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4505 else 4506 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4507 ? diag::err_typecheck_call_too_few_args 4508 : diag::err_typecheck_call_too_few_args_at_least) 4509 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4510 << Fn->getSourceRange(); 4511 4512 // Emit the location of the prototype. 4513 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4514 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4515 << FDecl; 4516 4517 return true; 4518 } 4519 Call->setNumArgs(Context, NumParams); 4520 } 4521 4522 // If too many are passed and not variadic, error on the extras and drop 4523 // them. 4524 if (Args.size() > NumParams) { 4525 if (!Proto->isVariadic()) { 4526 TypoCorrection TC; 4527 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4528 unsigned diag_id = 4529 MinArgs == NumParams && !Proto->isVariadic() 4530 ? diag::err_typecheck_call_too_many_args_suggest 4531 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4532 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4533 << static_cast<unsigned>(Args.size()) 4534 << TC.getCorrectionRange()); 4535 } else if (NumParams == 1 && FDecl && 4536 FDecl->getParamDecl(0)->getDeclName()) 4537 Diag(Args[NumParams]->getLocStart(), 4538 MinArgs == NumParams 4539 ? diag::err_typecheck_call_too_many_args_one 4540 : diag::err_typecheck_call_too_many_args_at_most_one) 4541 << FnKind << FDecl->getParamDecl(0) 4542 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4543 << SourceRange(Args[NumParams]->getLocStart(), 4544 Args.back()->getLocEnd()); 4545 else 4546 Diag(Args[NumParams]->getLocStart(), 4547 MinArgs == NumParams 4548 ? diag::err_typecheck_call_too_many_args 4549 : diag::err_typecheck_call_too_many_args_at_most) 4550 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4551 << Fn->getSourceRange() 4552 << SourceRange(Args[NumParams]->getLocStart(), 4553 Args.back()->getLocEnd()); 4554 4555 // Emit the location of the prototype. 4556 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4557 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4558 << FDecl; 4559 4560 // This deletes the extra arguments. 4561 Call->setNumArgs(Context, NumParams); 4562 return true; 4563 } 4564 } 4565 SmallVector<Expr *, 8> AllArgs; 4566 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4567 4568 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4569 Proto, 0, Args, AllArgs, CallType); 4570 if (Invalid) 4571 return true; 4572 unsigned TotalNumArgs = AllArgs.size(); 4573 for (unsigned i = 0; i < TotalNumArgs; ++i) 4574 Call->setArg(i, AllArgs[i]); 4575 4576 return false; 4577 } 4578 4579 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4580 const FunctionProtoType *Proto, 4581 unsigned FirstParam, ArrayRef<Expr *> Args, 4582 SmallVectorImpl<Expr *> &AllArgs, 4583 VariadicCallType CallType, bool AllowExplicit, 4584 bool IsListInitialization) { 4585 unsigned NumParams = Proto->getNumParams(); 4586 bool Invalid = false; 4587 unsigned ArgIx = 0; 4588 // Continue to check argument types (even if we have too few/many args). 4589 for (unsigned i = FirstParam; i < NumParams; i++) { 4590 QualType ProtoArgType = Proto->getParamType(i); 4591 4592 Expr *Arg; 4593 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4594 if (ArgIx < Args.size()) { 4595 Arg = Args[ArgIx++]; 4596 4597 if (RequireCompleteType(Arg->getLocStart(), 4598 ProtoArgType, 4599 diag::err_call_incomplete_argument, Arg)) 4600 return true; 4601 4602 // Strip the unbridged-cast placeholder expression off, if applicable. 4603 bool CFAudited = false; 4604 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4605 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4606 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4607 Arg = stripARCUnbridgedCast(Arg); 4608 else if (getLangOpts().ObjCAutoRefCount && 4609 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4610 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4611 CFAudited = true; 4612 4613 InitializedEntity Entity = 4614 Param ? InitializedEntity::InitializeParameter(Context, Param, 4615 ProtoArgType) 4616 : InitializedEntity::InitializeParameter( 4617 Context, ProtoArgType, Proto->isParamConsumed(i)); 4618 4619 // Remember that parameter belongs to a CF audited API. 4620 if (CFAudited) 4621 Entity.setParameterCFAudited(); 4622 4623 ExprResult ArgE = PerformCopyInitialization( 4624 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4625 if (ArgE.isInvalid()) 4626 return true; 4627 4628 Arg = ArgE.getAs<Expr>(); 4629 } else { 4630 assert(Param && "can't use default arguments without a known callee"); 4631 4632 ExprResult ArgExpr = 4633 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4634 if (ArgExpr.isInvalid()) 4635 return true; 4636 4637 Arg = ArgExpr.getAs<Expr>(); 4638 } 4639 4640 // Check for array bounds violations for each argument to the call. This 4641 // check only triggers warnings when the argument isn't a more complex Expr 4642 // with its own checking, such as a BinaryOperator. 4643 CheckArrayAccess(Arg); 4644 4645 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4646 CheckStaticArrayArgument(CallLoc, Param, Arg); 4647 4648 AllArgs.push_back(Arg); 4649 } 4650 4651 // If this is a variadic call, handle args passed through "...". 4652 if (CallType != VariadicDoesNotApply) { 4653 // Assume that extern "C" functions with variadic arguments that 4654 // return __unknown_anytype aren't *really* variadic. 4655 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4656 FDecl->isExternC()) { 4657 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4658 QualType paramType; // ignored 4659 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4660 Invalid |= arg.isInvalid(); 4661 AllArgs.push_back(arg.get()); 4662 } 4663 4664 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4665 } else { 4666 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4667 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4668 FDecl); 4669 Invalid |= Arg.isInvalid(); 4670 AllArgs.push_back(Arg.get()); 4671 } 4672 } 4673 4674 // Check for array bounds violations. 4675 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4676 CheckArrayAccess(Args[i]); 4677 } 4678 return Invalid; 4679 } 4680 4681 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4682 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4683 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4684 TL = DTL.getOriginalLoc(); 4685 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4686 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4687 << ATL.getLocalSourceRange(); 4688 } 4689 4690 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4691 /// array parameter, check that it is non-null, and that if it is formed by 4692 /// array-to-pointer decay, the underlying array is sufficiently large. 4693 /// 4694 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4695 /// array type derivation, then for each call to the function, the value of the 4696 /// corresponding actual argument shall provide access to the first element of 4697 /// an array with at least as many elements as specified by the size expression. 4698 void 4699 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4700 ParmVarDecl *Param, 4701 const Expr *ArgExpr) { 4702 // Static array parameters are not supported in C++. 4703 if (!Param || getLangOpts().CPlusPlus) 4704 return; 4705 4706 QualType OrigTy = Param->getOriginalType(); 4707 4708 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4709 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4710 return; 4711 4712 if (ArgExpr->isNullPointerConstant(Context, 4713 Expr::NPC_NeverValueDependent)) { 4714 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4715 DiagnoseCalleeStaticArrayParam(*this, Param); 4716 return; 4717 } 4718 4719 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4720 if (!CAT) 4721 return; 4722 4723 const ConstantArrayType *ArgCAT = 4724 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4725 if (!ArgCAT) 4726 return; 4727 4728 if (ArgCAT->getSize().ult(CAT->getSize())) { 4729 Diag(CallLoc, diag::warn_static_array_too_small) 4730 << ArgExpr->getSourceRange() 4731 << (unsigned) ArgCAT->getSize().getZExtValue() 4732 << (unsigned) CAT->getSize().getZExtValue(); 4733 DiagnoseCalleeStaticArrayParam(*this, Param); 4734 } 4735 } 4736 4737 /// Given a function expression of unknown-any type, try to rebuild it 4738 /// to have a function type. 4739 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4740 4741 /// Is the given type a placeholder that we need to lower out 4742 /// immediately during argument processing? 4743 static bool isPlaceholderToRemoveAsArg(QualType type) { 4744 // Placeholders are never sugared. 4745 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4746 if (!placeholder) return false; 4747 4748 switch (placeholder->getKind()) { 4749 // Ignore all the non-placeholder types. 4750 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4751 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4752 #include "clang/AST/BuiltinTypes.def" 4753 return false; 4754 4755 // We cannot lower out overload sets; they might validly be resolved 4756 // by the call machinery. 4757 case BuiltinType::Overload: 4758 return false; 4759 4760 // Unbridged casts in ARC can be handled in some call positions and 4761 // should be left in place. 4762 case BuiltinType::ARCUnbridgedCast: 4763 return false; 4764 4765 // Pseudo-objects should be converted as soon as possible. 4766 case BuiltinType::PseudoObject: 4767 return true; 4768 4769 // The debugger mode could theoretically but currently does not try 4770 // to resolve unknown-typed arguments based on known parameter types. 4771 case BuiltinType::UnknownAny: 4772 return true; 4773 4774 // These are always invalid as call arguments and should be reported. 4775 case BuiltinType::BoundMember: 4776 case BuiltinType::BuiltinFn: 4777 case BuiltinType::OMPArraySection: 4778 return true; 4779 4780 } 4781 llvm_unreachable("bad builtin type kind"); 4782 } 4783 4784 /// Check an argument list for placeholders that we won't try to 4785 /// handle later. 4786 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4787 // Apply this processing to all the arguments at once instead of 4788 // dying at the first failure. 4789 bool hasInvalid = false; 4790 for (size_t i = 0, e = args.size(); i != e; i++) { 4791 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4792 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4793 if (result.isInvalid()) hasInvalid = true; 4794 else args[i] = result.get(); 4795 } else if (hasInvalid) { 4796 (void)S.CorrectDelayedTyposInExpr(args[i]); 4797 } 4798 } 4799 return hasInvalid; 4800 } 4801 4802 /// If a builtin function has a pointer argument with no explicit address 4803 /// space, than it should be able to accept a pointer to any address 4804 /// space as input. In order to do this, we need to replace the 4805 /// standard builtin declaration with one that uses the same address space 4806 /// as the call. 4807 /// 4808 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4809 /// it does not contain any pointer arguments without 4810 /// an address space qualifer. Otherwise the rewritten 4811 /// FunctionDecl is returned. 4812 /// TODO: Handle pointer return types. 4813 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4814 const FunctionDecl *FDecl, 4815 MultiExprArg ArgExprs) { 4816 4817 QualType DeclType = FDecl->getType(); 4818 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4819 4820 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4821 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4822 return nullptr; 4823 4824 bool NeedsNewDecl = false; 4825 unsigned i = 0; 4826 SmallVector<QualType, 8> OverloadParams; 4827 4828 for (QualType ParamType : FT->param_types()) { 4829 4830 // Convert array arguments to pointer to simplify type lookup. 4831 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4832 QualType ArgType = Arg->getType(); 4833 if (!ParamType->isPointerType() || 4834 ParamType.getQualifiers().hasAddressSpace() || 4835 !ArgType->isPointerType() || 4836 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4837 OverloadParams.push_back(ParamType); 4838 continue; 4839 } 4840 4841 NeedsNewDecl = true; 4842 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 4843 4844 QualType PointeeType = ParamType->getPointeeType(); 4845 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 4846 OverloadParams.push_back(Context.getPointerType(PointeeType)); 4847 } 4848 4849 if (!NeedsNewDecl) 4850 return nullptr; 4851 4852 FunctionProtoType::ExtProtoInfo EPI; 4853 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 4854 OverloadParams, EPI); 4855 DeclContext *Parent = Context.getTranslationUnitDecl(); 4856 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 4857 FDecl->getLocation(), 4858 FDecl->getLocation(), 4859 FDecl->getIdentifier(), 4860 OverloadTy, 4861 /*TInfo=*/nullptr, 4862 SC_Extern, false, 4863 /*hasPrototype=*/true); 4864 SmallVector<ParmVarDecl*, 16> Params; 4865 FT = cast<FunctionProtoType>(OverloadTy); 4866 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 4867 QualType ParamType = FT->getParamType(i); 4868 ParmVarDecl *Parm = 4869 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 4870 SourceLocation(), nullptr, ParamType, 4871 /*TInfo=*/nullptr, SC_None, nullptr); 4872 Parm->setScopeInfo(0, i); 4873 Params.push_back(Parm); 4874 } 4875 OverloadDecl->setParams(Params); 4876 return OverloadDecl; 4877 } 4878 4879 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4880 /// This provides the location of the left/right parens and a list of comma 4881 /// locations. 4882 ExprResult 4883 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4884 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4885 Expr *ExecConfig, bool IsExecConfig) { 4886 // Since this might be a postfix expression, get rid of ParenListExprs. 4887 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4888 if (Result.isInvalid()) return ExprError(); 4889 Fn = Result.get(); 4890 4891 if (checkArgsForPlaceholders(*this, ArgExprs)) 4892 return ExprError(); 4893 4894 if (getLangOpts().CPlusPlus) { 4895 // If this is a pseudo-destructor expression, build the call immediately. 4896 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4897 if (!ArgExprs.empty()) { 4898 // Pseudo-destructor calls should not have any arguments. 4899 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4900 << FixItHint::CreateRemoval( 4901 SourceRange(ArgExprs[0]->getLocStart(), 4902 ArgExprs.back()->getLocEnd())); 4903 } 4904 4905 return new (Context) 4906 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4907 } 4908 if (Fn->getType() == Context.PseudoObjectTy) { 4909 ExprResult result = CheckPlaceholderExpr(Fn); 4910 if (result.isInvalid()) return ExprError(); 4911 Fn = result.get(); 4912 } 4913 4914 // Determine whether this is a dependent call inside a C++ template, 4915 // in which case we won't do any semantic analysis now. 4916 // FIXME: Will need to cache the results of name lookup (including ADL) in 4917 // Fn. 4918 bool Dependent = false; 4919 if (Fn->isTypeDependent()) 4920 Dependent = true; 4921 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4922 Dependent = true; 4923 4924 if (Dependent) { 4925 if (ExecConfig) { 4926 return new (Context) CUDAKernelCallExpr( 4927 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4928 Context.DependentTy, VK_RValue, RParenLoc); 4929 } else { 4930 return new (Context) CallExpr( 4931 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4932 } 4933 } 4934 4935 // Determine whether this is a call to an object (C++ [over.call.object]). 4936 if (Fn->getType()->isRecordType()) 4937 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4938 RParenLoc); 4939 4940 if (Fn->getType() == Context.UnknownAnyTy) { 4941 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4942 if (result.isInvalid()) return ExprError(); 4943 Fn = result.get(); 4944 } 4945 4946 if (Fn->getType() == Context.BoundMemberTy) { 4947 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4948 } 4949 } 4950 4951 // Check for overloaded calls. This can happen even in C due to extensions. 4952 if (Fn->getType() == Context.OverloadTy) { 4953 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4954 4955 // We aren't supposed to apply this logic for if there's an '&' involved. 4956 if (!find.HasFormOfMemberPointer) { 4957 OverloadExpr *ovl = find.Expression; 4958 if (isa<UnresolvedLookupExpr>(ovl)) { 4959 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4960 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4961 RParenLoc, ExecConfig); 4962 } else { 4963 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4964 RParenLoc); 4965 } 4966 } 4967 } 4968 4969 // If we're directly calling a function, get the appropriate declaration. 4970 if (Fn->getType() == Context.UnknownAnyTy) { 4971 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4972 if (result.isInvalid()) return ExprError(); 4973 Fn = result.get(); 4974 } 4975 4976 Expr *NakedFn = Fn->IgnoreParens(); 4977 4978 NamedDecl *NDecl = nullptr; 4979 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4980 if (UnOp->getOpcode() == UO_AddrOf) 4981 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4982 4983 if (isa<DeclRefExpr>(NakedFn)) { 4984 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4985 4986 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 4987 if (FDecl && FDecl->getBuiltinID()) { 4988 // Rewrite the function decl for this builtin by replacing paramaters 4989 // with no explicit address space with the address space of the arguments 4990 // in ArgExprs. 4991 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 4992 NDecl = FDecl; 4993 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 4994 SourceLocation(), FDecl, false, 4995 SourceLocation(), FDecl->getType(), 4996 Fn->getValueKind(), FDecl); 4997 } 4998 } 4999 } else if (isa<MemberExpr>(NakedFn)) 5000 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5001 5002 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5003 if (FD->hasAttr<EnableIfAttr>()) { 5004 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5005 Diag(Fn->getLocStart(), 5006 isa<CXXMethodDecl>(FD) ? 5007 diag::err_ovl_no_viable_member_function_in_call : 5008 diag::err_ovl_no_viable_function_in_call) 5009 << FD << FD->getSourceRange(); 5010 Diag(FD->getLocation(), 5011 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5012 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5013 } 5014 } 5015 } 5016 5017 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5018 ExecConfig, IsExecConfig); 5019 } 5020 5021 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5022 /// 5023 /// __builtin_astype( value, dst type ) 5024 /// 5025 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5026 SourceLocation BuiltinLoc, 5027 SourceLocation RParenLoc) { 5028 ExprValueKind VK = VK_RValue; 5029 ExprObjectKind OK = OK_Ordinary; 5030 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5031 QualType SrcTy = E->getType(); 5032 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5033 return ExprError(Diag(BuiltinLoc, 5034 diag::err_invalid_astype_of_different_size) 5035 << DstTy 5036 << SrcTy 5037 << E->getSourceRange()); 5038 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5039 } 5040 5041 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5042 /// provided arguments. 5043 /// 5044 /// __builtin_convertvector( value, dst type ) 5045 /// 5046 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5047 SourceLocation BuiltinLoc, 5048 SourceLocation RParenLoc) { 5049 TypeSourceInfo *TInfo; 5050 GetTypeFromParser(ParsedDestTy, &TInfo); 5051 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5052 } 5053 5054 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5055 /// i.e. an expression not of \p OverloadTy. The expression should 5056 /// unary-convert to an expression of function-pointer or 5057 /// block-pointer type. 5058 /// 5059 /// \param NDecl the declaration being called, if available 5060 ExprResult 5061 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5062 SourceLocation LParenLoc, 5063 ArrayRef<Expr *> Args, 5064 SourceLocation RParenLoc, 5065 Expr *Config, bool IsExecConfig) { 5066 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5067 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5068 5069 // Promote the function operand. 5070 // We special-case function promotion here because we only allow promoting 5071 // builtin functions to function pointers in the callee of a call. 5072 ExprResult Result; 5073 if (BuiltinID && 5074 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5075 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5076 CK_BuiltinFnToFnPtr).get(); 5077 } else { 5078 Result = CallExprUnaryConversions(Fn); 5079 } 5080 if (Result.isInvalid()) 5081 return ExprError(); 5082 Fn = Result.get(); 5083 5084 // Make the call expr early, before semantic checks. This guarantees cleanup 5085 // of arguments and function on error. 5086 CallExpr *TheCall; 5087 if (Config) 5088 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5089 cast<CallExpr>(Config), Args, 5090 Context.BoolTy, VK_RValue, 5091 RParenLoc); 5092 else 5093 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5094 VK_RValue, RParenLoc); 5095 5096 if (!getLangOpts().CPlusPlus) { 5097 // C cannot always handle TypoExpr nodes in builtin calls and direct 5098 // function calls as their argument checking don't necessarily handle 5099 // dependent types properly, so make sure any TypoExprs have been 5100 // dealt with. 5101 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5102 if (!Result.isUsable()) return ExprError(); 5103 TheCall = dyn_cast<CallExpr>(Result.get()); 5104 if (!TheCall) return Result; 5105 Args = ArrayRef<Expr *>(TheCall->getArgs(), TheCall->getNumArgs()); 5106 } 5107 5108 // Bail out early if calling a builtin with custom typechecking. 5109 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5110 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5111 5112 retry: 5113 const FunctionType *FuncT; 5114 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5115 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5116 // have type pointer to function". 5117 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5118 if (!FuncT) 5119 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5120 << Fn->getType() << Fn->getSourceRange()); 5121 } else if (const BlockPointerType *BPT = 5122 Fn->getType()->getAs<BlockPointerType>()) { 5123 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5124 } else { 5125 // Handle calls to expressions of unknown-any type. 5126 if (Fn->getType() == Context.UnknownAnyTy) { 5127 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5128 if (rewrite.isInvalid()) return ExprError(); 5129 Fn = rewrite.get(); 5130 TheCall->setCallee(Fn); 5131 goto retry; 5132 } 5133 5134 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5135 << Fn->getType() << Fn->getSourceRange()); 5136 } 5137 5138 if (getLangOpts().CUDA) { 5139 if (Config) { 5140 // CUDA: Kernel calls must be to global functions 5141 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5142 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5143 << FDecl->getName() << Fn->getSourceRange()); 5144 5145 // CUDA: Kernel function must have 'void' return type 5146 if (!FuncT->getReturnType()->isVoidType()) 5147 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5148 << Fn->getType() << Fn->getSourceRange()); 5149 } else { 5150 // CUDA: Calls to global functions must be configured 5151 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5152 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5153 << FDecl->getName() << Fn->getSourceRange()); 5154 } 5155 } 5156 5157 // Check for a valid return type 5158 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5159 FDecl)) 5160 return ExprError(); 5161 5162 // We know the result type of the call, set it. 5163 TheCall->setType(FuncT->getCallResultType(Context)); 5164 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5165 5166 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5167 if (Proto) { 5168 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5169 IsExecConfig)) 5170 return ExprError(); 5171 } else { 5172 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5173 5174 if (FDecl) { 5175 // Check if we have too few/too many template arguments, based 5176 // on our knowledge of the function definition. 5177 const FunctionDecl *Def = nullptr; 5178 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5179 Proto = Def->getType()->getAs<FunctionProtoType>(); 5180 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5181 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5182 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5183 } 5184 5185 // If the function we're calling isn't a function prototype, but we have 5186 // a function prototype from a prior declaratiom, use that prototype. 5187 if (!FDecl->hasPrototype()) 5188 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5189 } 5190 5191 // Promote the arguments (C99 6.5.2.2p6). 5192 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5193 Expr *Arg = Args[i]; 5194 5195 if (Proto && i < Proto->getNumParams()) { 5196 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5197 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5198 ExprResult ArgE = 5199 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5200 if (ArgE.isInvalid()) 5201 return true; 5202 5203 Arg = ArgE.getAs<Expr>(); 5204 5205 } else { 5206 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5207 5208 if (ArgE.isInvalid()) 5209 return true; 5210 5211 Arg = ArgE.getAs<Expr>(); 5212 } 5213 5214 if (RequireCompleteType(Arg->getLocStart(), 5215 Arg->getType(), 5216 diag::err_call_incomplete_argument, Arg)) 5217 return ExprError(); 5218 5219 TheCall->setArg(i, Arg); 5220 } 5221 } 5222 5223 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5224 if (!Method->isStatic()) 5225 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5226 << Fn->getSourceRange()); 5227 5228 // Check for sentinels 5229 if (NDecl) 5230 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5231 5232 // Do special checking on direct calls to functions. 5233 if (FDecl) { 5234 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5235 return ExprError(); 5236 5237 if (BuiltinID) 5238 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5239 } else if (NDecl) { 5240 if (CheckPointerCall(NDecl, TheCall, Proto)) 5241 return ExprError(); 5242 } else { 5243 if (CheckOtherCall(TheCall, Proto)) 5244 return ExprError(); 5245 } 5246 5247 return MaybeBindToTemporary(TheCall); 5248 } 5249 5250 ExprResult 5251 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5252 SourceLocation RParenLoc, Expr *InitExpr) { 5253 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5254 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5255 5256 TypeSourceInfo *TInfo; 5257 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5258 if (!TInfo) 5259 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5260 5261 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5262 } 5263 5264 ExprResult 5265 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5266 SourceLocation RParenLoc, Expr *LiteralExpr) { 5267 QualType literalType = TInfo->getType(); 5268 5269 if (literalType->isArrayType()) { 5270 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5271 diag::err_illegal_decl_array_incomplete_type, 5272 SourceRange(LParenLoc, 5273 LiteralExpr->getSourceRange().getEnd()))) 5274 return ExprError(); 5275 if (literalType->isVariableArrayType()) 5276 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5277 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5278 } else if (!literalType->isDependentType() && 5279 RequireCompleteType(LParenLoc, literalType, 5280 diag::err_typecheck_decl_incomplete_type, 5281 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5282 return ExprError(); 5283 5284 InitializedEntity Entity 5285 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5286 InitializationKind Kind 5287 = InitializationKind::CreateCStyleCast(LParenLoc, 5288 SourceRange(LParenLoc, RParenLoc), 5289 /*InitList=*/true); 5290 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5291 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5292 &literalType); 5293 if (Result.isInvalid()) 5294 return ExprError(); 5295 LiteralExpr = Result.get(); 5296 5297 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5298 if (isFileScope && 5299 !LiteralExpr->isTypeDependent() && 5300 !LiteralExpr->isValueDependent() && 5301 !literalType->isDependentType()) { // 6.5.2.5p3 5302 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5303 return ExprError(); 5304 } 5305 5306 // In C, compound literals are l-values for some reason. 5307 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5308 5309 return MaybeBindToTemporary( 5310 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5311 VK, LiteralExpr, isFileScope)); 5312 } 5313 5314 ExprResult 5315 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5316 SourceLocation RBraceLoc) { 5317 // Immediately handle non-overload placeholders. Overloads can be 5318 // resolved contextually, but everything else here can't. 5319 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5320 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5321 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5322 5323 // Ignore failures; dropping the entire initializer list because 5324 // of one failure would be terrible for indexing/etc. 5325 if (result.isInvalid()) continue; 5326 5327 InitArgList[I] = result.get(); 5328 } 5329 } 5330 5331 // Semantic analysis for initializers is done by ActOnDeclarator() and 5332 // CheckInitializer() - it requires knowledge of the object being intialized. 5333 5334 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5335 RBraceLoc); 5336 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5337 return E; 5338 } 5339 5340 /// Do an explicit extend of the given block pointer if we're in ARC. 5341 void Sema::maybeExtendBlockObject(ExprResult &E) { 5342 assert(E.get()->getType()->isBlockPointerType()); 5343 assert(E.get()->isRValue()); 5344 5345 // Only do this in an r-value context. 5346 if (!getLangOpts().ObjCAutoRefCount) return; 5347 5348 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5349 CK_ARCExtendBlockObject, E.get(), 5350 /*base path*/ nullptr, VK_RValue); 5351 ExprNeedsCleanups = true; 5352 } 5353 5354 /// Prepare a conversion of the given expression to an ObjC object 5355 /// pointer type. 5356 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5357 QualType type = E.get()->getType(); 5358 if (type->isObjCObjectPointerType()) { 5359 return CK_BitCast; 5360 } else if (type->isBlockPointerType()) { 5361 maybeExtendBlockObject(E); 5362 return CK_BlockPointerToObjCPointerCast; 5363 } else { 5364 assert(type->isPointerType()); 5365 return CK_CPointerToObjCPointerCast; 5366 } 5367 } 5368 5369 /// Prepares for a scalar cast, performing all the necessary stages 5370 /// except the final cast and returning the kind required. 5371 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5372 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5373 // Also, callers should have filtered out the invalid cases with 5374 // pointers. Everything else should be possible. 5375 5376 QualType SrcTy = Src.get()->getType(); 5377 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5378 return CK_NoOp; 5379 5380 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5381 case Type::STK_MemberPointer: 5382 llvm_unreachable("member pointer type in C"); 5383 5384 case Type::STK_CPointer: 5385 case Type::STK_BlockPointer: 5386 case Type::STK_ObjCObjectPointer: 5387 switch (DestTy->getScalarTypeKind()) { 5388 case Type::STK_CPointer: { 5389 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5390 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5391 if (SrcAS != DestAS) 5392 return CK_AddressSpaceConversion; 5393 return CK_BitCast; 5394 } 5395 case Type::STK_BlockPointer: 5396 return (SrcKind == Type::STK_BlockPointer 5397 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5398 case Type::STK_ObjCObjectPointer: 5399 if (SrcKind == Type::STK_ObjCObjectPointer) 5400 return CK_BitCast; 5401 if (SrcKind == Type::STK_CPointer) 5402 return CK_CPointerToObjCPointerCast; 5403 maybeExtendBlockObject(Src); 5404 return CK_BlockPointerToObjCPointerCast; 5405 case Type::STK_Bool: 5406 return CK_PointerToBoolean; 5407 case Type::STK_Integral: 5408 return CK_PointerToIntegral; 5409 case Type::STK_Floating: 5410 case Type::STK_FloatingComplex: 5411 case Type::STK_IntegralComplex: 5412 case Type::STK_MemberPointer: 5413 llvm_unreachable("illegal cast from pointer"); 5414 } 5415 llvm_unreachable("Should have returned before this"); 5416 5417 case Type::STK_Bool: // casting from bool is like casting from an integer 5418 case Type::STK_Integral: 5419 switch (DestTy->getScalarTypeKind()) { 5420 case Type::STK_CPointer: 5421 case Type::STK_ObjCObjectPointer: 5422 case Type::STK_BlockPointer: 5423 if (Src.get()->isNullPointerConstant(Context, 5424 Expr::NPC_ValueDependentIsNull)) 5425 return CK_NullToPointer; 5426 return CK_IntegralToPointer; 5427 case Type::STK_Bool: 5428 return CK_IntegralToBoolean; 5429 case Type::STK_Integral: 5430 return CK_IntegralCast; 5431 case Type::STK_Floating: 5432 return CK_IntegralToFloating; 5433 case Type::STK_IntegralComplex: 5434 Src = ImpCastExprToType(Src.get(), 5435 DestTy->castAs<ComplexType>()->getElementType(), 5436 CK_IntegralCast); 5437 return CK_IntegralRealToComplex; 5438 case Type::STK_FloatingComplex: 5439 Src = ImpCastExprToType(Src.get(), 5440 DestTy->castAs<ComplexType>()->getElementType(), 5441 CK_IntegralToFloating); 5442 return CK_FloatingRealToComplex; 5443 case Type::STK_MemberPointer: 5444 llvm_unreachable("member pointer type in C"); 5445 } 5446 llvm_unreachable("Should have returned before this"); 5447 5448 case Type::STK_Floating: 5449 switch (DestTy->getScalarTypeKind()) { 5450 case Type::STK_Floating: 5451 return CK_FloatingCast; 5452 case Type::STK_Bool: 5453 return CK_FloatingToBoolean; 5454 case Type::STK_Integral: 5455 return CK_FloatingToIntegral; 5456 case Type::STK_FloatingComplex: 5457 Src = ImpCastExprToType(Src.get(), 5458 DestTy->castAs<ComplexType>()->getElementType(), 5459 CK_FloatingCast); 5460 return CK_FloatingRealToComplex; 5461 case Type::STK_IntegralComplex: 5462 Src = ImpCastExprToType(Src.get(), 5463 DestTy->castAs<ComplexType>()->getElementType(), 5464 CK_FloatingToIntegral); 5465 return CK_IntegralRealToComplex; 5466 case Type::STK_CPointer: 5467 case Type::STK_ObjCObjectPointer: 5468 case Type::STK_BlockPointer: 5469 llvm_unreachable("valid float->pointer cast?"); 5470 case Type::STK_MemberPointer: 5471 llvm_unreachable("member pointer type in C"); 5472 } 5473 llvm_unreachable("Should have returned before this"); 5474 5475 case Type::STK_FloatingComplex: 5476 switch (DestTy->getScalarTypeKind()) { 5477 case Type::STK_FloatingComplex: 5478 return CK_FloatingComplexCast; 5479 case Type::STK_IntegralComplex: 5480 return CK_FloatingComplexToIntegralComplex; 5481 case Type::STK_Floating: { 5482 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5483 if (Context.hasSameType(ET, DestTy)) 5484 return CK_FloatingComplexToReal; 5485 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5486 return CK_FloatingCast; 5487 } 5488 case Type::STK_Bool: 5489 return CK_FloatingComplexToBoolean; 5490 case Type::STK_Integral: 5491 Src = ImpCastExprToType(Src.get(), 5492 SrcTy->castAs<ComplexType>()->getElementType(), 5493 CK_FloatingComplexToReal); 5494 return CK_FloatingToIntegral; 5495 case Type::STK_CPointer: 5496 case Type::STK_ObjCObjectPointer: 5497 case Type::STK_BlockPointer: 5498 llvm_unreachable("valid complex float->pointer cast?"); 5499 case Type::STK_MemberPointer: 5500 llvm_unreachable("member pointer type in C"); 5501 } 5502 llvm_unreachable("Should have returned before this"); 5503 5504 case Type::STK_IntegralComplex: 5505 switch (DestTy->getScalarTypeKind()) { 5506 case Type::STK_FloatingComplex: 5507 return CK_IntegralComplexToFloatingComplex; 5508 case Type::STK_IntegralComplex: 5509 return CK_IntegralComplexCast; 5510 case Type::STK_Integral: { 5511 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5512 if (Context.hasSameType(ET, DestTy)) 5513 return CK_IntegralComplexToReal; 5514 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5515 return CK_IntegralCast; 5516 } 5517 case Type::STK_Bool: 5518 return CK_IntegralComplexToBoolean; 5519 case Type::STK_Floating: 5520 Src = ImpCastExprToType(Src.get(), 5521 SrcTy->castAs<ComplexType>()->getElementType(), 5522 CK_IntegralComplexToReal); 5523 return CK_IntegralToFloating; 5524 case Type::STK_CPointer: 5525 case Type::STK_ObjCObjectPointer: 5526 case Type::STK_BlockPointer: 5527 llvm_unreachable("valid complex int->pointer cast?"); 5528 case Type::STK_MemberPointer: 5529 llvm_unreachable("member pointer type in C"); 5530 } 5531 llvm_unreachable("Should have returned before this"); 5532 } 5533 5534 llvm_unreachable("Unhandled scalar cast"); 5535 } 5536 5537 static bool breakDownVectorType(QualType type, uint64_t &len, 5538 QualType &eltType) { 5539 // Vectors are simple. 5540 if (const VectorType *vecType = type->getAs<VectorType>()) { 5541 len = vecType->getNumElements(); 5542 eltType = vecType->getElementType(); 5543 assert(eltType->isScalarType()); 5544 return true; 5545 } 5546 5547 // We allow lax conversion to and from non-vector types, but only if 5548 // they're real types (i.e. non-complex, non-pointer scalar types). 5549 if (!type->isRealType()) return false; 5550 5551 len = 1; 5552 eltType = type; 5553 return true; 5554 } 5555 5556 /// Are the two types lax-compatible vector types? That is, given 5557 /// that one of them is a vector, do they have equal storage sizes, 5558 /// where the storage size is the number of elements times the element 5559 /// size? 5560 /// 5561 /// This will also return false if either of the types is neither a 5562 /// vector nor a real type. 5563 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5564 assert(destTy->isVectorType() || srcTy->isVectorType()); 5565 5566 // Disallow lax conversions between scalars and ExtVectors (these 5567 // conversions are allowed for other vector types because common headers 5568 // depend on them). Most scalar OP ExtVector cases are handled by the 5569 // splat path anyway, which does what we want (convert, not bitcast). 5570 // What this rules out for ExtVectors is crazy things like char4*float. 5571 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5572 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5573 5574 uint64_t srcLen, destLen; 5575 QualType srcElt, destElt; 5576 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 5577 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 5578 5579 // ASTContext::getTypeSize will return the size rounded up to a 5580 // power of 2, so instead of using that, we need to use the raw 5581 // element size multiplied by the element count. 5582 uint64_t srcEltSize = Context.getTypeSize(srcElt); 5583 uint64_t destEltSize = Context.getTypeSize(destElt); 5584 5585 return (srcLen * srcEltSize == destLen * destEltSize); 5586 } 5587 5588 /// Is this a legal conversion between two types, one of which is 5589 /// known to be a vector type? 5590 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5591 assert(destTy->isVectorType() || srcTy->isVectorType()); 5592 5593 if (!Context.getLangOpts().LaxVectorConversions) 5594 return false; 5595 return areLaxCompatibleVectorTypes(srcTy, destTy); 5596 } 5597 5598 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5599 CastKind &Kind) { 5600 assert(VectorTy->isVectorType() && "Not a vector type!"); 5601 5602 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5603 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5604 return Diag(R.getBegin(), 5605 Ty->isVectorType() ? 5606 diag::err_invalid_conversion_between_vectors : 5607 diag::err_invalid_conversion_between_vector_and_integer) 5608 << VectorTy << Ty << R; 5609 } else 5610 return Diag(R.getBegin(), 5611 diag::err_invalid_conversion_between_vector_and_scalar) 5612 << VectorTy << Ty << R; 5613 5614 Kind = CK_BitCast; 5615 return false; 5616 } 5617 5618 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5619 Expr *CastExpr, CastKind &Kind) { 5620 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5621 5622 QualType SrcTy = CastExpr->getType(); 5623 5624 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5625 // an ExtVectorType. 5626 // In OpenCL, casts between vectors of different types are not allowed. 5627 // (See OpenCL 6.2). 5628 if (SrcTy->isVectorType()) { 5629 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5630 || (getLangOpts().OpenCL && 5631 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5632 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5633 << DestTy << SrcTy << R; 5634 return ExprError(); 5635 } 5636 Kind = CK_BitCast; 5637 return CastExpr; 5638 } 5639 5640 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5641 // conversion will take place first from scalar to elt type, and then 5642 // splat from elt type to vector. 5643 if (SrcTy->isPointerType()) 5644 return Diag(R.getBegin(), 5645 diag::err_invalid_conversion_between_vector_and_scalar) 5646 << DestTy << SrcTy << R; 5647 5648 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5649 ExprResult CastExprRes = CastExpr; 5650 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5651 if (CastExprRes.isInvalid()) 5652 return ExprError(); 5653 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5654 5655 Kind = CK_VectorSplat; 5656 return CastExpr; 5657 } 5658 5659 ExprResult 5660 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5661 Declarator &D, ParsedType &Ty, 5662 SourceLocation RParenLoc, Expr *CastExpr) { 5663 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5664 "ActOnCastExpr(): missing type or expr"); 5665 5666 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5667 if (D.isInvalidType()) 5668 return ExprError(); 5669 5670 if (getLangOpts().CPlusPlus) { 5671 // Check that there are no default arguments (C++ only). 5672 CheckExtraCXXDefaultArguments(D); 5673 } else { 5674 // Make sure any TypoExprs have been dealt with. 5675 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5676 if (!Res.isUsable()) 5677 return ExprError(); 5678 CastExpr = Res.get(); 5679 } 5680 5681 checkUnusedDeclAttributes(D); 5682 5683 QualType castType = castTInfo->getType(); 5684 Ty = CreateParsedType(castType, castTInfo); 5685 5686 bool isVectorLiteral = false; 5687 5688 // Check for an altivec or OpenCL literal, 5689 // i.e. all the elements are integer constants. 5690 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5691 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5692 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5693 && castType->isVectorType() && (PE || PLE)) { 5694 if (PLE && PLE->getNumExprs() == 0) { 5695 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5696 return ExprError(); 5697 } 5698 if (PE || PLE->getNumExprs() == 1) { 5699 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5700 if (!E->getType()->isVectorType()) 5701 isVectorLiteral = true; 5702 } 5703 else 5704 isVectorLiteral = true; 5705 } 5706 5707 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5708 // then handle it as such. 5709 if (isVectorLiteral) 5710 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5711 5712 // If the Expr being casted is a ParenListExpr, handle it specially. 5713 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5714 // sequence of BinOp comma operators. 5715 if (isa<ParenListExpr>(CastExpr)) { 5716 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5717 if (Result.isInvalid()) return ExprError(); 5718 CastExpr = Result.get(); 5719 } 5720 5721 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5722 !getSourceManager().isInSystemMacro(LParenLoc)) 5723 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5724 5725 CheckTollFreeBridgeCast(castType, CastExpr); 5726 5727 CheckObjCBridgeRelatedCast(castType, CastExpr); 5728 5729 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5730 } 5731 5732 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5733 SourceLocation RParenLoc, Expr *E, 5734 TypeSourceInfo *TInfo) { 5735 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5736 "Expected paren or paren list expression"); 5737 5738 Expr **exprs; 5739 unsigned numExprs; 5740 Expr *subExpr; 5741 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5742 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5743 LiteralLParenLoc = PE->getLParenLoc(); 5744 LiteralRParenLoc = PE->getRParenLoc(); 5745 exprs = PE->getExprs(); 5746 numExprs = PE->getNumExprs(); 5747 } else { // isa<ParenExpr> by assertion at function entrance 5748 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5749 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5750 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5751 exprs = &subExpr; 5752 numExprs = 1; 5753 } 5754 5755 QualType Ty = TInfo->getType(); 5756 assert(Ty->isVectorType() && "Expected vector type"); 5757 5758 SmallVector<Expr *, 8> initExprs; 5759 const VectorType *VTy = Ty->getAs<VectorType>(); 5760 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5761 5762 // '(...)' form of vector initialization in AltiVec: the number of 5763 // initializers must be one or must match the size of the vector. 5764 // If a single value is specified in the initializer then it will be 5765 // replicated to all the components of the vector 5766 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5767 // The number of initializers must be one or must match the size of the 5768 // vector. If a single value is specified in the initializer then it will 5769 // be replicated to all the components of the vector 5770 if (numExprs == 1) { 5771 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5772 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5773 if (Literal.isInvalid()) 5774 return ExprError(); 5775 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5776 PrepareScalarCast(Literal, ElemTy)); 5777 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5778 } 5779 else if (numExprs < numElems) { 5780 Diag(E->getExprLoc(), 5781 diag::err_incorrect_number_of_vector_initializers); 5782 return ExprError(); 5783 } 5784 else 5785 initExprs.append(exprs, exprs + numExprs); 5786 } 5787 else { 5788 // For OpenCL, when the number of initializers is a single value, 5789 // it will be replicated to all components of the vector. 5790 if (getLangOpts().OpenCL && 5791 VTy->getVectorKind() == VectorType::GenericVector && 5792 numExprs == 1) { 5793 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5794 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5795 if (Literal.isInvalid()) 5796 return ExprError(); 5797 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5798 PrepareScalarCast(Literal, ElemTy)); 5799 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5800 } 5801 5802 initExprs.append(exprs, exprs + numExprs); 5803 } 5804 // FIXME: This means that pretty-printing the final AST will produce curly 5805 // braces instead of the original commas. 5806 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5807 initExprs, LiteralRParenLoc); 5808 initE->setType(Ty); 5809 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5810 } 5811 5812 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5813 /// the ParenListExpr into a sequence of comma binary operators. 5814 ExprResult 5815 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5816 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5817 if (!E) 5818 return OrigExpr; 5819 5820 ExprResult Result(E->getExpr(0)); 5821 5822 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5823 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5824 E->getExpr(i)); 5825 5826 if (Result.isInvalid()) return ExprError(); 5827 5828 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5829 } 5830 5831 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5832 SourceLocation R, 5833 MultiExprArg Val) { 5834 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5835 return expr; 5836 } 5837 5838 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5839 /// constant and the other is not a pointer. Returns true if a diagnostic is 5840 /// emitted. 5841 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5842 SourceLocation QuestionLoc) { 5843 Expr *NullExpr = LHSExpr; 5844 Expr *NonPointerExpr = RHSExpr; 5845 Expr::NullPointerConstantKind NullKind = 5846 NullExpr->isNullPointerConstant(Context, 5847 Expr::NPC_ValueDependentIsNotNull); 5848 5849 if (NullKind == Expr::NPCK_NotNull) { 5850 NullExpr = RHSExpr; 5851 NonPointerExpr = LHSExpr; 5852 NullKind = 5853 NullExpr->isNullPointerConstant(Context, 5854 Expr::NPC_ValueDependentIsNotNull); 5855 } 5856 5857 if (NullKind == Expr::NPCK_NotNull) 5858 return false; 5859 5860 if (NullKind == Expr::NPCK_ZeroExpression) 5861 return false; 5862 5863 if (NullKind == Expr::NPCK_ZeroLiteral) { 5864 // In this case, check to make sure that we got here from a "NULL" 5865 // string in the source code. 5866 NullExpr = NullExpr->IgnoreParenImpCasts(); 5867 SourceLocation loc = NullExpr->getExprLoc(); 5868 if (!findMacroSpelling(loc, "NULL")) 5869 return false; 5870 } 5871 5872 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5873 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5874 << NonPointerExpr->getType() << DiagType 5875 << NonPointerExpr->getSourceRange(); 5876 return true; 5877 } 5878 5879 /// \brief Return false if the condition expression is valid, true otherwise. 5880 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 5881 QualType CondTy = Cond->getType(); 5882 5883 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 5884 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 5885 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 5886 << CondTy << Cond->getSourceRange(); 5887 return true; 5888 } 5889 5890 // C99 6.5.15p2 5891 if (CondTy->isScalarType()) return false; 5892 5893 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 5894 << CondTy << Cond->getSourceRange(); 5895 return true; 5896 } 5897 5898 /// \brief Handle when one or both operands are void type. 5899 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5900 ExprResult &RHS) { 5901 Expr *LHSExpr = LHS.get(); 5902 Expr *RHSExpr = RHS.get(); 5903 5904 if (!LHSExpr->getType()->isVoidType()) 5905 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5906 << RHSExpr->getSourceRange(); 5907 if (!RHSExpr->getType()->isVoidType()) 5908 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5909 << LHSExpr->getSourceRange(); 5910 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5911 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5912 return S.Context.VoidTy; 5913 } 5914 5915 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5916 /// true otherwise. 5917 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5918 QualType PointerTy) { 5919 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5920 !NullExpr.get()->isNullPointerConstant(S.Context, 5921 Expr::NPC_ValueDependentIsNull)) 5922 return true; 5923 5924 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5925 return false; 5926 } 5927 5928 /// \brief Checks compatibility between two pointers and return the resulting 5929 /// type. 5930 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5931 ExprResult &RHS, 5932 SourceLocation Loc) { 5933 QualType LHSTy = LHS.get()->getType(); 5934 QualType RHSTy = RHS.get()->getType(); 5935 5936 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5937 // Two identical pointers types are always compatible. 5938 return LHSTy; 5939 } 5940 5941 QualType lhptee, rhptee; 5942 5943 // Get the pointee types. 5944 bool IsBlockPointer = false; 5945 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5946 lhptee = LHSBTy->getPointeeType(); 5947 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5948 IsBlockPointer = true; 5949 } else { 5950 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5951 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5952 } 5953 5954 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5955 // differently qualified versions of compatible types, the result type is 5956 // a pointer to an appropriately qualified version of the composite 5957 // type. 5958 5959 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5960 // clause doesn't make sense for our extensions. E.g. address space 2 should 5961 // be incompatible with address space 3: they may live on different devices or 5962 // anything. 5963 Qualifiers lhQual = lhptee.getQualifiers(); 5964 Qualifiers rhQual = rhptee.getQualifiers(); 5965 5966 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5967 lhQual.removeCVRQualifiers(); 5968 rhQual.removeCVRQualifiers(); 5969 5970 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5971 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5972 5973 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5974 5975 if (CompositeTy.isNull()) { 5976 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 5977 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5978 << RHS.get()->getSourceRange(); 5979 // In this situation, we assume void* type. No especially good 5980 // reason, but this is what gcc does, and we do have to pick 5981 // to get a consistent AST. 5982 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5983 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5984 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5985 return incompatTy; 5986 } 5987 5988 // The pointer types are compatible. 5989 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5990 if (IsBlockPointer) 5991 ResultTy = S.Context.getBlockPointerType(ResultTy); 5992 else 5993 ResultTy = S.Context.getPointerType(ResultTy); 5994 5995 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5996 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5997 return ResultTy; 5998 } 5999 6000 /// \brief Return the resulting type when the operands are both block pointers. 6001 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6002 ExprResult &LHS, 6003 ExprResult &RHS, 6004 SourceLocation Loc) { 6005 QualType LHSTy = LHS.get()->getType(); 6006 QualType RHSTy = RHS.get()->getType(); 6007 6008 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6009 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6010 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6011 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6012 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6013 return destType; 6014 } 6015 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6016 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6017 << RHS.get()->getSourceRange(); 6018 return QualType(); 6019 } 6020 6021 // We have 2 block pointer types. 6022 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6023 } 6024 6025 /// \brief Return the resulting type when the operands are both pointers. 6026 static QualType 6027 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6028 ExprResult &RHS, 6029 SourceLocation Loc) { 6030 // get the pointer types 6031 QualType LHSTy = LHS.get()->getType(); 6032 QualType RHSTy = RHS.get()->getType(); 6033 6034 // get the "pointed to" types 6035 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6036 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6037 6038 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6039 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6040 // Figure out necessary qualifiers (C99 6.5.15p6) 6041 QualType destPointee 6042 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6043 QualType destType = S.Context.getPointerType(destPointee); 6044 // Add qualifiers if necessary. 6045 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6046 // Promote to void*. 6047 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6048 return destType; 6049 } 6050 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6051 QualType destPointee 6052 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6053 QualType destType = S.Context.getPointerType(destPointee); 6054 // Add qualifiers if necessary. 6055 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6056 // Promote to void*. 6057 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6058 return destType; 6059 } 6060 6061 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6062 } 6063 6064 /// \brief Return false if the first expression is not an integer and the second 6065 /// expression is not a pointer, true otherwise. 6066 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6067 Expr* PointerExpr, SourceLocation Loc, 6068 bool IsIntFirstExpr) { 6069 if (!PointerExpr->getType()->isPointerType() || 6070 !Int.get()->getType()->isIntegerType()) 6071 return false; 6072 6073 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6074 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6075 6076 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6077 << Expr1->getType() << Expr2->getType() 6078 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6079 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6080 CK_IntegralToPointer); 6081 return true; 6082 } 6083 6084 /// \brief Simple conversion between integer and floating point types. 6085 /// 6086 /// Used when handling the OpenCL conditional operator where the 6087 /// condition is a vector while the other operands are scalar. 6088 /// 6089 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6090 /// types are either integer or floating type. Between the two 6091 /// operands, the type with the higher rank is defined as the "result 6092 /// type". The other operand needs to be promoted to the same type. No 6093 /// other type promotion is allowed. We cannot use 6094 /// UsualArithmeticConversions() for this purpose, since it always 6095 /// promotes promotable types. 6096 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6097 ExprResult &RHS, 6098 SourceLocation QuestionLoc) { 6099 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6100 if (LHS.isInvalid()) 6101 return QualType(); 6102 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6103 if (RHS.isInvalid()) 6104 return QualType(); 6105 6106 // For conversion purposes, we ignore any qualifiers. 6107 // For example, "const float" and "float" are equivalent. 6108 QualType LHSType = 6109 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6110 QualType RHSType = 6111 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6112 6113 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6114 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6115 << LHSType << LHS.get()->getSourceRange(); 6116 return QualType(); 6117 } 6118 6119 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6120 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6121 << RHSType << RHS.get()->getSourceRange(); 6122 return QualType(); 6123 } 6124 6125 // If both types are identical, no conversion is needed. 6126 if (LHSType == RHSType) 6127 return LHSType; 6128 6129 // Now handle "real" floating types (i.e. float, double, long double). 6130 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6131 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6132 /*IsCompAssign = */ false); 6133 6134 // Finally, we have two differing integer types. 6135 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6136 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6137 } 6138 6139 /// \brief Convert scalar operands to a vector that matches the 6140 /// condition in length. 6141 /// 6142 /// Used when handling the OpenCL conditional operator where the 6143 /// condition is a vector while the other operands are scalar. 6144 /// 6145 /// We first compute the "result type" for the scalar operands 6146 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6147 /// into a vector of that type where the length matches the condition 6148 /// vector type. s6.11.6 requires that the element types of the result 6149 /// and the condition must have the same number of bits. 6150 static QualType 6151 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6152 QualType CondTy, SourceLocation QuestionLoc) { 6153 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6154 if (ResTy.isNull()) return QualType(); 6155 6156 const VectorType *CV = CondTy->getAs<VectorType>(); 6157 assert(CV); 6158 6159 // Determine the vector result type 6160 unsigned NumElements = CV->getNumElements(); 6161 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6162 6163 // Ensure that all types have the same number of bits 6164 if (S.Context.getTypeSize(CV->getElementType()) 6165 != S.Context.getTypeSize(ResTy)) { 6166 // Since VectorTy is created internally, it does not pretty print 6167 // with an OpenCL name. Instead, we just print a description. 6168 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6169 SmallString<64> Str; 6170 llvm::raw_svector_ostream OS(Str); 6171 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6172 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6173 << CondTy << OS.str(); 6174 return QualType(); 6175 } 6176 6177 // Convert operands to the vector result type 6178 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6179 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6180 6181 return VectorTy; 6182 } 6183 6184 /// \brief Return false if this is a valid OpenCL condition vector 6185 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6186 SourceLocation QuestionLoc) { 6187 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6188 // integral type. 6189 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6190 assert(CondTy); 6191 QualType EleTy = CondTy->getElementType(); 6192 if (EleTy->isIntegerType()) return false; 6193 6194 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6195 << Cond->getType() << Cond->getSourceRange(); 6196 return true; 6197 } 6198 6199 /// \brief Return false if the vector condition type and the vector 6200 /// result type are compatible. 6201 /// 6202 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6203 /// number of elements, and their element types have the same number 6204 /// of bits. 6205 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6206 SourceLocation QuestionLoc) { 6207 const VectorType *CV = CondTy->getAs<VectorType>(); 6208 const VectorType *RV = VecResTy->getAs<VectorType>(); 6209 assert(CV && RV); 6210 6211 if (CV->getNumElements() != RV->getNumElements()) { 6212 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6213 << CondTy << VecResTy; 6214 return true; 6215 } 6216 6217 QualType CVE = CV->getElementType(); 6218 QualType RVE = RV->getElementType(); 6219 6220 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6221 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6222 << CondTy << VecResTy; 6223 return true; 6224 } 6225 6226 return false; 6227 } 6228 6229 /// \brief Return the resulting type for the conditional operator in 6230 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6231 /// s6.3.i) when the condition is a vector type. 6232 static QualType 6233 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6234 ExprResult &LHS, ExprResult &RHS, 6235 SourceLocation QuestionLoc) { 6236 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6237 if (Cond.isInvalid()) 6238 return QualType(); 6239 QualType CondTy = Cond.get()->getType(); 6240 6241 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6242 return QualType(); 6243 6244 // If either operand is a vector then find the vector type of the 6245 // result as specified in OpenCL v1.1 s6.3.i. 6246 if (LHS.get()->getType()->isVectorType() || 6247 RHS.get()->getType()->isVectorType()) { 6248 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6249 /*isCompAssign*/false, 6250 /*AllowBothBool*/true, 6251 /*AllowBoolConversions*/false); 6252 if (VecResTy.isNull()) return QualType(); 6253 // The result type must match the condition type as specified in 6254 // OpenCL v1.1 s6.11.6. 6255 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6256 return QualType(); 6257 return VecResTy; 6258 } 6259 6260 // Both operands are scalar. 6261 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6262 } 6263 6264 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6265 /// In that case, LHS = cond. 6266 /// C99 6.5.15 6267 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6268 ExprResult &RHS, ExprValueKind &VK, 6269 ExprObjectKind &OK, 6270 SourceLocation QuestionLoc) { 6271 6272 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6273 if (!LHSResult.isUsable()) return QualType(); 6274 LHS = LHSResult; 6275 6276 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6277 if (!RHSResult.isUsable()) return QualType(); 6278 RHS = RHSResult; 6279 6280 // C++ is sufficiently different to merit its own checker. 6281 if (getLangOpts().CPlusPlus) 6282 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6283 6284 VK = VK_RValue; 6285 OK = OK_Ordinary; 6286 6287 // The OpenCL operator with a vector condition is sufficiently 6288 // different to merit its own checker. 6289 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6290 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6291 6292 // First, check the condition. 6293 Cond = UsualUnaryConversions(Cond.get()); 6294 if (Cond.isInvalid()) 6295 return QualType(); 6296 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6297 return QualType(); 6298 6299 // Now check the two expressions. 6300 if (LHS.get()->getType()->isVectorType() || 6301 RHS.get()->getType()->isVectorType()) 6302 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6303 /*AllowBothBool*/true, 6304 /*AllowBoolConversions*/false); 6305 6306 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6307 if (LHS.isInvalid() || RHS.isInvalid()) 6308 return QualType(); 6309 6310 QualType LHSTy = LHS.get()->getType(); 6311 QualType RHSTy = RHS.get()->getType(); 6312 6313 // If both operands have arithmetic type, do the usual arithmetic conversions 6314 // to find a common type: C99 6.5.15p3,5. 6315 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6316 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6317 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6318 6319 return ResTy; 6320 } 6321 6322 // If both operands are the same structure or union type, the result is that 6323 // type. 6324 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6325 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6326 if (LHSRT->getDecl() == RHSRT->getDecl()) 6327 // "If both the operands have structure or union type, the result has 6328 // that type." This implies that CV qualifiers are dropped. 6329 return LHSTy.getUnqualifiedType(); 6330 // FIXME: Type of conditional expression must be complete in C mode. 6331 } 6332 6333 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6334 // The following || allows only one side to be void (a GCC-ism). 6335 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6336 return checkConditionalVoidType(*this, LHS, RHS); 6337 } 6338 6339 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6340 // the type of the other operand." 6341 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6342 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6343 6344 // All objective-c pointer type analysis is done here. 6345 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6346 QuestionLoc); 6347 if (LHS.isInvalid() || RHS.isInvalid()) 6348 return QualType(); 6349 if (!compositeType.isNull()) 6350 return compositeType; 6351 6352 6353 // Handle block pointer types. 6354 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6355 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6356 QuestionLoc); 6357 6358 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6359 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6360 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6361 QuestionLoc); 6362 6363 // GCC compatibility: soften pointer/integer mismatch. Note that 6364 // null pointers have been filtered out by this point. 6365 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6366 /*isIntFirstExpr=*/true)) 6367 return RHSTy; 6368 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6369 /*isIntFirstExpr=*/false)) 6370 return LHSTy; 6371 6372 // Emit a better diagnostic if one of the expressions is a null pointer 6373 // constant and the other is not a pointer type. In this case, the user most 6374 // likely forgot to take the address of the other expression. 6375 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6376 return QualType(); 6377 6378 // Otherwise, the operands are not compatible. 6379 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6380 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6381 << RHS.get()->getSourceRange(); 6382 return QualType(); 6383 } 6384 6385 /// FindCompositeObjCPointerType - Helper method to find composite type of 6386 /// two objective-c pointer types of the two input expressions. 6387 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6388 SourceLocation QuestionLoc) { 6389 QualType LHSTy = LHS.get()->getType(); 6390 QualType RHSTy = RHS.get()->getType(); 6391 6392 // Handle things like Class and struct objc_class*. Here we case the result 6393 // to the pseudo-builtin, because that will be implicitly cast back to the 6394 // redefinition type if an attempt is made to access its fields. 6395 if (LHSTy->isObjCClassType() && 6396 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6397 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6398 return LHSTy; 6399 } 6400 if (RHSTy->isObjCClassType() && 6401 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6402 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6403 return RHSTy; 6404 } 6405 // And the same for struct objc_object* / id 6406 if (LHSTy->isObjCIdType() && 6407 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6408 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6409 return LHSTy; 6410 } 6411 if (RHSTy->isObjCIdType() && 6412 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6413 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6414 return RHSTy; 6415 } 6416 // And the same for struct objc_selector* / SEL 6417 if (Context.isObjCSelType(LHSTy) && 6418 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6419 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6420 return LHSTy; 6421 } 6422 if (Context.isObjCSelType(RHSTy) && 6423 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6424 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6425 return RHSTy; 6426 } 6427 // Check constraints for Objective-C object pointers types. 6428 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6429 6430 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6431 // Two identical object pointer types are always compatible. 6432 return LHSTy; 6433 } 6434 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6435 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6436 QualType compositeType = LHSTy; 6437 6438 // If both operands are interfaces and either operand can be 6439 // assigned to the other, use that type as the composite 6440 // type. This allows 6441 // xxx ? (A*) a : (B*) b 6442 // where B is a subclass of A. 6443 // 6444 // Additionally, as for assignment, if either type is 'id' 6445 // allow silent coercion. Finally, if the types are 6446 // incompatible then make sure to use 'id' as the composite 6447 // type so the result is acceptable for sending messages to. 6448 6449 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6450 // It could return the composite type. 6451 if (!(compositeType = 6452 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6453 // Nothing more to do. 6454 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6455 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6456 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6457 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6458 } else if ((LHSTy->isObjCQualifiedIdType() || 6459 RHSTy->isObjCQualifiedIdType()) && 6460 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6461 // Need to handle "id<xx>" explicitly. 6462 // GCC allows qualified id and any Objective-C type to devolve to 6463 // id. Currently localizing to here until clear this should be 6464 // part of ObjCQualifiedIdTypesAreCompatible. 6465 compositeType = Context.getObjCIdType(); 6466 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6467 compositeType = Context.getObjCIdType(); 6468 } else { 6469 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6470 << LHSTy << RHSTy 6471 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6472 QualType incompatTy = Context.getObjCIdType(); 6473 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6474 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6475 return incompatTy; 6476 } 6477 // The object pointer types are compatible. 6478 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6479 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6480 return compositeType; 6481 } 6482 // Check Objective-C object pointer types and 'void *' 6483 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6484 if (getLangOpts().ObjCAutoRefCount) { 6485 // ARC forbids the implicit conversion of object pointers to 'void *', 6486 // so these types are not compatible. 6487 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6488 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6489 LHS = RHS = true; 6490 return QualType(); 6491 } 6492 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6493 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6494 QualType destPointee 6495 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6496 QualType destType = Context.getPointerType(destPointee); 6497 // Add qualifiers if necessary. 6498 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6499 // Promote to void*. 6500 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6501 return destType; 6502 } 6503 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6504 if (getLangOpts().ObjCAutoRefCount) { 6505 // ARC forbids the implicit conversion of object pointers to 'void *', 6506 // so these types are not compatible. 6507 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6508 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6509 LHS = RHS = true; 6510 return QualType(); 6511 } 6512 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6513 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6514 QualType destPointee 6515 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6516 QualType destType = Context.getPointerType(destPointee); 6517 // Add qualifiers if necessary. 6518 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6519 // Promote to void*. 6520 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6521 return destType; 6522 } 6523 return QualType(); 6524 } 6525 6526 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6527 /// ParenRange in parentheses. 6528 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6529 const PartialDiagnostic &Note, 6530 SourceRange ParenRange) { 6531 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 6532 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6533 EndLoc.isValid()) { 6534 Self.Diag(Loc, Note) 6535 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6536 << FixItHint::CreateInsertion(EndLoc, ")"); 6537 } else { 6538 // We can't display the parentheses, so just show the bare note. 6539 Self.Diag(Loc, Note) << ParenRange; 6540 } 6541 } 6542 6543 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6544 return Opc >= BO_Mul && Opc <= BO_Shr; 6545 } 6546 6547 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6548 /// expression, either using a built-in or overloaded operator, 6549 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6550 /// expression. 6551 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6552 Expr **RHSExprs) { 6553 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6554 E = E->IgnoreImpCasts(); 6555 E = E->IgnoreConversionOperator(); 6556 E = E->IgnoreImpCasts(); 6557 6558 // Built-in binary operator. 6559 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6560 if (IsArithmeticOp(OP->getOpcode())) { 6561 *Opcode = OP->getOpcode(); 6562 *RHSExprs = OP->getRHS(); 6563 return true; 6564 } 6565 } 6566 6567 // Overloaded operator. 6568 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6569 if (Call->getNumArgs() != 2) 6570 return false; 6571 6572 // Make sure this is really a binary operator that is safe to pass into 6573 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6574 OverloadedOperatorKind OO = Call->getOperator(); 6575 if (OO < OO_Plus || OO > OO_Arrow || 6576 OO == OO_PlusPlus || OO == OO_MinusMinus) 6577 return false; 6578 6579 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6580 if (IsArithmeticOp(OpKind)) { 6581 *Opcode = OpKind; 6582 *RHSExprs = Call->getArg(1); 6583 return true; 6584 } 6585 } 6586 6587 return false; 6588 } 6589 6590 static bool IsLogicOp(BinaryOperatorKind Opc) { 6591 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 6592 } 6593 6594 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6595 /// or is a logical expression such as (x==y) which has int type, but is 6596 /// commonly interpreted as boolean. 6597 static bool ExprLooksBoolean(Expr *E) { 6598 E = E->IgnoreParenImpCasts(); 6599 6600 if (E->getType()->isBooleanType()) 6601 return true; 6602 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6603 return IsLogicOp(OP->getOpcode()); 6604 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6605 return OP->getOpcode() == UO_LNot; 6606 if (E->getType()->isPointerType()) 6607 return true; 6608 6609 return false; 6610 } 6611 6612 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6613 /// and binary operator are mixed in a way that suggests the programmer assumed 6614 /// the conditional operator has higher precedence, for example: 6615 /// "int x = a + someBinaryCondition ? 1 : 2". 6616 static void DiagnoseConditionalPrecedence(Sema &Self, 6617 SourceLocation OpLoc, 6618 Expr *Condition, 6619 Expr *LHSExpr, 6620 Expr *RHSExpr) { 6621 BinaryOperatorKind CondOpcode; 6622 Expr *CondRHS; 6623 6624 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6625 return; 6626 if (!ExprLooksBoolean(CondRHS)) 6627 return; 6628 6629 // The condition is an arithmetic binary expression, with a right- 6630 // hand side that looks boolean, so warn. 6631 6632 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6633 << Condition->getSourceRange() 6634 << BinaryOperator::getOpcodeStr(CondOpcode); 6635 6636 SuggestParentheses(Self, OpLoc, 6637 Self.PDiag(diag::note_precedence_silence) 6638 << BinaryOperator::getOpcodeStr(CondOpcode), 6639 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6640 6641 SuggestParentheses(Self, OpLoc, 6642 Self.PDiag(diag::note_precedence_conditional_first), 6643 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6644 } 6645 6646 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6647 /// in the case of a the GNU conditional expr extension. 6648 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6649 SourceLocation ColonLoc, 6650 Expr *CondExpr, Expr *LHSExpr, 6651 Expr *RHSExpr) { 6652 if (!getLangOpts().CPlusPlus) { 6653 // C cannot handle TypoExpr nodes in the condition because it 6654 // doesn't handle dependent types properly, so make sure any TypoExprs have 6655 // been dealt with before checking the operands. 6656 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6657 if (!CondResult.isUsable()) return ExprError(); 6658 CondExpr = CondResult.get(); 6659 } 6660 6661 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6662 // was the condition. 6663 OpaqueValueExpr *opaqueValue = nullptr; 6664 Expr *commonExpr = nullptr; 6665 if (!LHSExpr) { 6666 commonExpr = CondExpr; 6667 // Lower out placeholder types first. This is important so that we don't 6668 // try to capture a placeholder. This happens in few cases in C++; such 6669 // as Objective-C++'s dictionary subscripting syntax. 6670 if (commonExpr->hasPlaceholderType()) { 6671 ExprResult result = CheckPlaceholderExpr(commonExpr); 6672 if (!result.isUsable()) return ExprError(); 6673 commonExpr = result.get(); 6674 } 6675 // We usually want to apply unary conversions *before* saving, except 6676 // in the special case of a C++ l-value conditional. 6677 if (!(getLangOpts().CPlusPlus 6678 && !commonExpr->isTypeDependent() 6679 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6680 && commonExpr->isGLValue() 6681 && commonExpr->isOrdinaryOrBitFieldObject() 6682 && RHSExpr->isOrdinaryOrBitFieldObject() 6683 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6684 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6685 if (commonRes.isInvalid()) 6686 return ExprError(); 6687 commonExpr = commonRes.get(); 6688 } 6689 6690 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6691 commonExpr->getType(), 6692 commonExpr->getValueKind(), 6693 commonExpr->getObjectKind(), 6694 commonExpr); 6695 LHSExpr = CondExpr = opaqueValue; 6696 } 6697 6698 ExprValueKind VK = VK_RValue; 6699 ExprObjectKind OK = OK_Ordinary; 6700 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6701 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6702 VK, OK, QuestionLoc); 6703 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6704 RHS.isInvalid()) 6705 return ExprError(); 6706 6707 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6708 RHS.get()); 6709 6710 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6711 6712 if (!commonExpr) 6713 return new (Context) 6714 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6715 RHS.get(), result, VK, OK); 6716 6717 return new (Context) BinaryConditionalOperator( 6718 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6719 ColonLoc, result, VK, OK); 6720 } 6721 6722 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6723 // being closely modeled after the C99 spec:-). The odd characteristic of this 6724 // routine is it effectively iqnores the qualifiers on the top level pointee. 6725 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6726 // FIXME: add a couple examples in this comment. 6727 static Sema::AssignConvertType 6728 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6729 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6730 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6731 6732 // get the "pointed to" type (ignoring qualifiers at the top level) 6733 const Type *lhptee, *rhptee; 6734 Qualifiers lhq, rhq; 6735 std::tie(lhptee, lhq) = 6736 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6737 std::tie(rhptee, rhq) = 6738 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6739 6740 Sema::AssignConvertType ConvTy = Sema::Compatible; 6741 6742 // C99 6.5.16.1p1: This following citation is common to constraints 6743 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6744 // qualifiers of the type *pointed to* by the right; 6745 6746 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6747 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6748 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6749 // Ignore lifetime for further calculation. 6750 lhq.removeObjCLifetime(); 6751 rhq.removeObjCLifetime(); 6752 } 6753 6754 if (!lhq.compatiblyIncludes(rhq)) { 6755 // Treat address-space mismatches as fatal. TODO: address subspaces 6756 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6757 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6758 6759 // It's okay to add or remove GC or lifetime qualifiers when converting to 6760 // and from void*. 6761 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6762 .compatiblyIncludes( 6763 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6764 && (lhptee->isVoidType() || rhptee->isVoidType())) 6765 ; // keep old 6766 6767 // Treat lifetime mismatches as fatal. 6768 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6769 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6770 6771 // For GCC compatibility, other qualifier mismatches are treated 6772 // as still compatible in C. 6773 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6774 } 6775 6776 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6777 // incomplete type and the other is a pointer to a qualified or unqualified 6778 // version of void... 6779 if (lhptee->isVoidType()) { 6780 if (rhptee->isIncompleteOrObjectType()) 6781 return ConvTy; 6782 6783 // As an extension, we allow cast to/from void* to function pointer. 6784 assert(rhptee->isFunctionType()); 6785 return Sema::FunctionVoidPointer; 6786 } 6787 6788 if (rhptee->isVoidType()) { 6789 if (lhptee->isIncompleteOrObjectType()) 6790 return ConvTy; 6791 6792 // As an extension, we allow cast to/from void* to function pointer. 6793 assert(lhptee->isFunctionType()); 6794 return Sema::FunctionVoidPointer; 6795 } 6796 6797 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6798 // unqualified versions of compatible types, ... 6799 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6800 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6801 // Check if the pointee types are compatible ignoring the sign. 6802 // We explicitly check for char so that we catch "char" vs 6803 // "unsigned char" on systems where "char" is unsigned. 6804 if (lhptee->isCharType()) 6805 ltrans = S.Context.UnsignedCharTy; 6806 else if (lhptee->hasSignedIntegerRepresentation()) 6807 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6808 6809 if (rhptee->isCharType()) 6810 rtrans = S.Context.UnsignedCharTy; 6811 else if (rhptee->hasSignedIntegerRepresentation()) 6812 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6813 6814 if (ltrans == rtrans) { 6815 // Types are compatible ignoring the sign. Qualifier incompatibility 6816 // takes priority over sign incompatibility because the sign 6817 // warning can be disabled. 6818 if (ConvTy != Sema::Compatible) 6819 return ConvTy; 6820 6821 return Sema::IncompatiblePointerSign; 6822 } 6823 6824 // If we are a multi-level pointer, it's possible that our issue is simply 6825 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6826 // the eventual target type is the same and the pointers have the same 6827 // level of indirection, this must be the issue. 6828 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6829 do { 6830 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6831 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6832 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6833 6834 if (lhptee == rhptee) 6835 return Sema::IncompatibleNestedPointerQualifiers; 6836 } 6837 6838 // General pointer incompatibility takes priority over qualifiers. 6839 return Sema::IncompatiblePointer; 6840 } 6841 if (!S.getLangOpts().CPlusPlus && 6842 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6843 return Sema::IncompatiblePointer; 6844 return ConvTy; 6845 } 6846 6847 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6848 /// block pointer types are compatible or whether a block and normal pointer 6849 /// are compatible. It is more restrict than comparing two function pointer 6850 // types. 6851 static Sema::AssignConvertType 6852 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6853 QualType RHSType) { 6854 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6855 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6856 6857 QualType lhptee, rhptee; 6858 6859 // get the "pointed to" type (ignoring qualifiers at the top level) 6860 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6861 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6862 6863 // In C++, the types have to match exactly. 6864 if (S.getLangOpts().CPlusPlus) 6865 return Sema::IncompatibleBlockPointer; 6866 6867 Sema::AssignConvertType ConvTy = Sema::Compatible; 6868 6869 // For blocks we enforce that qualifiers are identical. 6870 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6871 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6872 6873 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6874 return Sema::IncompatibleBlockPointer; 6875 6876 return ConvTy; 6877 } 6878 6879 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6880 /// for assignment compatibility. 6881 static Sema::AssignConvertType 6882 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6883 QualType RHSType) { 6884 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6885 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6886 6887 if (LHSType->isObjCBuiltinType()) { 6888 // Class is not compatible with ObjC object pointers. 6889 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6890 !RHSType->isObjCQualifiedClassType()) 6891 return Sema::IncompatiblePointer; 6892 return Sema::Compatible; 6893 } 6894 if (RHSType->isObjCBuiltinType()) { 6895 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6896 !LHSType->isObjCQualifiedClassType()) 6897 return Sema::IncompatiblePointer; 6898 return Sema::Compatible; 6899 } 6900 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6901 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6902 6903 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6904 // make an exception for id<P> 6905 !LHSType->isObjCQualifiedIdType()) 6906 return Sema::CompatiblePointerDiscardsQualifiers; 6907 6908 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6909 return Sema::Compatible; 6910 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6911 return Sema::IncompatibleObjCQualifiedId; 6912 return Sema::IncompatiblePointer; 6913 } 6914 6915 Sema::AssignConvertType 6916 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6917 QualType LHSType, QualType RHSType) { 6918 // Fake up an opaque expression. We don't actually care about what 6919 // cast operations are required, so if CheckAssignmentConstraints 6920 // adds casts to this they'll be wasted, but fortunately that doesn't 6921 // usually happen on valid code. 6922 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6923 ExprResult RHSPtr = &RHSExpr; 6924 CastKind K = CK_Invalid; 6925 6926 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6927 } 6928 6929 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6930 /// has code to accommodate several GCC extensions when type checking 6931 /// pointers. Here are some objectionable examples that GCC considers warnings: 6932 /// 6933 /// int a, *pint; 6934 /// short *pshort; 6935 /// struct foo *pfoo; 6936 /// 6937 /// pint = pshort; // warning: assignment from incompatible pointer type 6938 /// a = pint; // warning: assignment makes integer from pointer without a cast 6939 /// pint = a; // warning: assignment makes pointer from integer without a cast 6940 /// pint = pfoo; // warning: assignment from incompatible pointer type 6941 /// 6942 /// As a result, the code for dealing with pointers is more complex than the 6943 /// C99 spec dictates. 6944 /// 6945 /// Sets 'Kind' for any result kind except Incompatible. 6946 Sema::AssignConvertType 6947 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6948 CastKind &Kind) { 6949 QualType RHSType = RHS.get()->getType(); 6950 QualType OrigLHSType = LHSType; 6951 6952 // Get canonical types. We're not formatting these types, just comparing 6953 // them. 6954 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6955 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6956 6957 // Common case: no conversion required. 6958 if (LHSType == RHSType) { 6959 Kind = CK_NoOp; 6960 return Compatible; 6961 } 6962 6963 // If we have an atomic type, try a non-atomic assignment, then just add an 6964 // atomic qualification step. 6965 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6966 Sema::AssignConvertType result = 6967 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6968 if (result != Compatible) 6969 return result; 6970 if (Kind != CK_NoOp) 6971 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 6972 Kind = CK_NonAtomicToAtomic; 6973 return Compatible; 6974 } 6975 6976 // If the left-hand side is a reference type, then we are in a 6977 // (rare!) case where we've allowed the use of references in C, 6978 // e.g., as a parameter type in a built-in function. In this case, 6979 // just make sure that the type referenced is compatible with the 6980 // right-hand side type. The caller is responsible for adjusting 6981 // LHSType so that the resulting expression does not have reference 6982 // type. 6983 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6984 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6985 Kind = CK_LValueBitCast; 6986 return Compatible; 6987 } 6988 return Incompatible; 6989 } 6990 6991 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6992 // to the same ExtVector type. 6993 if (LHSType->isExtVectorType()) { 6994 if (RHSType->isExtVectorType()) 6995 return Incompatible; 6996 if (RHSType->isArithmeticType()) { 6997 // CK_VectorSplat does T -> vector T, so first cast to the 6998 // element type. 6999 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 7000 if (elType != RHSType) { 7001 Kind = PrepareScalarCast(RHS, elType); 7002 RHS = ImpCastExprToType(RHS.get(), elType, Kind); 7003 } 7004 Kind = CK_VectorSplat; 7005 return Compatible; 7006 } 7007 } 7008 7009 // Conversions to or from vector type. 7010 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7011 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7012 // Allow assignments of an AltiVec vector type to an equivalent GCC 7013 // vector type and vice versa 7014 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7015 Kind = CK_BitCast; 7016 return Compatible; 7017 } 7018 7019 // If we are allowing lax vector conversions, and LHS and RHS are both 7020 // vectors, the total size only needs to be the same. This is a bitcast; 7021 // no bits are changed but the result type is different. 7022 if (isLaxVectorConversion(RHSType, LHSType)) { 7023 Kind = CK_BitCast; 7024 return IncompatibleVectors; 7025 } 7026 } 7027 return Incompatible; 7028 } 7029 7030 // Arithmetic conversions. 7031 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7032 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7033 Kind = PrepareScalarCast(RHS, LHSType); 7034 return Compatible; 7035 } 7036 7037 // Conversions to normal pointers. 7038 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7039 // U* -> T* 7040 if (isa<PointerType>(RHSType)) { 7041 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7042 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7043 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7044 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7045 } 7046 7047 // int -> T* 7048 if (RHSType->isIntegerType()) { 7049 Kind = CK_IntegralToPointer; // FIXME: null? 7050 return IntToPointer; 7051 } 7052 7053 // C pointers are not compatible with ObjC object pointers, 7054 // with two exceptions: 7055 if (isa<ObjCObjectPointerType>(RHSType)) { 7056 // - conversions to void* 7057 if (LHSPointer->getPointeeType()->isVoidType()) { 7058 Kind = CK_BitCast; 7059 return Compatible; 7060 } 7061 7062 // - conversions from 'Class' to the redefinition type 7063 if (RHSType->isObjCClassType() && 7064 Context.hasSameType(LHSType, 7065 Context.getObjCClassRedefinitionType())) { 7066 Kind = CK_BitCast; 7067 return Compatible; 7068 } 7069 7070 Kind = CK_BitCast; 7071 return IncompatiblePointer; 7072 } 7073 7074 // U^ -> void* 7075 if (RHSType->getAs<BlockPointerType>()) { 7076 if (LHSPointer->getPointeeType()->isVoidType()) { 7077 Kind = CK_BitCast; 7078 return Compatible; 7079 } 7080 } 7081 7082 return Incompatible; 7083 } 7084 7085 // Conversions to block pointers. 7086 if (isa<BlockPointerType>(LHSType)) { 7087 // U^ -> T^ 7088 if (RHSType->isBlockPointerType()) { 7089 Kind = CK_BitCast; 7090 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7091 } 7092 7093 // int or null -> T^ 7094 if (RHSType->isIntegerType()) { 7095 Kind = CK_IntegralToPointer; // FIXME: null 7096 return IntToBlockPointer; 7097 } 7098 7099 // id -> T^ 7100 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7101 Kind = CK_AnyPointerToBlockPointerCast; 7102 return Compatible; 7103 } 7104 7105 // void* -> T^ 7106 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7107 if (RHSPT->getPointeeType()->isVoidType()) { 7108 Kind = CK_AnyPointerToBlockPointerCast; 7109 return Compatible; 7110 } 7111 7112 return Incompatible; 7113 } 7114 7115 // Conversions to Objective-C pointers. 7116 if (isa<ObjCObjectPointerType>(LHSType)) { 7117 // A* -> B* 7118 if (RHSType->isObjCObjectPointerType()) { 7119 Kind = CK_BitCast; 7120 Sema::AssignConvertType result = 7121 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7122 if (getLangOpts().ObjCAutoRefCount && 7123 result == Compatible && 7124 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7125 result = IncompatibleObjCWeakRef; 7126 return result; 7127 } 7128 7129 // int or null -> A* 7130 if (RHSType->isIntegerType()) { 7131 Kind = CK_IntegralToPointer; // FIXME: null 7132 return IntToPointer; 7133 } 7134 7135 // In general, C pointers are not compatible with ObjC object pointers, 7136 // with two exceptions: 7137 if (isa<PointerType>(RHSType)) { 7138 Kind = CK_CPointerToObjCPointerCast; 7139 7140 // - conversions from 'void*' 7141 if (RHSType->isVoidPointerType()) { 7142 return Compatible; 7143 } 7144 7145 // - conversions to 'Class' from its redefinition type 7146 if (LHSType->isObjCClassType() && 7147 Context.hasSameType(RHSType, 7148 Context.getObjCClassRedefinitionType())) { 7149 return Compatible; 7150 } 7151 7152 return IncompatiblePointer; 7153 } 7154 7155 // Only under strict condition T^ is compatible with an Objective-C pointer. 7156 if (RHSType->isBlockPointerType() && 7157 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7158 maybeExtendBlockObject(RHS); 7159 Kind = CK_BlockPointerToObjCPointerCast; 7160 return Compatible; 7161 } 7162 7163 return Incompatible; 7164 } 7165 7166 // Conversions from pointers that are not covered by the above. 7167 if (isa<PointerType>(RHSType)) { 7168 // T* -> _Bool 7169 if (LHSType == Context.BoolTy) { 7170 Kind = CK_PointerToBoolean; 7171 return Compatible; 7172 } 7173 7174 // T* -> int 7175 if (LHSType->isIntegerType()) { 7176 Kind = CK_PointerToIntegral; 7177 return PointerToInt; 7178 } 7179 7180 return Incompatible; 7181 } 7182 7183 // Conversions from Objective-C pointers that are not covered by the above. 7184 if (isa<ObjCObjectPointerType>(RHSType)) { 7185 // T* -> _Bool 7186 if (LHSType == Context.BoolTy) { 7187 Kind = CK_PointerToBoolean; 7188 return Compatible; 7189 } 7190 7191 // T* -> int 7192 if (LHSType->isIntegerType()) { 7193 Kind = CK_PointerToIntegral; 7194 return PointerToInt; 7195 } 7196 7197 return Incompatible; 7198 } 7199 7200 // struct A -> struct B 7201 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7202 if (Context.typesAreCompatible(LHSType, RHSType)) { 7203 Kind = CK_NoOp; 7204 return Compatible; 7205 } 7206 } 7207 7208 return Incompatible; 7209 } 7210 7211 /// \brief Constructs a transparent union from an expression that is 7212 /// used to initialize the transparent union. 7213 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7214 ExprResult &EResult, QualType UnionType, 7215 FieldDecl *Field) { 7216 // Build an initializer list that designates the appropriate member 7217 // of the transparent union. 7218 Expr *E = EResult.get(); 7219 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7220 E, SourceLocation()); 7221 Initializer->setType(UnionType); 7222 Initializer->setInitializedFieldInUnion(Field); 7223 7224 // Build a compound literal constructing a value of the transparent 7225 // union type from this initializer list. 7226 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7227 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7228 VK_RValue, Initializer, false); 7229 } 7230 7231 Sema::AssignConvertType 7232 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7233 ExprResult &RHS) { 7234 QualType RHSType = RHS.get()->getType(); 7235 7236 // If the ArgType is a Union type, we want to handle a potential 7237 // transparent_union GCC extension. 7238 const RecordType *UT = ArgType->getAsUnionType(); 7239 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7240 return Incompatible; 7241 7242 // The field to initialize within the transparent union. 7243 RecordDecl *UD = UT->getDecl(); 7244 FieldDecl *InitField = nullptr; 7245 // It's compatible if the expression matches any of the fields. 7246 for (auto *it : UD->fields()) { 7247 if (it->getType()->isPointerType()) { 7248 // If the transparent union contains a pointer type, we allow: 7249 // 1) void pointer 7250 // 2) null pointer constant 7251 if (RHSType->isPointerType()) 7252 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7253 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7254 InitField = it; 7255 break; 7256 } 7257 7258 if (RHS.get()->isNullPointerConstant(Context, 7259 Expr::NPC_ValueDependentIsNull)) { 7260 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7261 CK_NullToPointer); 7262 InitField = it; 7263 break; 7264 } 7265 } 7266 7267 CastKind Kind = CK_Invalid; 7268 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7269 == Compatible) { 7270 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7271 InitField = it; 7272 break; 7273 } 7274 } 7275 7276 if (!InitField) 7277 return Incompatible; 7278 7279 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7280 return Compatible; 7281 } 7282 7283 Sema::AssignConvertType 7284 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7285 bool Diagnose, 7286 bool DiagnoseCFAudited) { 7287 if (getLangOpts().CPlusPlus) { 7288 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7289 // C++ 5.17p3: If the left operand is not of class type, the 7290 // expression is implicitly converted (C++ 4) to the 7291 // cv-unqualified type of the left operand. 7292 ExprResult Res; 7293 if (Diagnose) { 7294 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7295 AA_Assigning); 7296 } else { 7297 ImplicitConversionSequence ICS = 7298 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7299 /*SuppressUserConversions=*/false, 7300 /*AllowExplicit=*/false, 7301 /*InOverloadResolution=*/false, 7302 /*CStyle=*/false, 7303 /*AllowObjCWritebackConversion=*/false); 7304 if (ICS.isFailure()) 7305 return Incompatible; 7306 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7307 ICS, AA_Assigning); 7308 } 7309 if (Res.isInvalid()) 7310 return Incompatible; 7311 Sema::AssignConvertType result = Compatible; 7312 if (getLangOpts().ObjCAutoRefCount && 7313 !CheckObjCARCUnavailableWeakConversion(LHSType, 7314 RHS.get()->getType())) 7315 result = IncompatibleObjCWeakRef; 7316 RHS = Res; 7317 return result; 7318 } 7319 7320 // FIXME: Currently, we fall through and treat C++ classes like C 7321 // structures. 7322 // FIXME: We also fall through for atomics; not sure what should 7323 // happen there, though. 7324 } 7325 7326 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7327 // a null pointer constant. 7328 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7329 LHSType->isBlockPointerType()) && 7330 RHS.get()->isNullPointerConstant(Context, 7331 Expr::NPC_ValueDependentIsNull)) { 7332 CastKind Kind; 7333 CXXCastPath Path; 7334 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 7335 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7336 return Compatible; 7337 } 7338 7339 // This check seems unnatural, however it is necessary to ensure the proper 7340 // conversion of functions/arrays. If the conversion were done for all 7341 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7342 // expressions that suppress this implicit conversion (&, sizeof). 7343 // 7344 // Suppress this for references: C++ 8.5.3p5. 7345 if (!LHSType->isReferenceType()) { 7346 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7347 if (RHS.isInvalid()) 7348 return Incompatible; 7349 } 7350 7351 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7352 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) { 7353 ObjCProtocolDecl *PDecl = OPE->getProtocol(); 7354 if (PDecl && !PDecl->hasDefinition()) { 7355 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7356 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7357 } 7358 } 7359 7360 CastKind Kind = CK_Invalid; 7361 Sema::AssignConvertType result = 7362 CheckAssignmentConstraints(LHSType, RHS, Kind); 7363 7364 // C99 6.5.16.1p2: The value of the right operand is converted to the 7365 // type of the assignment expression. 7366 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7367 // so that we can use references in built-in functions even in C. 7368 // The getNonReferenceType() call makes sure that the resulting expression 7369 // does not have reference type. 7370 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7371 QualType Ty = LHSType.getNonLValueExprType(Context); 7372 Expr *E = RHS.get(); 7373 if (getLangOpts().ObjCAutoRefCount) 7374 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7375 DiagnoseCFAudited); 7376 if (getLangOpts().ObjC1 && 7377 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 7378 LHSType, E->getType(), E) || 7379 ConversionToObjCStringLiteralCheck(LHSType, E))) { 7380 RHS = E; 7381 return Compatible; 7382 } 7383 7384 RHS = ImpCastExprToType(E, Ty, Kind); 7385 } 7386 return result; 7387 } 7388 7389 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7390 ExprResult &RHS) { 7391 Diag(Loc, diag::err_typecheck_invalid_operands) 7392 << LHS.get()->getType() << RHS.get()->getType() 7393 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7394 return QualType(); 7395 } 7396 7397 /// Try to convert a value of non-vector type to a vector type by converting 7398 /// the type to the element type of the vector and then performing a splat. 7399 /// If the language is OpenCL, we only use conversions that promote scalar 7400 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7401 /// for float->int. 7402 /// 7403 /// \param scalar - if non-null, actually perform the conversions 7404 /// \return true if the operation fails (but without diagnosing the failure) 7405 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7406 QualType scalarTy, 7407 QualType vectorEltTy, 7408 QualType vectorTy) { 7409 // The conversion to apply to the scalar before splatting it, 7410 // if necessary. 7411 CastKind scalarCast = CK_Invalid; 7412 7413 if (vectorEltTy->isIntegralType(S.Context)) { 7414 if (!scalarTy->isIntegralType(S.Context)) 7415 return true; 7416 if (S.getLangOpts().OpenCL && 7417 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7418 return true; 7419 scalarCast = CK_IntegralCast; 7420 } else if (vectorEltTy->isRealFloatingType()) { 7421 if (scalarTy->isRealFloatingType()) { 7422 if (S.getLangOpts().OpenCL && 7423 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7424 return true; 7425 scalarCast = CK_FloatingCast; 7426 } 7427 else if (scalarTy->isIntegralType(S.Context)) 7428 scalarCast = CK_IntegralToFloating; 7429 else 7430 return true; 7431 } else { 7432 return true; 7433 } 7434 7435 // Adjust scalar if desired. 7436 if (scalar) { 7437 if (scalarCast != CK_Invalid) 7438 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7439 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7440 } 7441 return false; 7442 } 7443 7444 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7445 SourceLocation Loc, bool IsCompAssign, 7446 bool AllowBothBool, 7447 bool AllowBoolConversions) { 7448 if (!IsCompAssign) { 7449 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7450 if (LHS.isInvalid()) 7451 return QualType(); 7452 } 7453 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7454 if (RHS.isInvalid()) 7455 return QualType(); 7456 7457 // For conversion purposes, we ignore any qualifiers. 7458 // For example, "const float" and "float" are equivalent. 7459 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7460 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7461 7462 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7463 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7464 assert(LHSVecType || RHSVecType); 7465 7466 // AltiVec-style "vector bool op vector bool" combinations are allowed 7467 // for some operators but not others. 7468 if (!AllowBothBool && 7469 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7470 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7471 return InvalidOperands(Loc, LHS, RHS); 7472 7473 // If the vector types are identical, return. 7474 if (Context.hasSameType(LHSType, RHSType)) 7475 return LHSType; 7476 7477 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7478 if (LHSVecType && RHSVecType && 7479 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7480 if (isa<ExtVectorType>(LHSVecType)) { 7481 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7482 return LHSType; 7483 } 7484 7485 if (!IsCompAssign) 7486 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7487 return RHSType; 7488 } 7489 7490 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7491 // can be mixed, with the result being the non-bool type. The non-bool 7492 // operand must have integer element type. 7493 if (AllowBoolConversions && LHSVecType && RHSVecType && 7494 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7495 (Context.getTypeSize(LHSVecType->getElementType()) == 7496 Context.getTypeSize(RHSVecType->getElementType()))) { 7497 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7498 LHSVecType->getElementType()->isIntegerType() && 7499 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7500 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7501 return LHSType; 7502 } 7503 if (!IsCompAssign && 7504 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7505 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7506 RHSVecType->getElementType()->isIntegerType()) { 7507 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7508 return RHSType; 7509 } 7510 } 7511 7512 // If there's an ext-vector type and a scalar, try to convert the scalar to 7513 // the vector element type and splat. 7514 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7515 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7516 LHSVecType->getElementType(), LHSType)) 7517 return LHSType; 7518 } 7519 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7520 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7521 LHSType, RHSVecType->getElementType(), 7522 RHSType)) 7523 return RHSType; 7524 } 7525 7526 // If we're allowing lax vector conversions, only the total (data) size 7527 // needs to be the same. 7528 // FIXME: Should we really be allowing this? 7529 // FIXME: We really just pick the LHS type arbitrarily? 7530 if (isLaxVectorConversion(RHSType, LHSType)) { 7531 QualType resultType = LHSType; 7532 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7533 return resultType; 7534 } 7535 7536 // Okay, the expression is invalid. 7537 7538 // If there's a non-vector, non-real operand, diagnose that. 7539 if ((!RHSVecType && !RHSType->isRealType()) || 7540 (!LHSVecType && !LHSType->isRealType())) { 7541 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7542 << LHSType << RHSType 7543 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7544 return QualType(); 7545 } 7546 7547 // OpenCL V1.1 6.2.6.p1: 7548 // If the operands are of more than one vector type, then an error shall 7549 // occur. Implicit conversions between vector types are not permitted, per 7550 // section 6.2.1. 7551 if (getLangOpts().OpenCL && 7552 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7553 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7554 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7555 << RHSType; 7556 return QualType(); 7557 } 7558 7559 // Otherwise, use the generic diagnostic. 7560 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7561 << LHSType << RHSType 7562 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7563 return QualType(); 7564 } 7565 7566 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7567 // expression. These are mainly cases where the null pointer is used as an 7568 // integer instead of a pointer. 7569 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7570 SourceLocation Loc, bool IsCompare) { 7571 // The canonical way to check for a GNU null is with isNullPointerConstant, 7572 // but we use a bit of a hack here for speed; this is a relatively 7573 // hot path, and isNullPointerConstant is slow. 7574 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7575 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7576 7577 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7578 7579 // Avoid analyzing cases where the result will either be invalid (and 7580 // diagnosed as such) or entirely valid and not something to warn about. 7581 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7582 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7583 return; 7584 7585 // Comparison operations would not make sense with a null pointer no matter 7586 // what the other expression is. 7587 if (!IsCompare) { 7588 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7589 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7590 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7591 return; 7592 } 7593 7594 // The rest of the operations only make sense with a null pointer 7595 // if the other expression is a pointer. 7596 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7597 NonNullType->canDecayToPointerType()) 7598 return; 7599 7600 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7601 << LHSNull /* LHS is NULL */ << NonNullType 7602 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7603 } 7604 7605 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7606 ExprResult &RHS, 7607 SourceLocation Loc, bool IsDiv) { 7608 // Check for division/remainder by zero. 7609 unsigned Diag = (IsDiv) ? diag::warn_division_by_zero : 7610 diag::warn_remainder_by_zero; 7611 llvm::APSInt RHSValue; 7612 if (!RHS.get()->isValueDependent() && 7613 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7614 S.DiagRuntimeBehavior(Loc, RHS.get(), 7615 S.PDiag(Diag) << RHS.get()->getSourceRange()); 7616 } 7617 7618 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7619 SourceLocation Loc, 7620 bool IsCompAssign, bool IsDiv) { 7621 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7622 7623 if (LHS.get()->getType()->isVectorType() || 7624 RHS.get()->getType()->isVectorType()) 7625 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7626 /*AllowBothBool*/getLangOpts().AltiVec, 7627 /*AllowBoolConversions*/false); 7628 7629 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7630 if (LHS.isInvalid() || RHS.isInvalid()) 7631 return QualType(); 7632 7633 7634 if (compType.isNull() || !compType->isArithmeticType()) 7635 return InvalidOperands(Loc, LHS, RHS); 7636 if (IsDiv) 7637 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7638 return compType; 7639 } 7640 7641 QualType Sema::CheckRemainderOperands( 7642 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7643 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7644 7645 if (LHS.get()->getType()->isVectorType() || 7646 RHS.get()->getType()->isVectorType()) { 7647 if (LHS.get()->getType()->hasIntegerRepresentation() && 7648 RHS.get()->getType()->hasIntegerRepresentation()) 7649 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7650 /*AllowBothBool*/getLangOpts().AltiVec, 7651 /*AllowBoolConversions*/false); 7652 return InvalidOperands(Loc, LHS, RHS); 7653 } 7654 7655 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7656 if (LHS.isInvalid() || RHS.isInvalid()) 7657 return QualType(); 7658 7659 if (compType.isNull() || !compType->isIntegerType()) 7660 return InvalidOperands(Loc, LHS, RHS); 7661 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 7662 return compType; 7663 } 7664 7665 /// \brief Diagnose invalid arithmetic on two void pointers. 7666 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7667 Expr *LHSExpr, Expr *RHSExpr) { 7668 S.Diag(Loc, S.getLangOpts().CPlusPlus 7669 ? diag::err_typecheck_pointer_arith_void_type 7670 : diag::ext_gnu_void_ptr) 7671 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7672 << RHSExpr->getSourceRange(); 7673 } 7674 7675 /// \brief Diagnose invalid arithmetic on a void pointer. 7676 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7677 Expr *Pointer) { 7678 S.Diag(Loc, S.getLangOpts().CPlusPlus 7679 ? diag::err_typecheck_pointer_arith_void_type 7680 : diag::ext_gnu_void_ptr) 7681 << 0 /* one pointer */ << Pointer->getSourceRange(); 7682 } 7683 7684 /// \brief Diagnose invalid arithmetic on two function pointers. 7685 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7686 Expr *LHS, Expr *RHS) { 7687 assert(LHS->getType()->isAnyPointerType()); 7688 assert(RHS->getType()->isAnyPointerType()); 7689 S.Diag(Loc, S.getLangOpts().CPlusPlus 7690 ? diag::err_typecheck_pointer_arith_function_type 7691 : diag::ext_gnu_ptr_func_arith) 7692 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7693 // We only show the second type if it differs from the first. 7694 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7695 RHS->getType()) 7696 << RHS->getType()->getPointeeType() 7697 << LHS->getSourceRange() << RHS->getSourceRange(); 7698 } 7699 7700 /// \brief Diagnose invalid arithmetic on a function pointer. 7701 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7702 Expr *Pointer) { 7703 assert(Pointer->getType()->isAnyPointerType()); 7704 S.Diag(Loc, S.getLangOpts().CPlusPlus 7705 ? diag::err_typecheck_pointer_arith_function_type 7706 : diag::ext_gnu_ptr_func_arith) 7707 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7708 << 0 /* one pointer, so only one type */ 7709 << Pointer->getSourceRange(); 7710 } 7711 7712 /// \brief Emit error if Operand is incomplete pointer type 7713 /// 7714 /// \returns True if pointer has incomplete type 7715 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7716 Expr *Operand) { 7717 QualType ResType = Operand->getType(); 7718 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7719 ResType = ResAtomicType->getValueType(); 7720 7721 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7722 QualType PointeeTy = ResType->getPointeeType(); 7723 return S.RequireCompleteType(Loc, PointeeTy, 7724 diag::err_typecheck_arithmetic_incomplete_type, 7725 PointeeTy, Operand->getSourceRange()); 7726 } 7727 7728 /// \brief Check the validity of an arithmetic pointer operand. 7729 /// 7730 /// If the operand has pointer type, this code will check for pointer types 7731 /// which are invalid in arithmetic operations. These will be diagnosed 7732 /// appropriately, including whether or not the use is supported as an 7733 /// extension. 7734 /// 7735 /// \returns True when the operand is valid to use (even if as an extension). 7736 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7737 Expr *Operand) { 7738 QualType ResType = Operand->getType(); 7739 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7740 ResType = ResAtomicType->getValueType(); 7741 7742 if (!ResType->isAnyPointerType()) return true; 7743 7744 QualType PointeeTy = ResType->getPointeeType(); 7745 if (PointeeTy->isVoidType()) { 7746 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7747 return !S.getLangOpts().CPlusPlus; 7748 } 7749 if (PointeeTy->isFunctionType()) { 7750 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7751 return !S.getLangOpts().CPlusPlus; 7752 } 7753 7754 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7755 7756 return true; 7757 } 7758 7759 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7760 /// operands. 7761 /// 7762 /// This routine will diagnose any invalid arithmetic on pointer operands much 7763 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7764 /// for emitting a single diagnostic even for operations where both LHS and RHS 7765 /// are (potentially problematic) pointers. 7766 /// 7767 /// \returns True when the operand is valid to use (even if as an extension). 7768 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7769 Expr *LHSExpr, Expr *RHSExpr) { 7770 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7771 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7772 if (!isLHSPointer && !isRHSPointer) return true; 7773 7774 QualType LHSPointeeTy, RHSPointeeTy; 7775 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7776 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7777 7778 // if both are pointers check if operation is valid wrt address spaces 7779 if (isLHSPointer && isRHSPointer) { 7780 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 7781 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 7782 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 7783 S.Diag(Loc, 7784 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7785 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 7786 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7787 return false; 7788 } 7789 } 7790 7791 // Check for arithmetic on pointers to incomplete types. 7792 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7793 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7794 if (isLHSVoidPtr || isRHSVoidPtr) { 7795 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7796 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7797 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7798 7799 return !S.getLangOpts().CPlusPlus; 7800 } 7801 7802 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7803 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7804 if (isLHSFuncPtr || isRHSFuncPtr) { 7805 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7806 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7807 RHSExpr); 7808 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7809 7810 return !S.getLangOpts().CPlusPlus; 7811 } 7812 7813 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7814 return false; 7815 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7816 return false; 7817 7818 return true; 7819 } 7820 7821 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7822 /// literal. 7823 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7824 Expr *LHSExpr, Expr *RHSExpr) { 7825 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7826 Expr* IndexExpr = RHSExpr; 7827 if (!StrExpr) { 7828 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7829 IndexExpr = LHSExpr; 7830 } 7831 7832 bool IsStringPlusInt = StrExpr && 7833 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7834 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 7835 return; 7836 7837 llvm::APSInt index; 7838 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7839 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7840 if (index.isNonNegative() && 7841 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7842 index.isUnsigned())) 7843 return; 7844 } 7845 7846 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7847 Self.Diag(OpLoc, diag::warn_string_plus_int) 7848 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7849 7850 // Only print a fixit for "str" + int, not for int + "str". 7851 if (IndexExpr == RHSExpr) { 7852 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7853 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7854 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7855 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7856 << FixItHint::CreateInsertion(EndLoc, "]"); 7857 } else 7858 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7859 } 7860 7861 /// \brief Emit a warning when adding a char literal to a string. 7862 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7863 Expr *LHSExpr, Expr *RHSExpr) { 7864 const Expr *StringRefExpr = LHSExpr; 7865 const CharacterLiteral *CharExpr = 7866 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7867 7868 if (!CharExpr) { 7869 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7870 StringRefExpr = RHSExpr; 7871 } 7872 7873 if (!CharExpr || !StringRefExpr) 7874 return; 7875 7876 const QualType StringType = StringRefExpr->getType(); 7877 7878 // Return if not a PointerType. 7879 if (!StringType->isAnyPointerType()) 7880 return; 7881 7882 // Return if not a CharacterType. 7883 if (!StringType->getPointeeType()->isAnyCharacterType()) 7884 return; 7885 7886 ASTContext &Ctx = Self.getASTContext(); 7887 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7888 7889 const QualType CharType = CharExpr->getType(); 7890 if (!CharType->isAnyCharacterType() && 7891 CharType->isIntegerType() && 7892 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7893 Self.Diag(OpLoc, diag::warn_string_plus_char) 7894 << DiagRange << Ctx.CharTy; 7895 } else { 7896 Self.Diag(OpLoc, diag::warn_string_plus_char) 7897 << DiagRange << CharExpr->getType(); 7898 } 7899 7900 // Only print a fixit for str + char, not for char + str. 7901 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7902 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7903 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7904 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7905 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7906 << FixItHint::CreateInsertion(EndLoc, "]"); 7907 } else { 7908 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7909 } 7910 } 7911 7912 /// \brief Emit error when two pointers are incompatible. 7913 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7914 Expr *LHSExpr, Expr *RHSExpr) { 7915 assert(LHSExpr->getType()->isAnyPointerType()); 7916 assert(RHSExpr->getType()->isAnyPointerType()); 7917 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7918 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7919 << RHSExpr->getSourceRange(); 7920 } 7921 7922 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7923 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7924 QualType* CompLHSTy) { 7925 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7926 7927 if (LHS.get()->getType()->isVectorType() || 7928 RHS.get()->getType()->isVectorType()) { 7929 QualType compType = CheckVectorOperands( 7930 LHS, RHS, Loc, CompLHSTy, 7931 /*AllowBothBool*/getLangOpts().AltiVec, 7932 /*AllowBoolConversions*/getLangOpts().ZVector); 7933 if (CompLHSTy) *CompLHSTy = compType; 7934 return compType; 7935 } 7936 7937 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7938 if (LHS.isInvalid() || RHS.isInvalid()) 7939 return QualType(); 7940 7941 // Diagnose "string literal" '+' int and string '+' "char literal". 7942 if (Opc == BO_Add) { 7943 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7944 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7945 } 7946 7947 // handle the common case first (both operands are arithmetic). 7948 if (!compType.isNull() && compType->isArithmeticType()) { 7949 if (CompLHSTy) *CompLHSTy = compType; 7950 return compType; 7951 } 7952 7953 // Type-checking. Ultimately the pointer's going to be in PExp; 7954 // note that we bias towards the LHS being the pointer. 7955 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7956 7957 bool isObjCPointer; 7958 if (PExp->getType()->isPointerType()) { 7959 isObjCPointer = false; 7960 } else if (PExp->getType()->isObjCObjectPointerType()) { 7961 isObjCPointer = true; 7962 } else { 7963 std::swap(PExp, IExp); 7964 if (PExp->getType()->isPointerType()) { 7965 isObjCPointer = false; 7966 } else if (PExp->getType()->isObjCObjectPointerType()) { 7967 isObjCPointer = true; 7968 } else { 7969 return InvalidOperands(Loc, LHS, RHS); 7970 } 7971 } 7972 assert(PExp->getType()->isAnyPointerType()); 7973 7974 if (!IExp->getType()->isIntegerType()) 7975 return InvalidOperands(Loc, LHS, RHS); 7976 7977 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7978 return QualType(); 7979 7980 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7981 return QualType(); 7982 7983 // Check array bounds for pointer arithemtic 7984 CheckArrayAccess(PExp, IExp); 7985 7986 if (CompLHSTy) { 7987 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7988 if (LHSTy.isNull()) { 7989 LHSTy = LHS.get()->getType(); 7990 if (LHSTy->isPromotableIntegerType()) 7991 LHSTy = Context.getPromotedIntegerType(LHSTy); 7992 } 7993 *CompLHSTy = LHSTy; 7994 } 7995 7996 return PExp->getType(); 7997 } 7998 7999 // C99 6.5.6 8000 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8001 SourceLocation Loc, 8002 QualType* CompLHSTy) { 8003 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8004 8005 if (LHS.get()->getType()->isVectorType() || 8006 RHS.get()->getType()->isVectorType()) { 8007 QualType compType = CheckVectorOperands( 8008 LHS, RHS, Loc, CompLHSTy, 8009 /*AllowBothBool*/getLangOpts().AltiVec, 8010 /*AllowBoolConversions*/getLangOpts().ZVector); 8011 if (CompLHSTy) *CompLHSTy = compType; 8012 return compType; 8013 } 8014 8015 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8016 if (LHS.isInvalid() || RHS.isInvalid()) 8017 return QualType(); 8018 8019 // Enforce type constraints: C99 6.5.6p3. 8020 8021 // Handle the common case first (both operands are arithmetic). 8022 if (!compType.isNull() && compType->isArithmeticType()) { 8023 if (CompLHSTy) *CompLHSTy = compType; 8024 return compType; 8025 } 8026 8027 // Either ptr - int or ptr - ptr. 8028 if (LHS.get()->getType()->isAnyPointerType()) { 8029 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8030 8031 // Diagnose bad cases where we step over interface counts. 8032 if (LHS.get()->getType()->isObjCObjectPointerType() && 8033 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8034 return QualType(); 8035 8036 // The result type of a pointer-int computation is the pointer type. 8037 if (RHS.get()->getType()->isIntegerType()) { 8038 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8039 return QualType(); 8040 8041 // Check array bounds for pointer arithemtic 8042 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8043 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8044 8045 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8046 return LHS.get()->getType(); 8047 } 8048 8049 // Handle pointer-pointer subtractions. 8050 if (const PointerType *RHSPTy 8051 = RHS.get()->getType()->getAs<PointerType>()) { 8052 QualType rpointee = RHSPTy->getPointeeType(); 8053 8054 if (getLangOpts().CPlusPlus) { 8055 // Pointee types must be the same: C++ [expr.add] 8056 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8057 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8058 } 8059 } else { 8060 // Pointee types must be compatible C99 6.5.6p3 8061 if (!Context.typesAreCompatible( 8062 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8063 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8064 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8065 return QualType(); 8066 } 8067 } 8068 8069 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8070 LHS.get(), RHS.get())) 8071 return QualType(); 8072 8073 // The pointee type may have zero size. As an extension, a structure or 8074 // union may have zero size or an array may have zero length. In this 8075 // case subtraction does not make sense. 8076 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8077 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8078 if (ElementSize.isZero()) { 8079 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8080 << rpointee.getUnqualifiedType() 8081 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8082 } 8083 } 8084 8085 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8086 return Context.getPointerDiffType(); 8087 } 8088 } 8089 8090 return InvalidOperands(Loc, LHS, RHS); 8091 } 8092 8093 static bool isScopedEnumerationType(QualType T) { 8094 if (const EnumType *ET = T->getAs<EnumType>()) 8095 return ET->getDecl()->isScoped(); 8096 return false; 8097 } 8098 8099 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8100 SourceLocation Loc, unsigned Opc, 8101 QualType LHSType) { 8102 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8103 // so skip remaining warnings as we don't want to modify values within Sema. 8104 if (S.getLangOpts().OpenCL) 8105 return; 8106 8107 llvm::APSInt Right; 8108 // Check right/shifter operand 8109 if (RHS.get()->isValueDependent() || 8110 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8111 return; 8112 8113 if (Right.isNegative()) { 8114 S.DiagRuntimeBehavior(Loc, RHS.get(), 8115 S.PDiag(diag::warn_shift_negative) 8116 << RHS.get()->getSourceRange()); 8117 return; 8118 } 8119 llvm::APInt LeftBits(Right.getBitWidth(), 8120 S.Context.getTypeSize(LHS.get()->getType())); 8121 if (Right.uge(LeftBits)) { 8122 S.DiagRuntimeBehavior(Loc, RHS.get(), 8123 S.PDiag(diag::warn_shift_gt_typewidth) 8124 << RHS.get()->getSourceRange()); 8125 return; 8126 } 8127 if (Opc != BO_Shl) 8128 return; 8129 8130 // When left shifting an ICE which is signed, we can check for overflow which 8131 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8132 // integers have defined behavior modulo one more than the maximum value 8133 // representable in the result type, so never warn for those. 8134 llvm::APSInt Left; 8135 if (LHS.get()->isValueDependent() || 8136 LHSType->hasUnsignedIntegerRepresentation() || 8137 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8138 return; 8139 8140 // If LHS does not have a signed type and non-negative value 8141 // then, the behavior is undefined. Warn about it. 8142 if (Left.isNegative()) { 8143 S.DiagRuntimeBehavior(Loc, LHS.get(), 8144 S.PDiag(diag::warn_shift_lhs_negative) 8145 << LHS.get()->getSourceRange()); 8146 return; 8147 } 8148 8149 llvm::APInt ResultBits = 8150 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8151 if (LeftBits.uge(ResultBits)) 8152 return; 8153 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8154 Result = Result.shl(Right); 8155 8156 // Print the bit representation of the signed integer as an unsigned 8157 // hexadecimal number. 8158 SmallString<40> HexResult; 8159 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8160 8161 // If we are only missing a sign bit, this is less likely to result in actual 8162 // bugs -- if the result is cast back to an unsigned type, it will have the 8163 // expected value. Thus we place this behind a different warning that can be 8164 // turned off separately if needed. 8165 if (LeftBits == ResultBits - 1) { 8166 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8167 << HexResult << LHSType 8168 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8169 return; 8170 } 8171 8172 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8173 << HexResult.str() << Result.getMinSignedBits() << LHSType 8174 << Left.getBitWidth() << LHS.get()->getSourceRange() 8175 << RHS.get()->getSourceRange(); 8176 } 8177 8178 /// \brief Return the resulting type when an OpenCL vector is shifted 8179 /// by a scalar or vector shift amount. 8180 static QualType checkOpenCLVectorShift(Sema &S, 8181 ExprResult &LHS, ExprResult &RHS, 8182 SourceLocation Loc, bool IsCompAssign) { 8183 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8184 if (!LHS.get()->getType()->isVectorType()) { 8185 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8186 << RHS.get()->getType() << LHS.get()->getType() 8187 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8188 return QualType(); 8189 } 8190 8191 if (!IsCompAssign) { 8192 LHS = S.UsualUnaryConversions(LHS.get()); 8193 if (LHS.isInvalid()) return QualType(); 8194 } 8195 8196 RHS = S.UsualUnaryConversions(RHS.get()); 8197 if (RHS.isInvalid()) return QualType(); 8198 8199 QualType LHSType = LHS.get()->getType(); 8200 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8201 QualType LHSEleType = LHSVecTy->getElementType(); 8202 8203 // Note that RHS might not be a vector. 8204 QualType RHSType = RHS.get()->getType(); 8205 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8206 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8207 8208 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8209 if (!LHSEleType->isIntegerType()) { 8210 S.Diag(Loc, diag::err_typecheck_expect_int) 8211 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8212 return QualType(); 8213 } 8214 8215 if (!RHSEleType->isIntegerType()) { 8216 S.Diag(Loc, diag::err_typecheck_expect_int) 8217 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8218 return QualType(); 8219 } 8220 8221 if (RHSVecTy) { 8222 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8223 // are applied component-wise. So if RHS is a vector, then ensure 8224 // that the number of elements is the same as LHS... 8225 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8226 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8227 << LHS.get()->getType() << RHS.get()->getType() 8228 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8229 return QualType(); 8230 } 8231 } else { 8232 // ...else expand RHS to match the number of elements in LHS. 8233 QualType VecTy = 8234 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8235 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8236 } 8237 8238 return LHSType; 8239 } 8240 8241 // C99 6.5.7 8242 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8243 SourceLocation Loc, unsigned Opc, 8244 bool IsCompAssign) { 8245 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8246 8247 // Vector shifts promote their scalar inputs to vector type. 8248 if (LHS.get()->getType()->isVectorType() || 8249 RHS.get()->getType()->isVectorType()) { 8250 if (LangOpts.OpenCL) 8251 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8252 if (LangOpts.ZVector) { 8253 // The shift operators for the z vector extensions work basically 8254 // like OpenCL shifts, except that neither the LHS nor the RHS is 8255 // allowed to be a "vector bool". 8256 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8257 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8258 return InvalidOperands(Loc, LHS, RHS); 8259 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8260 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8261 return InvalidOperands(Loc, LHS, RHS); 8262 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8263 } 8264 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8265 /*AllowBothBool*/true, 8266 /*AllowBoolConversions*/false); 8267 } 8268 8269 // Shifts don't perform usual arithmetic conversions, they just do integer 8270 // promotions on each operand. C99 6.5.7p3 8271 8272 // For the LHS, do usual unary conversions, but then reset them away 8273 // if this is a compound assignment. 8274 ExprResult OldLHS = LHS; 8275 LHS = UsualUnaryConversions(LHS.get()); 8276 if (LHS.isInvalid()) 8277 return QualType(); 8278 QualType LHSType = LHS.get()->getType(); 8279 if (IsCompAssign) LHS = OldLHS; 8280 8281 // The RHS is simpler. 8282 RHS = UsualUnaryConversions(RHS.get()); 8283 if (RHS.isInvalid()) 8284 return QualType(); 8285 QualType RHSType = RHS.get()->getType(); 8286 8287 // C99 6.5.7p2: Each of the operands shall have integer type. 8288 if (!LHSType->hasIntegerRepresentation() || 8289 !RHSType->hasIntegerRepresentation()) 8290 return InvalidOperands(Loc, LHS, RHS); 8291 8292 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8293 // hasIntegerRepresentation() above instead of this. 8294 if (isScopedEnumerationType(LHSType) || 8295 isScopedEnumerationType(RHSType)) { 8296 return InvalidOperands(Loc, LHS, RHS); 8297 } 8298 // Sanity-check shift operands 8299 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8300 8301 // "The type of the result is that of the promoted left operand." 8302 return LHSType; 8303 } 8304 8305 static bool IsWithinTemplateSpecialization(Decl *D) { 8306 if (DeclContext *DC = D->getDeclContext()) { 8307 if (isa<ClassTemplateSpecializationDecl>(DC)) 8308 return true; 8309 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8310 return FD->isFunctionTemplateSpecialization(); 8311 } 8312 return false; 8313 } 8314 8315 /// If two different enums are compared, raise a warning. 8316 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8317 Expr *RHS) { 8318 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8319 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8320 8321 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8322 if (!LHSEnumType) 8323 return; 8324 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8325 if (!RHSEnumType) 8326 return; 8327 8328 // Ignore anonymous enums. 8329 if (!LHSEnumType->getDecl()->getIdentifier()) 8330 return; 8331 if (!RHSEnumType->getDecl()->getIdentifier()) 8332 return; 8333 8334 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8335 return; 8336 8337 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8338 << LHSStrippedType << RHSStrippedType 8339 << LHS->getSourceRange() << RHS->getSourceRange(); 8340 } 8341 8342 /// \brief Diagnose bad pointer comparisons. 8343 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8344 ExprResult &LHS, ExprResult &RHS, 8345 bool IsError) { 8346 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8347 : diag::ext_typecheck_comparison_of_distinct_pointers) 8348 << LHS.get()->getType() << RHS.get()->getType() 8349 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8350 } 8351 8352 /// \brief Returns false if the pointers are converted to a composite type, 8353 /// true otherwise. 8354 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8355 ExprResult &LHS, ExprResult &RHS) { 8356 // C++ [expr.rel]p2: 8357 // [...] Pointer conversions (4.10) and qualification 8358 // conversions (4.4) are performed on pointer operands (or on 8359 // a pointer operand and a null pointer constant) to bring 8360 // them to their composite pointer type. [...] 8361 // 8362 // C++ [expr.eq]p1 uses the same notion for (in)equality 8363 // comparisons of pointers. 8364 8365 // C++ [expr.eq]p2: 8366 // In addition, pointers to members can be compared, or a pointer to 8367 // member and a null pointer constant. Pointer to member conversions 8368 // (4.11) and qualification conversions (4.4) are performed to bring 8369 // them to a common type. If one operand is a null pointer constant, 8370 // the common type is the type of the other operand. Otherwise, the 8371 // common type is a pointer to member type similar (4.4) to the type 8372 // of one of the operands, with a cv-qualification signature (4.4) 8373 // that is the union of the cv-qualification signatures of the operand 8374 // types. 8375 8376 QualType LHSType = LHS.get()->getType(); 8377 QualType RHSType = RHS.get()->getType(); 8378 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8379 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8380 8381 bool NonStandardCompositeType = false; 8382 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8383 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8384 if (T.isNull()) { 8385 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8386 return true; 8387 } 8388 8389 if (NonStandardCompositeType) 8390 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8391 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8392 << RHS.get()->getSourceRange(); 8393 8394 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8395 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8396 return false; 8397 } 8398 8399 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8400 ExprResult &LHS, 8401 ExprResult &RHS, 8402 bool IsError) { 8403 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8404 : diag::ext_typecheck_comparison_of_fptr_to_void) 8405 << LHS.get()->getType() << RHS.get()->getType() 8406 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8407 } 8408 8409 static bool isObjCObjectLiteral(ExprResult &E) { 8410 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8411 case Stmt::ObjCArrayLiteralClass: 8412 case Stmt::ObjCDictionaryLiteralClass: 8413 case Stmt::ObjCStringLiteralClass: 8414 case Stmt::ObjCBoxedExprClass: 8415 return true; 8416 default: 8417 // Note that ObjCBoolLiteral is NOT an object literal! 8418 return false; 8419 } 8420 } 8421 8422 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8423 const ObjCObjectPointerType *Type = 8424 LHS->getType()->getAs<ObjCObjectPointerType>(); 8425 8426 // If this is not actually an Objective-C object, bail out. 8427 if (!Type) 8428 return false; 8429 8430 // Get the LHS object's interface type. 8431 QualType InterfaceType = Type->getPointeeType(); 8432 8433 // If the RHS isn't an Objective-C object, bail out. 8434 if (!RHS->getType()->isObjCObjectPointerType()) 8435 return false; 8436 8437 // Try to find the -isEqual: method. 8438 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8439 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8440 InterfaceType, 8441 /*instance=*/true); 8442 if (!Method) { 8443 if (Type->isObjCIdType()) { 8444 // For 'id', just check the global pool. 8445 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8446 /*receiverId=*/true); 8447 } else { 8448 // Check protocols. 8449 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8450 /*instance=*/true); 8451 } 8452 } 8453 8454 if (!Method) 8455 return false; 8456 8457 QualType T = Method->parameters()[0]->getType(); 8458 if (!T->isObjCObjectPointerType()) 8459 return false; 8460 8461 QualType R = Method->getReturnType(); 8462 if (!R->isScalarType()) 8463 return false; 8464 8465 return true; 8466 } 8467 8468 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8469 FromE = FromE->IgnoreParenImpCasts(); 8470 switch (FromE->getStmtClass()) { 8471 default: 8472 break; 8473 case Stmt::ObjCStringLiteralClass: 8474 // "string literal" 8475 return LK_String; 8476 case Stmt::ObjCArrayLiteralClass: 8477 // "array literal" 8478 return LK_Array; 8479 case Stmt::ObjCDictionaryLiteralClass: 8480 // "dictionary literal" 8481 return LK_Dictionary; 8482 case Stmt::BlockExprClass: 8483 return LK_Block; 8484 case Stmt::ObjCBoxedExprClass: { 8485 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8486 switch (Inner->getStmtClass()) { 8487 case Stmt::IntegerLiteralClass: 8488 case Stmt::FloatingLiteralClass: 8489 case Stmt::CharacterLiteralClass: 8490 case Stmt::ObjCBoolLiteralExprClass: 8491 case Stmt::CXXBoolLiteralExprClass: 8492 // "numeric literal" 8493 return LK_Numeric; 8494 case Stmt::ImplicitCastExprClass: { 8495 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8496 // Boolean literals can be represented by implicit casts. 8497 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8498 return LK_Numeric; 8499 break; 8500 } 8501 default: 8502 break; 8503 } 8504 return LK_Boxed; 8505 } 8506 } 8507 return LK_None; 8508 } 8509 8510 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8511 ExprResult &LHS, ExprResult &RHS, 8512 BinaryOperator::Opcode Opc){ 8513 Expr *Literal; 8514 Expr *Other; 8515 if (isObjCObjectLiteral(LHS)) { 8516 Literal = LHS.get(); 8517 Other = RHS.get(); 8518 } else { 8519 Literal = RHS.get(); 8520 Other = LHS.get(); 8521 } 8522 8523 // Don't warn on comparisons against nil. 8524 Other = Other->IgnoreParenCasts(); 8525 if (Other->isNullPointerConstant(S.getASTContext(), 8526 Expr::NPC_ValueDependentIsNotNull)) 8527 return; 8528 8529 // This should be kept in sync with warn_objc_literal_comparison. 8530 // LK_String should always be after the other literals, since it has its own 8531 // warning flag. 8532 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8533 assert(LiteralKind != Sema::LK_Block); 8534 if (LiteralKind == Sema::LK_None) { 8535 llvm_unreachable("Unknown Objective-C object literal kind"); 8536 } 8537 8538 if (LiteralKind == Sema::LK_String) 8539 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8540 << Literal->getSourceRange(); 8541 else 8542 S.Diag(Loc, diag::warn_objc_literal_comparison) 8543 << LiteralKind << Literal->getSourceRange(); 8544 8545 if (BinaryOperator::isEqualityOp(Opc) && 8546 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8547 SourceLocation Start = LHS.get()->getLocStart(); 8548 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 8549 CharSourceRange OpRange = 8550 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 8551 8552 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8553 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8554 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8555 << FixItHint::CreateInsertion(End, "]"); 8556 } 8557 } 8558 8559 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8560 ExprResult &RHS, 8561 SourceLocation Loc, 8562 unsigned OpaqueOpc) { 8563 // Check that left hand side is !something. 8564 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8565 if (!UO || UO->getOpcode() != UO_LNot) return; 8566 8567 // Only check if the right hand side is non-bool arithmetic type. 8568 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8569 8570 // Make sure that the something in !something is not bool. 8571 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8572 if (SubExpr->isKnownToHaveBooleanValue()) return; 8573 8574 // Emit warning. 8575 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8576 << Loc; 8577 8578 // First note suggest !(x < y) 8579 SourceLocation FirstOpen = SubExpr->getLocStart(); 8580 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8581 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 8582 if (FirstClose.isInvalid()) 8583 FirstOpen = SourceLocation(); 8584 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8585 << FixItHint::CreateInsertion(FirstOpen, "(") 8586 << FixItHint::CreateInsertion(FirstClose, ")"); 8587 8588 // Second note suggests (!x) < y 8589 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8590 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8591 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 8592 if (SecondClose.isInvalid()) 8593 SecondOpen = SourceLocation(); 8594 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8595 << FixItHint::CreateInsertion(SecondOpen, "(") 8596 << FixItHint::CreateInsertion(SecondClose, ")"); 8597 } 8598 8599 // Get the decl for a simple expression: a reference to a variable, 8600 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8601 static ValueDecl *getCompareDecl(Expr *E) { 8602 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8603 return DR->getDecl(); 8604 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8605 if (Ivar->isFreeIvar()) 8606 return Ivar->getDecl(); 8607 } 8608 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8609 if (Mem->isImplicitAccess()) 8610 return Mem->getMemberDecl(); 8611 } 8612 return nullptr; 8613 } 8614 8615 // C99 6.5.8, C++ [expr.rel] 8616 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8617 SourceLocation Loc, unsigned OpaqueOpc, 8618 bool IsRelational) { 8619 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8620 8621 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 8622 8623 // Handle vector comparisons separately. 8624 if (LHS.get()->getType()->isVectorType() || 8625 RHS.get()->getType()->isVectorType()) 8626 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8627 8628 QualType LHSType = LHS.get()->getType(); 8629 QualType RHSType = RHS.get()->getType(); 8630 8631 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8632 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8633 8634 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8635 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 8636 8637 if (!LHSType->hasFloatingRepresentation() && 8638 !(LHSType->isBlockPointerType() && IsRelational) && 8639 !LHS.get()->getLocStart().isMacroID() && 8640 !RHS.get()->getLocStart().isMacroID() && 8641 ActiveTemplateInstantiations.empty()) { 8642 // For non-floating point types, check for self-comparisons of the form 8643 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8644 // often indicate logic errors in the program. 8645 // 8646 // NOTE: Don't warn about comparison expressions resulting from macro 8647 // expansion. Also don't warn about comparisons which are only self 8648 // comparisons within a template specialization. The warnings should catch 8649 // obvious cases in the definition of the template anyways. The idea is to 8650 // warn when the typed comparison operator will always evaluate to the same 8651 // result. 8652 ValueDecl *DL = getCompareDecl(LHSStripped); 8653 ValueDecl *DR = getCompareDecl(RHSStripped); 8654 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8655 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8656 << 0 // self- 8657 << (Opc == BO_EQ 8658 || Opc == BO_LE 8659 || Opc == BO_GE)); 8660 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8661 !DL->getType()->isReferenceType() && 8662 !DR->getType()->isReferenceType()) { 8663 // what is it always going to eval to? 8664 char always_evals_to; 8665 switch(Opc) { 8666 case BO_EQ: // e.g. array1 == array2 8667 always_evals_to = 0; // false 8668 break; 8669 case BO_NE: // e.g. array1 != array2 8670 always_evals_to = 1; // true 8671 break; 8672 default: 8673 // best we can say is 'a constant' 8674 always_evals_to = 2; // e.g. array1 <= array2 8675 break; 8676 } 8677 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8678 << 1 // array 8679 << always_evals_to); 8680 } 8681 8682 if (isa<CastExpr>(LHSStripped)) 8683 LHSStripped = LHSStripped->IgnoreParenCasts(); 8684 if (isa<CastExpr>(RHSStripped)) 8685 RHSStripped = RHSStripped->IgnoreParenCasts(); 8686 8687 // Warn about comparisons against a string constant (unless the other 8688 // operand is null), the user probably wants strcmp. 8689 Expr *literalString = nullptr; 8690 Expr *literalStringStripped = nullptr; 8691 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8692 !RHSStripped->isNullPointerConstant(Context, 8693 Expr::NPC_ValueDependentIsNull)) { 8694 literalString = LHS.get(); 8695 literalStringStripped = LHSStripped; 8696 } else if ((isa<StringLiteral>(RHSStripped) || 8697 isa<ObjCEncodeExpr>(RHSStripped)) && 8698 !LHSStripped->isNullPointerConstant(Context, 8699 Expr::NPC_ValueDependentIsNull)) { 8700 literalString = RHS.get(); 8701 literalStringStripped = RHSStripped; 8702 } 8703 8704 if (literalString) { 8705 DiagRuntimeBehavior(Loc, nullptr, 8706 PDiag(diag::warn_stringcompare) 8707 << isa<ObjCEncodeExpr>(literalStringStripped) 8708 << literalString->getSourceRange()); 8709 } 8710 } 8711 8712 // C99 6.5.8p3 / C99 6.5.9p4 8713 UsualArithmeticConversions(LHS, RHS); 8714 if (LHS.isInvalid() || RHS.isInvalid()) 8715 return QualType(); 8716 8717 LHSType = LHS.get()->getType(); 8718 RHSType = RHS.get()->getType(); 8719 8720 // The result of comparisons is 'bool' in C++, 'int' in C. 8721 QualType ResultTy = Context.getLogicalOperationType(); 8722 8723 if (IsRelational) { 8724 if (LHSType->isRealType() && RHSType->isRealType()) 8725 return ResultTy; 8726 } else { 8727 // Check for comparisons of floating point operands using != and ==. 8728 if (LHSType->hasFloatingRepresentation()) 8729 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8730 8731 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8732 return ResultTy; 8733 } 8734 8735 const Expr::NullPointerConstantKind LHSNullKind = 8736 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8737 const Expr::NullPointerConstantKind RHSNullKind = 8738 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8739 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8740 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8741 8742 if (!IsRelational && LHSIsNull != RHSIsNull) { 8743 bool IsEquality = Opc == BO_EQ; 8744 if (RHSIsNull) 8745 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 8746 RHS.get()->getSourceRange()); 8747 else 8748 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 8749 LHS.get()->getSourceRange()); 8750 } 8751 8752 // All of the following pointer-related warnings are GCC extensions, except 8753 // when handling null pointer constants. 8754 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 8755 QualType LCanPointeeTy = 8756 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8757 QualType RCanPointeeTy = 8758 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8759 8760 if (getLangOpts().CPlusPlus) { 8761 if (LCanPointeeTy == RCanPointeeTy) 8762 return ResultTy; 8763 if (!IsRelational && 8764 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8765 // Valid unless comparison between non-null pointer and function pointer 8766 // This is a gcc extension compatibility comparison. 8767 // In a SFINAE context, we treat this as a hard error to maintain 8768 // conformance with the C++ standard. 8769 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8770 && !LHSIsNull && !RHSIsNull) { 8771 diagnoseFunctionPointerToVoidComparison( 8772 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8773 8774 if (isSFINAEContext()) 8775 return QualType(); 8776 8777 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8778 return ResultTy; 8779 } 8780 } 8781 8782 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8783 return QualType(); 8784 else 8785 return ResultTy; 8786 } 8787 // C99 6.5.9p2 and C99 6.5.8p2 8788 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8789 RCanPointeeTy.getUnqualifiedType())) { 8790 // Valid unless a relational comparison of function pointers 8791 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8792 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8793 << LHSType << RHSType << LHS.get()->getSourceRange() 8794 << RHS.get()->getSourceRange(); 8795 } 8796 } else if (!IsRelational && 8797 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8798 // Valid unless comparison between non-null pointer and function pointer 8799 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8800 && !LHSIsNull && !RHSIsNull) 8801 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8802 /*isError*/false); 8803 } else { 8804 // Invalid 8805 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8806 } 8807 if (LCanPointeeTy != RCanPointeeTy) { 8808 const PointerType *lhsPtr = LHSType->getAs<PointerType>(); 8809 if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 8810 Diag(Loc, 8811 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8812 << LHSType << RHSType << 0 /* comparison */ 8813 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8814 } 8815 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 8816 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 8817 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 8818 : CK_BitCast; 8819 if (LHSIsNull && !RHSIsNull) 8820 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 8821 else 8822 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 8823 } 8824 return ResultTy; 8825 } 8826 8827 if (getLangOpts().CPlusPlus) { 8828 // Comparison of nullptr_t with itself. 8829 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 8830 return ResultTy; 8831 8832 // Comparison of pointers with null pointer constants and equality 8833 // comparisons of member pointers to null pointer constants. 8834 if (RHSIsNull && 8835 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 8836 (!IsRelational && 8837 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 8838 RHS = ImpCastExprToType(RHS.get(), LHSType, 8839 LHSType->isMemberPointerType() 8840 ? CK_NullToMemberPointer 8841 : CK_NullToPointer); 8842 return ResultTy; 8843 } 8844 if (LHSIsNull && 8845 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 8846 (!IsRelational && 8847 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 8848 LHS = ImpCastExprToType(LHS.get(), RHSType, 8849 RHSType->isMemberPointerType() 8850 ? CK_NullToMemberPointer 8851 : CK_NullToPointer); 8852 return ResultTy; 8853 } 8854 8855 // Comparison of member pointers. 8856 if (!IsRelational && 8857 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 8858 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8859 return QualType(); 8860 else 8861 return ResultTy; 8862 } 8863 8864 // Handle scoped enumeration types specifically, since they don't promote 8865 // to integers. 8866 if (LHS.get()->getType()->isEnumeralType() && 8867 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8868 RHS.get()->getType())) 8869 return ResultTy; 8870 } 8871 8872 // Handle block pointer types. 8873 if (!IsRelational && LHSType->isBlockPointerType() && 8874 RHSType->isBlockPointerType()) { 8875 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8876 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8877 8878 if (!LHSIsNull && !RHSIsNull && 8879 !Context.typesAreCompatible(lpointee, rpointee)) { 8880 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8881 << LHSType << RHSType << LHS.get()->getSourceRange() 8882 << RHS.get()->getSourceRange(); 8883 } 8884 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8885 return ResultTy; 8886 } 8887 8888 // Allow block pointers to be compared with null pointer constants. 8889 if (!IsRelational 8890 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8891 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8892 if (!LHSIsNull && !RHSIsNull) { 8893 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8894 ->getPointeeType()->isVoidType()) 8895 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8896 ->getPointeeType()->isVoidType()))) 8897 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8898 << LHSType << RHSType << LHS.get()->getSourceRange() 8899 << RHS.get()->getSourceRange(); 8900 } 8901 if (LHSIsNull && !RHSIsNull) 8902 LHS = ImpCastExprToType(LHS.get(), RHSType, 8903 RHSType->isPointerType() ? CK_BitCast 8904 : CK_AnyPointerToBlockPointerCast); 8905 else 8906 RHS = ImpCastExprToType(RHS.get(), LHSType, 8907 LHSType->isPointerType() ? CK_BitCast 8908 : CK_AnyPointerToBlockPointerCast); 8909 return ResultTy; 8910 } 8911 8912 if (LHSType->isObjCObjectPointerType() || 8913 RHSType->isObjCObjectPointerType()) { 8914 const PointerType *LPT = LHSType->getAs<PointerType>(); 8915 const PointerType *RPT = RHSType->getAs<PointerType>(); 8916 if (LPT || RPT) { 8917 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8918 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8919 8920 if (!LPtrToVoid && !RPtrToVoid && 8921 !Context.typesAreCompatible(LHSType, RHSType)) { 8922 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8923 /*isError*/false); 8924 } 8925 if (LHSIsNull && !RHSIsNull) { 8926 Expr *E = LHS.get(); 8927 if (getLangOpts().ObjCAutoRefCount) 8928 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8929 LHS = ImpCastExprToType(E, RHSType, 8930 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8931 } 8932 else { 8933 Expr *E = RHS.get(); 8934 if (getLangOpts().ObjCAutoRefCount) 8935 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false, 8936 Opc); 8937 RHS = ImpCastExprToType(E, LHSType, 8938 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8939 } 8940 return ResultTy; 8941 } 8942 if (LHSType->isObjCObjectPointerType() && 8943 RHSType->isObjCObjectPointerType()) { 8944 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8945 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8946 /*isError*/false); 8947 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8948 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8949 8950 if (LHSIsNull && !RHSIsNull) 8951 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8952 else 8953 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8954 return ResultTy; 8955 } 8956 } 8957 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8958 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8959 unsigned DiagID = 0; 8960 bool isError = false; 8961 if (LangOpts.DebuggerSupport) { 8962 // Under a debugger, allow the comparison of pointers to integers, 8963 // since users tend to want to compare addresses. 8964 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8965 (RHSIsNull && RHSType->isIntegerType())) { 8966 if (IsRelational && !getLangOpts().CPlusPlus) 8967 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8968 } else if (IsRelational && !getLangOpts().CPlusPlus) 8969 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8970 else if (getLangOpts().CPlusPlus) { 8971 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8972 isError = true; 8973 } else 8974 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8975 8976 if (DiagID) { 8977 Diag(Loc, DiagID) 8978 << LHSType << RHSType << LHS.get()->getSourceRange() 8979 << RHS.get()->getSourceRange(); 8980 if (isError) 8981 return QualType(); 8982 } 8983 8984 if (LHSType->isIntegerType()) 8985 LHS = ImpCastExprToType(LHS.get(), RHSType, 8986 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8987 else 8988 RHS = ImpCastExprToType(RHS.get(), LHSType, 8989 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8990 return ResultTy; 8991 } 8992 8993 // Handle block pointers. 8994 if (!IsRelational && RHSIsNull 8995 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8996 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8997 return ResultTy; 8998 } 8999 if (!IsRelational && LHSIsNull 9000 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9001 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9002 return ResultTy; 9003 } 9004 9005 return InvalidOperands(Loc, LHS, RHS); 9006 } 9007 9008 9009 // Return a signed type that is of identical size and number of elements. 9010 // For floating point vectors, return an integer type of identical size 9011 // and number of elements. 9012 QualType Sema::GetSignedVectorType(QualType V) { 9013 const VectorType *VTy = V->getAs<VectorType>(); 9014 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9015 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9016 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9017 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9018 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9019 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9020 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9021 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9022 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9023 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9024 "Unhandled vector element size in vector compare"); 9025 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9026 } 9027 9028 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9029 /// operates on extended vector types. Instead of producing an IntTy result, 9030 /// like a scalar comparison, a vector comparison produces a vector of integer 9031 /// types. 9032 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9033 SourceLocation Loc, 9034 bool IsRelational) { 9035 // Check to make sure we're operating on vectors of the same type and width, 9036 // Allowing one side to be a scalar of element type. 9037 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9038 /*AllowBothBool*/true, 9039 /*AllowBoolConversions*/getLangOpts().ZVector); 9040 if (vType.isNull()) 9041 return vType; 9042 9043 QualType LHSType = LHS.get()->getType(); 9044 9045 // If AltiVec, the comparison results in a numeric type, i.e. 9046 // bool for C++, int for C 9047 if (getLangOpts().AltiVec && 9048 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9049 return Context.getLogicalOperationType(); 9050 9051 // For non-floating point types, check for self-comparisons of the form 9052 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9053 // often indicate logic errors in the program. 9054 if (!LHSType->hasFloatingRepresentation() && 9055 ActiveTemplateInstantiations.empty()) { 9056 if (DeclRefExpr* DRL 9057 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9058 if (DeclRefExpr* DRR 9059 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9060 if (DRL->getDecl() == DRR->getDecl()) 9061 DiagRuntimeBehavior(Loc, nullptr, 9062 PDiag(diag::warn_comparison_always) 9063 << 0 // self- 9064 << 2 // "a constant" 9065 ); 9066 } 9067 9068 // Check for comparisons of floating point operands using != and ==. 9069 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9070 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9071 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9072 } 9073 9074 // Return a signed type for the vector. 9075 return GetSignedVectorType(LHSType); 9076 } 9077 9078 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9079 SourceLocation Loc) { 9080 // Ensure that either both operands are of the same vector type, or 9081 // one operand is of a vector type and the other is of its element type. 9082 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9083 /*AllowBothBool*/true, 9084 /*AllowBoolConversions*/false); 9085 if (vType.isNull()) 9086 return InvalidOperands(Loc, LHS, RHS); 9087 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9088 vType->hasFloatingRepresentation()) 9089 return InvalidOperands(Loc, LHS, RHS); 9090 9091 return GetSignedVectorType(LHS.get()->getType()); 9092 } 9093 9094 inline QualType Sema::CheckBitwiseOperands( 9095 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9096 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9097 9098 if (LHS.get()->getType()->isVectorType() || 9099 RHS.get()->getType()->isVectorType()) { 9100 if (LHS.get()->getType()->hasIntegerRepresentation() && 9101 RHS.get()->getType()->hasIntegerRepresentation()) 9102 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9103 /*AllowBothBool*/true, 9104 /*AllowBoolConversions*/getLangOpts().ZVector); 9105 return InvalidOperands(Loc, LHS, RHS); 9106 } 9107 9108 ExprResult LHSResult = LHS, RHSResult = RHS; 9109 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9110 IsCompAssign); 9111 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9112 return QualType(); 9113 LHS = LHSResult.get(); 9114 RHS = RHSResult.get(); 9115 9116 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9117 return compType; 9118 return InvalidOperands(Loc, LHS, RHS); 9119 } 9120 9121 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 9122 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 9123 9124 // Check vector operands differently. 9125 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9126 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9127 9128 // Diagnose cases where the user write a logical and/or but probably meant a 9129 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9130 // is a constant. 9131 if (LHS.get()->getType()->isIntegerType() && 9132 !LHS.get()->getType()->isBooleanType() && 9133 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9134 // Don't warn in macros or template instantiations. 9135 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9136 // If the RHS can be constant folded, and if it constant folds to something 9137 // that isn't 0 or 1 (which indicate a potential logical operation that 9138 // happened to fold to true/false) then warn. 9139 // Parens on the RHS are ignored. 9140 llvm::APSInt Result; 9141 if (RHS.get()->EvaluateAsInt(Result, Context)) 9142 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9143 !RHS.get()->getExprLoc().isMacroID()) || 9144 (Result != 0 && Result != 1)) { 9145 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9146 << RHS.get()->getSourceRange() 9147 << (Opc == BO_LAnd ? "&&" : "||"); 9148 // Suggest replacing the logical operator with the bitwise version 9149 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9150 << (Opc == BO_LAnd ? "&" : "|") 9151 << FixItHint::CreateReplacement(SourceRange( 9152 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 9153 getLangOpts())), 9154 Opc == BO_LAnd ? "&" : "|"); 9155 if (Opc == BO_LAnd) 9156 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9157 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9158 << FixItHint::CreateRemoval( 9159 SourceRange( 9160 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 9161 0, getSourceManager(), 9162 getLangOpts()), 9163 RHS.get()->getLocEnd())); 9164 } 9165 } 9166 9167 if (!Context.getLangOpts().CPlusPlus) { 9168 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9169 // not operate on the built-in scalar and vector float types. 9170 if (Context.getLangOpts().OpenCL && 9171 Context.getLangOpts().OpenCLVersion < 120) { 9172 if (LHS.get()->getType()->isFloatingType() || 9173 RHS.get()->getType()->isFloatingType()) 9174 return InvalidOperands(Loc, LHS, RHS); 9175 } 9176 9177 LHS = UsualUnaryConversions(LHS.get()); 9178 if (LHS.isInvalid()) 9179 return QualType(); 9180 9181 RHS = UsualUnaryConversions(RHS.get()); 9182 if (RHS.isInvalid()) 9183 return QualType(); 9184 9185 if (!LHS.get()->getType()->isScalarType() || 9186 !RHS.get()->getType()->isScalarType()) 9187 return InvalidOperands(Loc, LHS, RHS); 9188 9189 return Context.IntTy; 9190 } 9191 9192 // The following is safe because we only use this method for 9193 // non-overloadable operands. 9194 9195 // C++ [expr.log.and]p1 9196 // C++ [expr.log.or]p1 9197 // The operands are both contextually converted to type bool. 9198 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9199 if (LHSRes.isInvalid()) 9200 return InvalidOperands(Loc, LHS, RHS); 9201 LHS = LHSRes; 9202 9203 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9204 if (RHSRes.isInvalid()) 9205 return InvalidOperands(Loc, LHS, RHS); 9206 RHS = RHSRes; 9207 9208 // C++ [expr.log.and]p2 9209 // C++ [expr.log.or]p2 9210 // The result is a bool. 9211 return Context.BoolTy; 9212 } 9213 9214 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9215 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9216 if (!ME) return false; 9217 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9218 ObjCMessageExpr *Base = 9219 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9220 if (!Base) return false; 9221 return Base->getMethodDecl() != nullptr; 9222 } 9223 9224 /// Is the given expression (which must be 'const') a reference to a 9225 /// variable which was originally non-const, but which has become 9226 /// 'const' due to being captured within a block? 9227 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9228 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9229 assert(E->isLValue() && E->getType().isConstQualified()); 9230 E = E->IgnoreParens(); 9231 9232 // Must be a reference to a declaration from an enclosing scope. 9233 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9234 if (!DRE) return NCCK_None; 9235 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9236 9237 // The declaration must be a variable which is not declared 'const'. 9238 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9239 if (!var) return NCCK_None; 9240 if (var->getType().isConstQualified()) return NCCK_None; 9241 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9242 9243 // Decide whether the first capture was for a block or a lambda. 9244 DeclContext *DC = S.CurContext, *Prev = nullptr; 9245 while (DC != var->getDeclContext()) { 9246 Prev = DC; 9247 DC = DC->getParent(); 9248 } 9249 // Unless we have an init-capture, we've gone one step too far. 9250 if (!var->isInitCapture()) 9251 DC = Prev; 9252 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9253 } 9254 9255 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9256 Ty = Ty.getNonReferenceType(); 9257 if (IsDereference && Ty->isPointerType()) 9258 Ty = Ty->getPointeeType(); 9259 return !Ty.isConstQualified(); 9260 } 9261 9262 /// Emit the "read-only variable not assignable" error and print notes to give 9263 /// more information about why the variable is not assignable, such as pointing 9264 /// to the declaration of a const variable, showing that a method is const, or 9265 /// that the function is returning a const reference. 9266 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9267 SourceLocation Loc) { 9268 // Update err_typecheck_assign_const and note_typecheck_assign_const 9269 // when this enum is changed. 9270 enum { 9271 ConstFunction, 9272 ConstVariable, 9273 ConstMember, 9274 ConstMethod, 9275 ConstUnknown, // Keep as last element 9276 }; 9277 9278 SourceRange ExprRange = E->getSourceRange(); 9279 9280 // Only emit one error on the first const found. All other consts will emit 9281 // a note to the error. 9282 bool DiagnosticEmitted = false; 9283 9284 // Track if the current expression is the result of a derefence, and if the 9285 // next checked expression is the result of a derefence. 9286 bool IsDereference = false; 9287 bool NextIsDereference = false; 9288 9289 // Loop to process MemberExpr chains. 9290 while (true) { 9291 IsDereference = NextIsDereference; 9292 NextIsDereference = false; 9293 9294 E = E->IgnoreParenImpCasts(); 9295 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9296 NextIsDereference = ME->isArrow(); 9297 const ValueDecl *VD = ME->getMemberDecl(); 9298 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9299 // Mutable fields can be modified even if the class is const. 9300 if (Field->isMutable()) { 9301 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9302 break; 9303 } 9304 9305 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9306 if (!DiagnosticEmitted) { 9307 S.Diag(Loc, diag::err_typecheck_assign_const) 9308 << ExprRange << ConstMember << false /*static*/ << Field 9309 << Field->getType(); 9310 DiagnosticEmitted = true; 9311 } 9312 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9313 << ConstMember << false /*static*/ << Field << Field->getType() 9314 << Field->getSourceRange(); 9315 } 9316 E = ME->getBase(); 9317 continue; 9318 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9319 if (VDecl->getType().isConstQualified()) { 9320 if (!DiagnosticEmitted) { 9321 S.Diag(Loc, diag::err_typecheck_assign_const) 9322 << ExprRange << ConstMember << true /*static*/ << VDecl 9323 << VDecl->getType(); 9324 DiagnosticEmitted = true; 9325 } 9326 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9327 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9328 << VDecl->getSourceRange(); 9329 } 9330 // Static fields do not inherit constness from parents. 9331 break; 9332 } 9333 break; 9334 } // End MemberExpr 9335 break; 9336 } 9337 9338 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9339 // Function calls 9340 const FunctionDecl *FD = CE->getDirectCallee(); 9341 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9342 if (!DiagnosticEmitted) { 9343 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9344 << ConstFunction << FD; 9345 DiagnosticEmitted = true; 9346 } 9347 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9348 diag::note_typecheck_assign_const) 9349 << ConstFunction << FD << FD->getReturnType() 9350 << FD->getReturnTypeSourceRange(); 9351 } 9352 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9353 // Point to variable declaration. 9354 if (const ValueDecl *VD = DRE->getDecl()) { 9355 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9356 if (!DiagnosticEmitted) { 9357 S.Diag(Loc, diag::err_typecheck_assign_const) 9358 << ExprRange << ConstVariable << VD << VD->getType(); 9359 DiagnosticEmitted = true; 9360 } 9361 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9362 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9363 } 9364 } 9365 } else if (isa<CXXThisExpr>(E)) { 9366 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9367 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9368 if (MD->isConst()) { 9369 if (!DiagnosticEmitted) { 9370 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9371 << ConstMethod << MD; 9372 DiagnosticEmitted = true; 9373 } 9374 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9375 << ConstMethod << MD << MD->getSourceRange(); 9376 } 9377 } 9378 } 9379 } 9380 9381 if (DiagnosticEmitted) 9382 return; 9383 9384 // Can't determine a more specific message, so display the generic error. 9385 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9386 } 9387 9388 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9389 /// emit an error and return true. If so, return false. 9390 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9391 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9392 SourceLocation OrigLoc = Loc; 9393 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9394 &Loc); 9395 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9396 IsLV = Expr::MLV_InvalidMessageExpression; 9397 if (IsLV == Expr::MLV_Valid) 9398 return false; 9399 9400 unsigned DiagID = 0; 9401 bool NeedType = false; 9402 switch (IsLV) { // C99 6.5.16p2 9403 case Expr::MLV_ConstQualified: 9404 // Use a specialized diagnostic when we're assigning to an object 9405 // from an enclosing function or block. 9406 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9407 if (NCCK == NCCK_Block) 9408 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9409 else 9410 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9411 break; 9412 } 9413 9414 // In ARC, use some specialized diagnostics for occasions where we 9415 // infer 'const'. These are always pseudo-strong variables. 9416 if (S.getLangOpts().ObjCAutoRefCount) { 9417 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9418 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9419 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9420 9421 // Use the normal diagnostic if it's pseudo-__strong but the 9422 // user actually wrote 'const'. 9423 if (var->isARCPseudoStrong() && 9424 (!var->getTypeSourceInfo() || 9425 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9426 // There are two pseudo-strong cases: 9427 // - self 9428 ObjCMethodDecl *method = S.getCurMethodDecl(); 9429 if (method && var == method->getSelfDecl()) 9430 DiagID = method->isClassMethod() 9431 ? diag::err_typecheck_arc_assign_self_class_method 9432 : diag::err_typecheck_arc_assign_self; 9433 9434 // - fast enumeration variables 9435 else 9436 DiagID = diag::err_typecheck_arr_assign_enumeration; 9437 9438 SourceRange Assign; 9439 if (Loc != OrigLoc) 9440 Assign = SourceRange(OrigLoc, OrigLoc); 9441 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9442 // We need to preserve the AST regardless, so migration tool 9443 // can do its job. 9444 return false; 9445 } 9446 } 9447 } 9448 9449 // If none of the special cases above are triggered, then this is a 9450 // simple const assignment. 9451 if (DiagID == 0) { 9452 DiagnoseConstAssignment(S, E, Loc); 9453 return true; 9454 } 9455 9456 break; 9457 case Expr::MLV_ConstAddrSpace: 9458 DiagnoseConstAssignment(S, E, Loc); 9459 return true; 9460 case Expr::MLV_ArrayType: 9461 case Expr::MLV_ArrayTemporary: 9462 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9463 NeedType = true; 9464 break; 9465 case Expr::MLV_NotObjectType: 9466 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9467 NeedType = true; 9468 break; 9469 case Expr::MLV_LValueCast: 9470 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9471 break; 9472 case Expr::MLV_Valid: 9473 llvm_unreachable("did not take early return for MLV_Valid"); 9474 case Expr::MLV_InvalidExpression: 9475 case Expr::MLV_MemberFunction: 9476 case Expr::MLV_ClassTemporary: 9477 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9478 break; 9479 case Expr::MLV_IncompleteType: 9480 case Expr::MLV_IncompleteVoidType: 9481 return S.RequireCompleteType(Loc, E->getType(), 9482 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9483 case Expr::MLV_DuplicateVectorComponents: 9484 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9485 break; 9486 case Expr::MLV_NoSetterProperty: 9487 llvm_unreachable("readonly properties should be processed differently"); 9488 case Expr::MLV_InvalidMessageExpression: 9489 DiagID = diag::error_readonly_message_assignment; 9490 break; 9491 case Expr::MLV_SubObjCPropertySetting: 9492 DiagID = diag::error_no_subobject_property_setting; 9493 break; 9494 } 9495 9496 SourceRange Assign; 9497 if (Loc != OrigLoc) 9498 Assign = SourceRange(OrigLoc, OrigLoc); 9499 if (NeedType) 9500 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9501 else 9502 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9503 return true; 9504 } 9505 9506 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9507 SourceLocation Loc, 9508 Sema &Sema) { 9509 // C / C++ fields 9510 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9511 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9512 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9513 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9514 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9515 } 9516 9517 // Objective-C instance variables 9518 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9519 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9520 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9521 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9522 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9523 if (RL && RR && RL->getDecl() == RR->getDecl()) 9524 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9525 } 9526 } 9527 9528 // C99 6.5.16.1 9529 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9530 SourceLocation Loc, 9531 QualType CompoundType) { 9532 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9533 9534 // Verify that LHS is a modifiable lvalue, and emit error if not. 9535 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9536 return QualType(); 9537 9538 QualType LHSType = LHSExpr->getType(); 9539 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9540 CompoundType; 9541 AssignConvertType ConvTy; 9542 if (CompoundType.isNull()) { 9543 Expr *RHSCheck = RHS.get(); 9544 9545 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9546 9547 QualType LHSTy(LHSType); 9548 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9549 if (RHS.isInvalid()) 9550 return QualType(); 9551 // Special case of NSObject attributes on c-style pointer types. 9552 if (ConvTy == IncompatiblePointer && 9553 ((Context.isObjCNSObjectType(LHSType) && 9554 RHSType->isObjCObjectPointerType()) || 9555 (Context.isObjCNSObjectType(RHSType) && 9556 LHSType->isObjCObjectPointerType()))) 9557 ConvTy = Compatible; 9558 9559 if (ConvTy == Compatible && 9560 LHSType->isObjCObjectType()) 9561 Diag(Loc, diag::err_objc_object_assignment) 9562 << LHSType; 9563 9564 // If the RHS is a unary plus or minus, check to see if they = and + are 9565 // right next to each other. If so, the user may have typo'd "x =+ 4" 9566 // instead of "x += 4". 9567 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9568 RHSCheck = ICE->getSubExpr(); 9569 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9570 if ((UO->getOpcode() == UO_Plus || 9571 UO->getOpcode() == UO_Minus) && 9572 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9573 // Only if the two operators are exactly adjacent. 9574 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9575 // And there is a space or other character before the subexpr of the 9576 // unary +/-. We don't want to warn on "x=-1". 9577 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9578 UO->getSubExpr()->getLocStart().isFileID()) { 9579 Diag(Loc, diag::warn_not_compound_assign) 9580 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9581 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9582 } 9583 } 9584 9585 if (ConvTy == Compatible) { 9586 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9587 // Warn about retain cycles where a block captures the LHS, but 9588 // not if the LHS is a simple variable into which the block is 9589 // being stored...unless that variable can be captured by reference! 9590 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9591 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9592 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9593 checkRetainCycles(LHSExpr, RHS.get()); 9594 9595 // It is safe to assign a weak reference into a strong variable. 9596 // Although this code can still have problems: 9597 // id x = self.weakProp; 9598 // id y = self.weakProp; 9599 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9600 // paths through the function. This should be revisited if 9601 // -Wrepeated-use-of-weak is made flow-sensitive. 9602 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9603 RHS.get()->getLocStart())) 9604 getCurFunction()->markSafeWeakUse(RHS.get()); 9605 9606 } else if (getLangOpts().ObjCAutoRefCount) { 9607 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9608 } 9609 } 9610 } else { 9611 // Compound assignment "x += y" 9612 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9613 } 9614 9615 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9616 RHS.get(), AA_Assigning)) 9617 return QualType(); 9618 9619 CheckForNullPointerDereference(*this, LHSExpr); 9620 9621 // C99 6.5.16p3: The type of an assignment expression is the type of the 9622 // left operand unless the left operand has qualified type, in which case 9623 // it is the unqualified version of the type of the left operand. 9624 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9625 // is converted to the type of the assignment expression (above). 9626 // C++ 5.17p1: the type of the assignment expression is that of its left 9627 // operand. 9628 return (getLangOpts().CPlusPlus 9629 ? LHSType : LHSType.getUnqualifiedType()); 9630 } 9631 9632 // C99 6.5.17 9633 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9634 SourceLocation Loc) { 9635 LHS = S.CheckPlaceholderExpr(LHS.get()); 9636 RHS = S.CheckPlaceholderExpr(RHS.get()); 9637 if (LHS.isInvalid() || RHS.isInvalid()) 9638 return QualType(); 9639 9640 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9641 // operands, but not unary promotions. 9642 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9643 9644 // So we treat the LHS as a ignored value, and in C++ we allow the 9645 // containing site to determine what should be done with the RHS. 9646 LHS = S.IgnoredValueConversions(LHS.get()); 9647 if (LHS.isInvalid()) 9648 return QualType(); 9649 9650 S.DiagnoseUnusedExprResult(LHS.get()); 9651 9652 if (!S.getLangOpts().CPlusPlus) { 9653 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9654 if (RHS.isInvalid()) 9655 return QualType(); 9656 if (!RHS.get()->getType()->isVoidType()) 9657 S.RequireCompleteType(Loc, RHS.get()->getType(), 9658 diag::err_incomplete_type); 9659 } 9660 9661 return RHS.get()->getType(); 9662 } 9663 9664 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9665 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9666 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9667 ExprValueKind &VK, 9668 ExprObjectKind &OK, 9669 SourceLocation OpLoc, 9670 bool IsInc, bool IsPrefix) { 9671 if (Op->isTypeDependent()) 9672 return S.Context.DependentTy; 9673 9674 QualType ResType = Op->getType(); 9675 // Atomic types can be used for increment / decrement where the non-atomic 9676 // versions can, so ignore the _Atomic() specifier for the purpose of 9677 // checking. 9678 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9679 ResType = ResAtomicType->getValueType(); 9680 9681 assert(!ResType.isNull() && "no type for increment/decrement expression"); 9682 9683 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 9684 // Decrement of bool is not allowed. 9685 if (!IsInc) { 9686 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 9687 return QualType(); 9688 } 9689 // Increment of bool sets it to true, but is deprecated. 9690 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 9691 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 9692 // Error on enum increments and decrements in C++ mode 9693 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 9694 return QualType(); 9695 } else if (ResType->isRealType()) { 9696 // OK! 9697 } else if (ResType->isPointerType()) { 9698 // C99 6.5.2.4p2, 6.5.6p2 9699 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 9700 return QualType(); 9701 } else if (ResType->isObjCObjectPointerType()) { 9702 // On modern runtimes, ObjC pointer arithmetic is forbidden. 9703 // Otherwise, we just need a complete type. 9704 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 9705 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 9706 return QualType(); 9707 } else if (ResType->isAnyComplexType()) { 9708 // C99 does not support ++/-- on complex types, we allow as an extension. 9709 S.Diag(OpLoc, diag::ext_integer_increment_complex) 9710 << ResType << Op->getSourceRange(); 9711 } else if (ResType->isPlaceholderType()) { 9712 ExprResult PR = S.CheckPlaceholderExpr(Op); 9713 if (PR.isInvalid()) return QualType(); 9714 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 9715 IsInc, IsPrefix); 9716 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 9717 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 9718 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 9719 (ResType->getAs<VectorType>()->getVectorKind() != 9720 VectorType::AltiVecBool)) { 9721 // The z vector extensions allow ++ and -- for non-bool vectors. 9722 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 9723 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 9724 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 9725 } else { 9726 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 9727 << ResType << int(IsInc) << Op->getSourceRange(); 9728 return QualType(); 9729 } 9730 // At this point, we know we have a real, complex or pointer type. 9731 // Now make sure the operand is a modifiable lvalue. 9732 if (CheckForModifiableLvalue(Op, OpLoc, S)) 9733 return QualType(); 9734 // In C++, a prefix increment is the same type as the operand. Otherwise 9735 // (in C or with postfix), the increment is the unqualified type of the 9736 // operand. 9737 if (IsPrefix && S.getLangOpts().CPlusPlus) { 9738 VK = VK_LValue; 9739 OK = Op->getObjectKind(); 9740 return ResType; 9741 } else { 9742 VK = VK_RValue; 9743 return ResType.getUnqualifiedType(); 9744 } 9745 } 9746 9747 9748 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 9749 /// This routine allows us to typecheck complex/recursive expressions 9750 /// where the declaration is needed for type checking. We only need to 9751 /// handle cases when the expression references a function designator 9752 /// or is an lvalue. Here are some examples: 9753 /// - &(x) => x 9754 /// - &*****f => f for f a function designator. 9755 /// - &s.xx => s 9756 /// - &s.zz[1].yy -> s, if zz is an array 9757 /// - *(x + 1) -> x, if x is an array 9758 /// - &"123"[2] -> 0 9759 /// - & __real__ x -> x 9760 static ValueDecl *getPrimaryDecl(Expr *E) { 9761 switch (E->getStmtClass()) { 9762 case Stmt::DeclRefExprClass: 9763 return cast<DeclRefExpr>(E)->getDecl(); 9764 case Stmt::MemberExprClass: 9765 // If this is an arrow operator, the address is an offset from 9766 // the base's value, so the object the base refers to is 9767 // irrelevant. 9768 if (cast<MemberExpr>(E)->isArrow()) 9769 return nullptr; 9770 // Otherwise, the expression refers to a part of the base 9771 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 9772 case Stmt::ArraySubscriptExprClass: { 9773 // FIXME: This code shouldn't be necessary! We should catch the implicit 9774 // promotion of register arrays earlier. 9775 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 9776 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 9777 if (ICE->getSubExpr()->getType()->isArrayType()) 9778 return getPrimaryDecl(ICE->getSubExpr()); 9779 } 9780 return nullptr; 9781 } 9782 case Stmt::UnaryOperatorClass: { 9783 UnaryOperator *UO = cast<UnaryOperator>(E); 9784 9785 switch(UO->getOpcode()) { 9786 case UO_Real: 9787 case UO_Imag: 9788 case UO_Extension: 9789 return getPrimaryDecl(UO->getSubExpr()); 9790 default: 9791 return nullptr; 9792 } 9793 } 9794 case Stmt::ParenExprClass: 9795 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 9796 case Stmt::ImplicitCastExprClass: 9797 // If the result of an implicit cast is an l-value, we care about 9798 // the sub-expression; otherwise, the result here doesn't matter. 9799 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 9800 default: 9801 return nullptr; 9802 } 9803 } 9804 9805 namespace { 9806 enum { 9807 AO_Bit_Field = 0, 9808 AO_Vector_Element = 1, 9809 AO_Property_Expansion = 2, 9810 AO_Register_Variable = 3, 9811 AO_No_Error = 4 9812 }; 9813 } 9814 /// \brief Diagnose invalid operand for address of operations. 9815 /// 9816 /// \param Type The type of operand which cannot have its address taken. 9817 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 9818 Expr *E, unsigned Type) { 9819 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 9820 } 9821 9822 /// CheckAddressOfOperand - The operand of & must be either a function 9823 /// designator or an lvalue designating an object. If it is an lvalue, the 9824 /// object cannot be declared with storage class register or be a bit field. 9825 /// Note: The usual conversions are *not* applied to the operand of the & 9826 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 9827 /// In C++, the operand might be an overloaded function name, in which case 9828 /// we allow the '&' but retain the overloaded-function type. 9829 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 9830 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 9831 if (PTy->getKind() == BuiltinType::Overload) { 9832 Expr *E = OrigOp.get()->IgnoreParens(); 9833 if (!isa<OverloadExpr>(E)) { 9834 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 9835 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 9836 << OrigOp.get()->getSourceRange(); 9837 return QualType(); 9838 } 9839 9840 OverloadExpr *Ovl = cast<OverloadExpr>(E); 9841 if (isa<UnresolvedMemberExpr>(Ovl)) 9842 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 9843 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9844 << OrigOp.get()->getSourceRange(); 9845 return QualType(); 9846 } 9847 9848 return Context.OverloadTy; 9849 } 9850 9851 if (PTy->getKind() == BuiltinType::UnknownAny) 9852 return Context.UnknownAnyTy; 9853 9854 if (PTy->getKind() == BuiltinType::BoundMember) { 9855 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9856 << OrigOp.get()->getSourceRange(); 9857 return QualType(); 9858 } 9859 9860 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 9861 if (OrigOp.isInvalid()) return QualType(); 9862 } 9863 9864 if (OrigOp.get()->isTypeDependent()) 9865 return Context.DependentTy; 9866 9867 assert(!OrigOp.get()->getType()->isPlaceholderType()); 9868 9869 // Make sure to ignore parentheses in subsequent checks 9870 Expr *op = OrigOp.get()->IgnoreParens(); 9871 9872 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 9873 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 9874 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 9875 return QualType(); 9876 } 9877 9878 if (getLangOpts().C99) { 9879 // Implement C99-only parts of addressof rules. 9880 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 9881 if (uOp->getOpcode() == UO_Deref) 9882 // Per C99 6.5.3.2, the address of a deref always returns a valid result 9883 // (assuming the deref expression is valid). 9884 return uOp->getSubExpr()->getType(); 9885 } 9886 // Technically, there should be a check for array subscript 9887 // expressions here, but the result of one is always an lvalue anyway. 9888 } 9889 ValueDecl *dcl = getPrimaryDecl(op); 9890 Expr::LValueClassification lval = op->ClassifyLValue(Context); 9891 unsigned AddressOfError = AO_No_Error; 9892 9893 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 9894 bool sfinae = (bool)isSFINAEContext(); 9895 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 9896 : diag::ext_typecheck_addrof_temporary) 9897 << op->getType() << op->getSourceRange(); 9898 if (sfinae) 9899 return QualType(); 9900 // Materialize the temporary as an lvalue so that we can take its address. 9901 OrigOp = op = new (Context) 9902 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 9903 } else if (isa<ObjCSelectorExpr>(op)) { 9904 return Context.getPointerType(op->getType()); 9905 } else if (lval == Expr::LV_MemberFunction) { 9906 // If it's an instance method, make a member pointer. 9907 // The expression must have exactly the form &A::foo. 9908 9909 // If the underlying expression isn't a decl ref, give up. 9910 if (!isa<DeclRefExpr>(op)) { 9911 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9912 << OrigOp.get()->getSourceRange(); 9913 return QualType(); 9914 } 9915 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 9916 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 9917 9918 // The id-expression was parenthesized. 9919 if (OrigOp.get() != DRE) { 9920 Diag(OpLoc, diag::err_parens_pointer_member_function) 9921 << OrigOp.get()->getSourceRange(); 9922 9923 // The method was named without a qualifier. 9924 } else if (!DRE->getQualifier()) { 9925 if (MD->getParent()->getName().empty()) 9926 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9927 << op->getSourceRange(); 9928 else { 9929 SmallString<32> Str; 9930 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 9931 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9932 << op->getSourceRange() 9933 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 9934 } 9935 } 9936 9937 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 9938 if (isa<CXXDestructorDecl>(MD)) 9939 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 9940 9941 QualType MPTy = Context.getMemberPointerType( 9942 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 9943 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9944 RequireCompleteType(OpLoc, MPTy, 0); 9945 return MPTy; 9946 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 9947 // C99 6.5.3.2p1 9948 // The operand must be either an l-value or a function designator 9949 if (!op->getType()->isFunctionType()) { 9950 // Use a special diagnostic for loads from property references. 9951 if (isa<PseudoObjectExpr>(op)) { 9952 AddressOfError = AO_Property_Expansion; 9953 } else { 9954 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 9955 << op->getType() << op->getSourceRange(); 9956 return QualType(); 9957 } 9958 } 9959 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 9960 // The operand cannot be a bit-field 9961 AddressOfError = AO_Bit_Field; 9962 } else if (op->getObjectKind() == OK_VectorComponent) { 9963 // The operand cannot be an element of a vector 9964 AddressOfError = AO_Vector_Element; 9965 } else if (dcl) { // C99 6.5.3.2p1 9966 // We have an lvalue with a decl. Make sure the decl is not declared 9967 // with the register storage-class specifier. 9968 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 9969 // in C++ it is not error to take address of a register 9970 // variable (c++03 7.1.1P3) 9971 if (vd->getStorageClass() == SC_Register && 9972 !getLangOpts().CPlusPlus) { 9973 AddressOfError = AO_Register_Variable; 9974 } 9975 } else if (isa<MSPropertyDecl>(dcl)) { 9976 AddressOfError = AO_Property_Expansion; 9977 } else if (isa<FunctionTemplateDecl>(dcl)) { 9978 return Context.OverloadTy; 9979 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 9980 // Okay: we can take the address of a field. 9981 // Could be a pointer to member, though, if there is an explicit 9982 // scope qualifier for the class. 9983 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 9984 DeclContext *Ctx = dcl->getDeclContext(); 9985 if (Ctx && Ctx->isRecord()) { 9986 if (dcl->getType()->isReferenceType()) { 9987 Diag(OpLoc, 9988 diag::err_cannot_form_pointer_to_member_of_reference_type) 9989 << dcl->getDeclName() << dcl->getType(); 9990 return QualType(); 9991 } 9992 9993 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 9994 Ctx = Ctx->getParent(); 9995 9996 QualType MPTy = Context.getMemberPointerType( 9997 op->getType(), 9998 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 9999 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10000 RequireCompleteType(OpLoc, MPTy, 0); 10001 return MPTy; 10002 } 10003 } 10004 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10005 llvm_unreachable("Unknown/unexpected decl type"); 10006 } 10007 10008 if (AddressOfError != AO_No_Error) { 10009 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10010 return QualType(); 10011 } 10012 10013 if (lval == Expr::LV_IncompleteVoidType) { 10014 // Taking the address of a void variable is technically illegal, but we 10015 // allow it in cases which are otherwise valid. 10016 // Example: "extern void x; void* y = &x;". 10017 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10018 } 10019 10020 // If the operand has type "type", the result has type "pointer to type". 10021 if (op->getType()->isObjCObjectType()) 10022 return Context.getObjCObjectPointerType(op->getType()); 10023 return Context.getPointerType(op->getType()); 10024 } 10025 10026 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10027 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10028 if (!DRE) 10029 return; 10030 const Decl *D = DRE->getDecl(); 10031 if (!D) 10032 return; 10033 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10034 if (!Param) 10035 return; 10036 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10037 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10038 return; 10039 if (FunctionScopeInfo *FD = S.getCurFunction()) 10040 if (!FD->ModifiedNonNullParams.count(Param)) 10041 FD->ModifiedNonNullParams.insert(Param); 10042 } 10043 10044 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10045 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10046 SourceLocation OpLoc) { 10047 if (Op->isTypeDependent()) 10048 return S.Context.DependentTy; 10049 10050 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10051 if (ConvResult.isInvalid()) 10052 return QualType(); 10053 Op = ConvResult.get(); 10054 QualType OpTy = Op->getType(); 10055 QualType Result; 10056 10057 if (isa<CXXReinterpretCastExpr>(Op)) { 10058 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10059 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10060 Op->getSourceRange()); 10061 } 10062 10063 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10064 Result = PT->getPointeeType(); 10065 else if (const ObjCObjectPointerType *OPT = 10066 OpTy->getAs<ObjCObjectPointerType>()) 10067 Result = OPT->getPointeeType(); 10068 else { 10069 ExprResult PR = S.CheckPlaceholderExpr(Op); 10070 if (PR.isInvalid()) return QualType(); 10071 if (PR.get() != Op) 10072 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10073 } 10074 10075 if (Result.isNull()) { 10076 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10077 << OpTy << Op->getSourceRange(); 10078 return QualType(); 10079 } 10080 10081 // Note that per both C89 and C99, indirection is always legal, even if Result 10082 // is an incomplete type or void. It would be possible to warn about 10083 // dereferencing a void pointer, but it's completely well-defined, and such a 10084 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10085 // for pointers to 'void' but is fine for any other pointer type: 10086 // 10087 // C++ [expr.unary.op]p1: 10088 // [...] the expression to which [the unary * operator] is applied shall 10089 // be a pointer to an object type, or a pointer to a function type 10090 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10091 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10092 << OpTy << Op->getSourceRange(); 10093 10094 // Dereferences are usually l-values... 10095 VK = VK_LValue; 10096 10097 // ...except that certain expressions are never l-values in C. 10098 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10099 VK = VK_RValue; 10100 10101 return Result; 10102 } 10103 10104 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10105 BinaryOperatorKind Opc; 10106 switch (Kind) { 10107 default: llvm_unreachable("Unknown binop!"); 10108 case tok::periodstar: Opc = BO_PtrMemD; break; 10109 case tok::arrowstar: Opc = BO_PtrMemI; break; 10110 case tok::star: Opc = BO_Mul; break; 10111 case tok::slash: Opc = BO_Div; break; 10112 case tok::percent: Opc = BO_Rem; break; 10113 case tok::plus: Opc = BO_Add; break; 10114 case tok::minus: Opc = BO_Sub; break; 10115 case tok::lessless: Opc = BO_Shl; break; 10116 case tok::greatergreater: Opc = BO_Shr; break; 10117 case tok::lessequal: Opc = BO_LE; break; 10118 case tok::less: Opc = BO_LT; break; 10119 case tok::greaterequal: Opc = BO_GE; break; 10120 case tok::greater: Opc = BO_GT; break; 10121 case tok::exclaimequal: Opc = BO_NE; break; 10122 case tok::equalequal: Opc = BO_EQ; break; 10123 case tok::amp: Opc = BO_And; break; 10124 case tok::caret: Opc = BO_Xor; break; 10125 case tok::pipe: Opc = BO_Or; break; 10126 case tok::ampamp: Opc = BO_LAnd; break; 10127 case tok::pipepipe: Opc = BO_LOr; break; 10128 case tok::equal: Opc = BO_Assign; break; 10129 case tok::starequal: Opc = BO_MulAssign; break; 10130 case tok::slashequal: Opc = BO_DivAssign; break; 10131 case tok::percentequal: Opc = BO_RemAssign; break; 10132 case tok::plusequal: Opc = BO_AddAssign; break; 10133 case tok::minusequal: Opc = BO_SubAssign; break; 10134 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10135 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10136 case tok::ampequal: Opc = BO_AndAssign; break; 10137 case tok::caretequal: Opc = BO_XorAssign; break; 10138 case tok::pipeequal: Opc = BO_OrAssign; break; 10139 case tok::comma: Opc = BO_Comma; break; 10140 } 10141 return Opc; 10142 } 10143 10144 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10145 tok::TokenKind Kind) { 10146 UnaryOperatorKind Opc; 10147 switch (Kind) { 10148 default: llvm_unreachable("Unknown unary op!"); 10149 case tok::plusplus: Opc = UO_PreInc; break; 10150 case tok::minusminus: Opc = UO_PreDec; break; 10151 case tok::amp: Opc = UO_AddrOf; break; 10152 case tok::star: Opc = UO_Deref; break; 10153 case tok::plus: Opc = UO_Plus; break; 10154 case tok::minus: Opc = UO_Minus; break; 10155 case tok::tilde: Opc = UO_Not; break; 10156 case tok::exclaim: Opc = UO_LNot; break; 10157 case tok::kw___real: Opc = UO_Real; break; 10158 case tok::kw___imag: Opc = UO_Imag; break; 10159 case tok::kw___extension__: Opc = UO_Extension; break; 10160 } 10161 return Opc; 10162 } 10163 10164 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10165 /// This warning is only emitted for builtin assignment operations. It is also 10166 /// suppressed in the event of macro expansions. 10167 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10168 SourceLocation OpLoc) { 10169 if (!S.ActiveTemplateInstantiations.empty()) 10170 return; 10171 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10172 return; 10173 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10174 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10175 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10176 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10177 if (!LHSDeclRef || !RHSDeclRef || 10178 LHSDeclRef->getLocation().isMacroID() || 10179 RHSDeclRef->getLocation().isMacroID()) 10180 return; 10181 const ValueDecl *LHSDecl = 10182 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10183 const ValueDecl *RHSDecl = 10184 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10185 if (LHSDecl != RHSDecl) 10186 return; 10187 if (LHSDecl->getType().isVolatileQualified()) 10188 return; 10189 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10190 if (RefTy->getPointeeType().isVolatileQualified()) 10191 return; 10192 10193 S.Diag(OpLoc, diag::warn_self_assignment) 10194 << LHSDeclRef->getType() 10195 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10196 } 10197 10198 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10199 /// is usually indicative of introspection within the Objective-C pointer. 10200 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10201 SourceLocation OpLoc) { 10202 if (!S.getLangOpts().ObjC1) 10203 return; 10204 10205 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10206 const Expr *LHS = L.get(); 10207 const Expr *RHS = R.get(); 10208 10209 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10210 ObjCPointerExpr = LHS; 10211 OtherExpr = RHS; 10212 } 10213 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10214 ObjCPointerExpr = RHS; 10215 OtherExpr = LHS; 10216 } 10217 10218 // This warning is deliberately made very specific to reduce false 10219 // positives with logic that uses '&' for hashing. This logic mainly 10220 // looks for code trying to introspect into tagged pointers, which 10221 // code should generally never do. 10222 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10223 unsigned Diag = diag::warn_objc_pointer_masking; 10224 // Determine if we are introspecting the result of performSelectorXXX. 10225 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10226 // Special case messages to -performSelector and friends, which 10227 // can return non-pointer values boxed in a pointer value. 10228 // Some clients may wish to silence warnings in this subcase. 10229 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10230 Selector S = ME->getSelector(); 10231 StringRef SelArg0 = S.getNameForSlot(0); 10232 if (SelArg0.startswith("performSelector")) 10233 Diag = diag::warn_objc_pointer_masking_performSelector; 10234 } 10235 10236 S.Diag(OpLoc, Diag) 10237 << ObjCPointerExpr->getSourceRange(); 10238 } 10239 } 10240 10241 static NamedDecl *getDeclFromExpr(Expr *E) { 10242 if (!E) 10243 return nullptr; 10244 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10245 return DRE->getDecl(); 10246 if (auto *ME = dyn_cast<MemberExpr>(E)) 10247 return ME->getMemberDecl(); 10248 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10249 return IRE->getDecl(); 10250 return nullptr; 10251 } 10252 10253 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10254 /// operator @p Opc at location @c TokLoc. This routine only supports 10255 /// built-in operations; ActOnBinOp handles overloaded operators. 10256 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10257 BinaryOperatorKind Opc, 10258 Expr *LHSExpr, Expr *RHSExpr) { 10259 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10260 // The syntax only allows initializer lists on the RHS of assignment, 10261 // so we don't need to worry about accepting invalid code for 10262 // non-assignment operators. 10263 // C++11 5.17p9: 10264 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10265 // of x = {} is x = T(). 10266 InitializationKind Kind = 10267 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10268 InitializedEntity Entity = 10269 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10270 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10271 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10272 if (Init.isInvalid()) 10273 return Init; 10274 RHSExpr = Init.get(); 10275 } 10276 10277 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10278 QualType ResultTy; // Result type of the binary operator. 10279 // The following two variables are used for compound assignment operators 10280 QualType CompLHSTy; // Type of LHS after promotions for computation 10281 QualType CompResultTy; // Type of computation result 10282 ExprValueKind VK = VK_RValue; 10283 ExprObjectKind OK = OK_Ordinary; 10284 10285 if (!getLangOpts().CPlusPlus) { 10286 // C cannot handle TypoExpr nodes on either side of a binop because it 10287 // doesn't handle dependent types properly, so make sure any TypoExprs have 10288 // been dealt with before checking the operands. 10289 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10290 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10291 if (Opc != BO_Assign) 10292 return ExprResult(E); 10293 // Avoid correcting the RHS to the same Expr as the LHS. 10294 Decl *D = getDeclFromExpr(E); 10295 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10296 }); 10297 if (!LHS.isUsable() || !RHS.isUsable()) 10298 return ExprError(); 10299 } 10300 10301 switch (Opc) { 10302 case BO_Assign: 10303 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10304 if (getLangOpts().CPlusPlus && 10305 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10306 VK = LHS.get()->getValueKind(); 10307 OK = LHS.get()->getObjectKind(); 10308 } 10309 if (!ResultTy.isNull()) { 10310 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10311 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10312 } 10313 RecordModifiableNonNullParam(*this, LHS.get()); 10314 break; 10315 case BO_PtrMemD: 10316 case BO_PtrMemI: 10317 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10318 Opc == BO_PtrMemI); 10319 break; 10320 case BO_Mul: 10321 case BO_Div: 10322 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10323 Opc == BO_Div); 10324 break; 10325 case BO_Rem: 10326 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10327 break; 10328 case BO_Add: 10329 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10330 break; 10331 case BO_Sub: 10332 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10333 break; 10334 case BO_Shl: 10335 case BO_Shr: 10336 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10337 break; 10338 case BO_LE: 10339 case BO_LT: 10340 case BO_GE: 10341 case BO_GT: 10342 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10343 break; 10344 case BO_EQ: 10345 case BO_NE: 10346 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10347 break; 10348 case BO_And: 10349 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10350 case BO_Xor: 10351 case BO_Or: 10352 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10353 break; 10354 case BO_LAnd: 10355 case BO_LOr: 10356 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10357 break; 10358 case BO_MulAssign: 10359 case BO_DivAssign: 10360 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10361 Opc == BO_DivAssign); 10362 CompLHSTy = CompResultTy; 10363 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10364 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10365 break; 10366 case BO_RemAssign: 10367 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10368 CompLHSTy = CompResultTy; 10369 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10370 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10371 break; 10372 case BO_AddAssign: 10373 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10374 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10375 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10376 break; 10377 case BO_SubAssign: 10378 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10379 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10380 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10381 break; 10382 case BO_ShlAssign: 10383 case BO_ShrAssign: 10384 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10385 CompLHSTy = CompResultTy; 10386 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10387 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10388 break; 10389 case BO_AndAssign: 10390 case BO_OrAssign: // fallthrough 10391 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10392 case BO_XorAssign: 10393 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, 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_Comma: 10399 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10400 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10401 VK = RHS.get()->getValueKind(); 10402 OK = RHS.get()->getObjectKind(); 10403 } 10404 break; 10405 } 10406 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10407 return ExprError(); 10408 10409 // Check for array bounds violations for both sides of the BinaryOperator 10410 CheckArrayAccess(LHS.get()); 10411 CheckArrayAccess(RHS.get()); 10412 10413 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10414 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10415 &Context.Idents.get("object_setClass"), 10416 SourceLocation(), LookupOrdinaryName); 10417 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10418 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 10419 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10420 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10421 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10422 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10423 } 10424 else 10425 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10426 } 10427 else if (const ObjCIvarRefExpr *OIRE = 10428 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10429 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10430 10431 if (CompResultTy.isNull()) 10432 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10433 OK, OpLoc, FPFeatures.fp_contract); 10434 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10435 OK_ObjCProperty) { 10436 VK = VK_LValue; 10437 OK = LHS.get()->getObjectKind(); 10438 } 10439 return new (Context) CompoundAssignOperator( 10440 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10441 OpLoc, FPFeatures.fp_contract); 10442 } 10443 10444 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10445 /// operators are mixed in a way that suggests that the programmer forgot that 10446 /// comparison operators have higher precedence. The most typical example of 10447 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10448 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10449 SourceLocation OpLoc, Expr *LHSExpr, 10450 Expr *RHSExpr) { 10451 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10452 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10453 10454 // Check that one of the sides is a comparison operator. 10455 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10456 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10457 if (!isLeftComp && !isRightComp) 10458 return; 10459 10460 // Bitwise operations are sometimes used as eager logical ops. 10461 // Don't diagnose this. 10462 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10463 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10464 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 10465 return; 10466 10467 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10468 OpLoc) 10469 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10470 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10471 SourceRange ParensRange = isLeftComp ? 10472 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10473 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10474 10475 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10476 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10477 SuggestParentheses(Self, OpLoc, 10478 Self.PDiag(diag::note_precedence_silence) << OpStr, 10479 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10480 SuggestParentheses(Self, OpLoc, 10481 Self.PDiag(diag::note_precedence_bitwise_first) 10482 << BinaryOperator::getOpcodeStr(Opc), 10483 ParensRange); 10484 } 10485 10486 /// \brief It accepts a '&' expr that is inside a '|' one. 10487 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 10488 /// in parentheses. 10489 static void 10490 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 10491 BinaryOperator *Bop) { 10492 assert(Bop->getOpcode() == BO_And); 10493 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 10494 << Bop->getSourceRange() << OpLoc; 10495 SuggestParentheses(Self, Bop->getOperatorLoc(), 10496 Self.PDiag(diag::note_precedence_silence) 10497 << Bop->getOpcodeStr(), 10498 Bop->getSourceRange()); 10499 } 10500 10501 /// \brief It accepts a '&&' expr that is inside a '||' one. 10502 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10503 /// in parentheses. 10504 static void 10505 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10506 BinaryOperator *Bop) { 10507 assert(Bop->getOpcode() == BO_LAnd); 10508 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10509 << Bop->getSourceRange() << OpLoc; 10510 SuggestParentheses(Self, Bop->getOperatorLoc(), 10511 Self.PDiag(diag::note_precedence_silence) 10512 << Bop->getOpcodeStr(), 10513 Bop->getSourceRange()); 10514 } 10515 10516 /// \brief Returns true if the given expression can be evaluated as a constant 10517 /// 'true'. 10518 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10519 bool Res; 10520 return !E->isValueDependent() && 10521 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10522 } 10523 10524 /// \brief Returns true if the given expression can be evaluated as a constant 10525 /// 'false'. 10526 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10527 bool Res; 10528 return !E->isValueDependent() && 10529 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10530 } 10531 10532 /// \brief Look for '&&' in the left hand of a '||' expr. 10533 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10534 Expr *LHSExpr, Expr *RHSExpr) { 10535 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10536 if (Bop->getOpcode() == BO_LAnd) { 10537 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10538 if (EvaluatesAsFalse(S, RHSExpr)) 10539 return; 10540 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10541 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10542 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10543 } else if (Bop->getOpcode() == BO_LOr) { 10544 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10545 // If it's "a || b && 1 || c" we didn't warn earlier for 10546 // "a || b && 1", but warn now. 10547 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10548 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10549 } 10550 } 10551 } 10552 } 10553 10554 /// \brief Look for '&&' in the right hand of a '||' expr. 10555 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10556 Expr *LHSExpr, Expr *RHSExpr) { 10557 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10558 if (Bop->getOpcode() == BO_LAnd) { 10559 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10560 if (EvaluatesAsFalse(S, LHSExpr)) 10561 return; 10562 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10563 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10564 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10565 } 10566 } 10567 } 10568 10569 /// \brief Look for '&' in the left or right hand of a '|' expr. 10570 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 10571 Expr *OrArg) { 10572 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 10573 if (Bop->getOpcode() == BO_And) 10574 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 10575 } 10576 } 10577 10578 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10579 Expr *SubExpr, StringRef Shift) { 10580 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10581 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10582 StringRef Op = Bop->getOpcodeStr(); 10583 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10584 << Bop->getSourceRange() << OpLoc << Shift << Op; 10585 SuggestParentheses(S, Bop->getOperatorLoc(), 10586 S.PDiag(diag::note_precedence_silence) << Op, 10587 Bop->getSourceRange()); 10588 } 10589 } 10590 } 10591 10592 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10593 Expr *LHSExpr, Expr *RHSExpr) { 10594 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10595 if (!OCE) 10596 return; 10597 10598 FunctionDecl *FD = OCE->getDirectCallee(); 10599 if (!FD || !FD->isOverloadedOperator()) 10600 return; 10601 10602 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10603 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10604 return; 10605 10606 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10607 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10608 << (Kind == OO_LessLess); 10609 SuggestParentheses(S, OCE->getOperatorLoc(), 10610 S.PDiag(diag::note_precedence_silence) 10611 << (Kind == OO_LessLess ? "<<" : ">>"), 10612 OCE->getSourceRange()); 10613 SuggestParentheses(S, OpLoc, 10614 S.PDiag(diag::note_evaluate_comparison_first), 10615 SourceRange(OCE->getArg(1)->getLocStart(), 10616 RHSExpr->getLocEnd())); 10617 } 10618 10619 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10620 /// precedence. 10621 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10622 SourceLocation OpLoc, Expr *LHSExpr, 10623 Expr *RHSExpr){ 10624 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10625 if (BinaryOperator::isBitwiseOp(Opc)) 10626 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10627 10628 // Diagnose "arg1 & arg2 | arg3" 10629 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10630 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 10631 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 10632 } 10633 10634 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10635 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10636 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10637 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10638 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10639 } 10640 10641 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 10642 || Opc == BO_Shr) { 10643 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 10644 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 10645 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 10646 } 10647 10648 // Warn on overloaded shift operators and comparisons, such as: 10649 // cout << 5 == 4; 10650 if (BinaryOperator::isComparisonOp(Opc)) 10651 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 10652 } 10653 10654 // Binary Operators. 'Tok' is the token for the operator. 10655 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 10656 tok::TokenKind Kind, 10657 Expr *LHSExpr, Expr *RHSExpr) { 10658 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 10659 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 10660 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 10661 10662 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 10663 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 10664 10665 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 10666 } 10667 10668 /// Build an overloaded binary operator expression in the given scope. 10669 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 10670 BinaryOperatorKind Opc, 10671 Expr *LHS, Expr *RHS) { 10672 // Find all of the overloaded operators visible from this 10673 // point. We perform both an operator-name lookup from the local 10674 // scope and an argument-dependent lookup based on the types of 10675 // the arguments. 10676 UnresolvedSet<16> Functions; 10677 OverloadedOperatorKind OverOp 10678 = BinaryOperator::getOverloadedOperator(Opc); 10679 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 10680 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 10681 RHS->getType(), Functions); 10682 10683 // Build the (potentially-overloaded, potentially-dependent) 10684 // binary operation. 10685 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 10686 } 10687 10688 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 10689 BinaryOperatorKind Opc, 10690 Expr *LHSExpr, Expr *RHSExpr) { 10691 // We want to end up calling one of checkPseudoObjectAssignment 10692 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 10693 // both expressions are overloadable or either is type-dependent), 10694 // or CreateBuiltinBinOp (in any other case). We also want to get 10695 // any placeholder types out of the way. 10696 10697 // Handle pseudo-objects in the LHS. 10698 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 10699 // Assignments with a pseudo-object l-value need special analysis. 10700 if (pty->getKind() == BuiltinType::PseudoObject && 10701 BinaryOperator::isAssignmentOp(Opc)) 10702 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 10703 10704 // Don't resolve overloads if the other type is overloadable. 10705 if (pty->getKind() == BuiltinType::Overload) { 10706 // We can't actually test that if we still have a placeholder, 10707 // though. Fortunately, none of the exceptions we see in that 10708 // code below are valid when the LHS is an overload set. Note 10709 // that an overload set can be dependently-typed, but it never 10710 // instantiates to having an overloadable type. 10711 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10712 if (resolvedRHS.isInvalid()) return ExprError(); 10713 RHSExpr = resolvedRHS.get(); 10714 10715 if (RHSExpr->isTypeDependent() || 10716 RHSExpr->getType()->isOverloadableType()) 10717 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10718 } 10719 10720 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 10721 if (LHS.isInvalid()) return ExprError(); 10722 LHSExpr = LHS.get(); 10723 } 10724 10725 // Handle pseudo-objects in the RHS. 10726 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 10727 // An overload in the RHS can potentially be resolved by the type 10728 // being assigned to. 10729 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 10730 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10731 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10732 10733 if (LHSExpr->getType()->isOverloadableType()) 10734 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10735 10736 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10737 } 10738 10739 // Don't resolve overloads if the other type is overloadable. 10740 if (pty->getKind() == BuiltinType::Overload && 10741 LHSExpr->getType()->isOverloadableType()) 10742 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10743 10744 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10745 if (!resolvedRHS.isUsable()) return ExprError(); 10746 RHSExpr = resolvedRHS.get(); 10747 } 10748 10749 if (getLangOpts().CPlusPlus) { 10750 // If either expression is type-dependent, always build an 10751 // overloaded op. 10752 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10753 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10754 10755 // Otherwise, build an overloaded op if either expression has an 10756 // overloadable type. 10757 if (LHSExpr->getType()->isOverloadableType() || 10758 RHSExpr->getType()->isOverloadableType()) 10759 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10760 } 10761 10762 // Build a built-in binary operation. 10763 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10764 } 10765 10766 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 10767 UnaryOperatorKind Opc, 10768 Expr *InputExpr) { 10769 ExprResult Input = InputExpr; 10770 ExprValueKind VK = VK_RValue; 10771 ExprObjectKind OK = OK_Ordinary; 10772 QualType resultType; 10773 switch (Opc) { 10774 case UO_PreInc: 10775 case UO_PreDec: 10776 case UO_PostInc: 10777 case UO_PostDec: 10778 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 10779 OpLoc, 10780 Opc == UO_PreInc || 10781 Opc == UO_PostInc, 10782 Opc == UO_PreInc || 10783 Opc == UO_PreDec); 10784 break; 10785 case UO_AddrOf: 10786 resultType = CheckAddressOfOperand(Input, OpLoc); 10787 RecordModifiableNonNullParam(*this, InputExpr); 10788 break; 10789 case UO_Deref: { 10790 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10791 if (Input.isInvalid()) return ExprError(); 10792 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 10793 break; 10794 } 10795 case UO_Plus: 10796 case UO_Minus: 10797 Input = UsualUnaryConversions(Input.get()); 10798 if (Input.isInvalid()) return ExprError(); 10799 resultType = Input.get()->getType(); 10800 if (resultType->isDependentType()) 10801 break; 10802 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 10803 break; 10804 else if (resultType->isVectorType() && 10805 // The z vector extensions don't allow + or - with bool vectors. 10806 (!Context.getLangOpts().ZVector || 10807 resultType->getAs<VectorType>()->getVectorKind() != 10808 VectorType::AltiVecBool)) 10809 break; 10810 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 10811 Opc == UO_Plus && 10812 resultType->isPointerType()) 10813 break; 10814 10815 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10816 << resultType << Input.get()->getSourceRange()); 10817 10818 case UO_Not: // bitwise complement 10819 Input = UsualUnaryConversions(Input.get()); 10820 if (Input.isInvalid()) 10821 return ExprError(); 10822 resultType = Input.get()->getType(); 10823 if (resultType->isDependentType()) 10824 break; 10825 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 10826 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 10827 // C99 does not support '~' for complex conjugation. 10828 Diag(OpLoc, diag::ext_integer_complement_complex) 10829 << resultType << Input.get()->getSourceRange(); 10830 else if (resultType->hasIntegerRepresentation()) 10831 break; 10832 else if (resultType->isExtVectorType()) { 10833 if (Context.getLangOpts().OpenCL) { 10834 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 10835 // on vector float types. 10836 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10837 if (!T->isIntegerType()) 10838 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10839 << resultType << Input.get()->getSourceRange()); 10840 } 10841 break; 10842 } else { 10843 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10844 << resultType << Input.get()->getSourceRange()); 10845 } 10846 break; 10847 10848 case UO_LNot: // logical negation 10849 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 10850 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10851 if (Input.isInvalid()) return ExprError(); 10852 resultType = Input.get()->getType(); 10853 10854 // Though we still have to promote half FP to float... 10855 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 10856 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 10857 resultType = Context.FloatTy; 10858 } 10859 10860 if (resultType->isDependentType()) 10861 break; 10862 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 10863 // C99 6.5.3.3p1: ok, fallthrough; 10864 if (Context.getLangOpts().CPlusPlus) { 10865 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 10866 // operand contextually converted to bool. 10867 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 10868 ScalarTypeToBooleanCastKind(resultType)); 10869 } else if (Context.getLangOpts().OpenCL && 10870 Context.getLangOpts().OpenCLVersion < 120) { 10871 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10872 // operate on scalar float types. 10873 if (!resultType->isIntegerType()) 10874 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10875 << resultType << Input.get()->getSourceRange()); 10876 } 10877 } else if (resultType->isExtVectorType()) { 10878 if (Context.getLangOpts().OpenCL && 10879 Context.getLangOpts().OpenCLVersion < 120) { 10880 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10881 // operate on vector float types. 10882 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10883 if (!T->isIntegerType()) 10884 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10885 << resultType << Input.get()->getSourceRange()); 10886 } 10887 // Vector logical not returns the signed variant of the operand type. 10888 resultType = GetSignedVectorType(resultType); 10889 break; 10890 } else { 10891 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10892 << resultType << Input.get()->getSourceRange()); 10893 } 10894 10895 // LNot always has type int. C99 6.5.3.3p5. 10896 // In C++, it's bool. C++ 5.3.1p8 10897 resultType = Context.getLogicalOperationType(); 10898 break; 10899 case UO_Real: 10900 case UO_Imag: 10901 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 10902 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 10903 // complex l-values to ordinary l-values and all other values to r-values. 10904 if (Input.isInvalid()) return ExprError(); 10905 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 10906 if (Input.get()->getValueKind() != VK_RValue && 10907 Input.get()->getObjectKind() == OK_Ordinary) 10908 VK = Input.get()->getValueKind(); 10909 } else if (!getLangOpts().CPlusPlus) { 10910 // In C, a volatile scalar is read by __imag. In C++, it is not. 10911 Input = DefaultLvalueConversion(Input.get()); 10912 } 10913 break; 10914 case UO_Extension: 10915 resultType = Input.get()->getType(); 10916 VK = Input.get()->getValueKind(); 10917 OK = Input.get()->getObjectKind(); 10918 break; 10919 } 10920 if (resultType.isNull() || Input.isInvalid()) 10921 return ExprError(); 10922 10923 // Check for array bounds violations in the operand of the UnaryOperator, 10924 // except for the '*' and '&' operators that have to be handled specially 10925 // by CheckArrayAccess (as there are special cases like &array[arraysize] 10926 // that are explicitly defined as valid by the standard). 10927 if (Opc != UO_AddrOf && Opc != UO_Deref) 10928 CheckArrayAccess(Input.get()); 10929 10930 return new (Context) 10931 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 10932 } 10933 10934 /// \brief Determine whether the given expression is a qualified member 10935 /// access expression, of a form that could be turned into a pointer to member 10936 /// with the address-of operator. 10937 static bool isQualifiedMemberAccess(Expr *E) { 10938 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10939 if (!DRE->getQualifier()) 10940 return false; 10941 10942 ValueDecl *VD = DRE->getDecl(); 10943 if (!VD->isCXXClassMember()) 10944 return false; 10945 10946 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 10947 return true; 10948 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 10949 return Method->isInstance(); 10950 10951 return false; 10952 } 10953 10954 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 10955 if (!ULE->getQualifier()) 10956 return false; 10957 10958 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 10959 DEnd = ULE->decls_end(); 10960 D != DEnd; ++D) { 10961 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 10962 if (Method->isInstance()) 10963 return true; 10964 } else { 10965 // Overload set does not contain methods. 10966 break; 10967 } 10968 } 10969 10970 return false; 10971 } 10972 10973 return false; 10974 } 10975 10976 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 10977 UnaryOperatorKind Opc, Expr *Input) { 10978 // First things first: handle placeholders so that the 10979 // overloaded-operator check considers the right type. 10980 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 10981 // Increment and decrement of pseudo-object references. 10982 if (pty->getKind() == BuiltinType::PseudoObject && 10983 UnaryOperator::isIncrementDecrementOp(Opc)) 10984 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 10985 10986 // extension is always a builtin operator. 10987 if (Opc == UO_Extension) 10988 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10989 10990 // & gets special logic for several kinds of placeholder. 10991 // The builtin code knows what to do. 10992 if (Opc == UO_AddrOf && 10993 (pty->getKind() == BuiltinType::Overload || 10994 pty->getKind() == BuiltinType::UnknownAny || 10995 pty->getKind() == BuiltinType::BoundMember)) 10996 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10997 10998 // Anything else needs to be handled now. 10999 ExprResult Result = CheckPlaceholderExpr(Input); 11000 if (Result.isInvalid()) return ExprError(); 11001 Input = Result.get(); 11002 } 11003 11004 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11005 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11006 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11007 // Find all of the overloaded operators visible from this 11008 // point. We perform both an operator-name lookup from the local 11009 // scope and an argument-dependent lookup based on the types of 11010 // the arguments. 11011 UnresolvedSet<16> Functions; 11012 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11013 if (S && OverOp != OO_None) 11014 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11015 Functions); 11016 11017 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11018 } 11019 11020 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11021 } 11022 11023 // Unary Operators. 'Tok' is the token for the operator. 11024 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11025 tok::TokenKind Op, Expr *Input) { 11026 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11027 } 11028 11029 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11030 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11031 LabelDecl *TheDecl) { 11032 TheDecl->markUsed(Context); 11033 // Create the AST node. The address of a label always has type 'void*'. 11034 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11035 Context.getPointerType(Context.VoidTy)); 11036 } 11037 11038 /// Given the last statement in a statement-expression, check whether 11039 /// the result is a producing expression (like a call to an 11040 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11041 /// release out of the full-expression. Otherwise, return null. 11042 /// Cannot fail. 11043 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11044 // Should always be wrapped with one of these. 11045 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11046 if (!cleanups) return nullptr; 11047 11048 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11049 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11050 return nullptr; 11051 11052 // Splice out the cast. This shouldn't modify any interesting 11053 // features of the statement. 11054 Expr *producer = cast->getSubExpr(); 11055 assert(producer->getType() == cast->getType()); 11056 assert(producer->getValueKind() == cast->getValueKind()); 11057 cleanups->setSubExpr(producer); 11058 return cleanups; 11059 } 11060 11061 void Sema::ActOnStartStmtExpr() { 11062 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11063 } 11064 11065 void Sema::ActOnStmtExprError() { 11066 // Note that function is also called by TreeTransform when leaving a 11067 // StmtExpr scope without rebuilding anything. 11068 11069 DiscardCleanupsInEvaluationContext(); 11070 PopExpressionEvaluationContext(); 11071 } 11072 11073 ExprResult 11074 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11075 SourceLocation RPLoc) { // "({..})" 11076 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11077 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11078 11079 if (hasAnyUnrecoverableErrorsInThisFunction()) 11080 DiscardCleanupsInEvaluationContext(); 11081 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11082 PopExpressionEvaluationContext(); 11083 11084 // FIXME: there are a variety of strange constraints to enforce here, for 11085 // example, it is not possible to goto into a stmt expression apparently. 11086 // More semantic analysis is needed. 11087 11088 // If there are sub-stmts in the compound stmt, take the type of the last one 11089 // as the type of the stmtexpr. 11090 QualType Ty = Context.VoidTy; 11091 bool StmtExprMayBindToTemp = false; 11092 if (!Compound->body_empty()) { 11093 Stmt *LastStmt = Compound->body_back(); 11094 LabelStmt *LastLabelStmt = nullptr; 11095 // If LastStmt is a label, skip down through into the body. 11096 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11097 LastLabelStmt = Label; 11098 LastStmt = Label->getSubStmt(); 11099 } 11100 11101 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11102 // Do function/array conversion on the last expression, but not 11103 // lvalue-to-rvalue. However, initialize an unqualified type. 11104 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11105 if (LastExpr.isInvalid()) 11106 return ExprError(); 11107 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11108 11109 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11110 // In ARC, if the final expression ends in a consume, splice 11111 // the consume out and bind it later. In the alternate case 11112 // (when dealing with a retainable type), the result 11113 // initialization will create a produce. In both cases the 11114 // result will be +1, and we'll need to balance that out with 11115 // a bind. 11116 if (Expr *rebuiltLastStmt 11117 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11118 LastExpr = rebuiltLastStmt; 11119 } else { 11120 LastExpr = PerformCopyInitialization( 11121 InitializedEntity::InitializeResult(LPLoc, 11122 Ty, 11123 false), 11124 SourceLocation(), 11125 LastExpr); 11126 } 11127 11128 if (LastExpr.isInvalid()) 11129 return ExprError(); 11130 if (LastExpr.get() != nullptr) { 11131 if (!LastLabelStmt) 11132 Compound->setLastStmt(LastExpr.get()); 11133 else 11134 LastLabelStmt->setSubStmt(LastExpr.get()); 11135 StmtExprMayBindToTemp = true; 11136 } 11137 } 11138 } 11139 } 11140 11141 // FIXME: Check that expression type is complete/non-abstract; statement 11142 // expressions are not lvalues. 11143 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11144 if (StmtExprMayBindToTemp) 11145 return MaybeBindToTemporary(ResStmtExpr); 11146 return ResStmtExpr; 11147 } 11148 11149 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11150 TypeSourceInfo *TInfo, 11151 OffsetOfComponent *CompPtr, 11152 unsigned NumComponents, 11153 SourceLocation RParenLoc) { 11154 QualType ArgTy = TInfo->getType(); 11155 bool Dependent = ArgTy->isDependentType(); 11156 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11157 11158 // We must have at least one component that refers to the type, and the first 11159 // one is known to be a field designator. Verify that the ArgTy represents 11160 // a struct/union/class. 11161 if (!Dependent && !ArgTy->isRecordType()) 11162 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11163 << ArgTy << TypeRange); 11164 11165 // Type must be complete per C99 7.17p3 because a declaring a variable 11166 // with an incomplete type would be ill-formed. 11167 if (!Dependent 11168 && RequireCompleteType(BuiltinLoc, ArgTy, 11169 diag::err_offsetof_incomplete_type, TypeRange)) 11170 return ExprError(); 11171 11172 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11173 // GCC extension, diagnose them. 11174 // FIXME: This diagnostic isn't actually visible because the location is in 11175 // a system header! 11176 if (NumComponents != 1) 11177 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11178 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 11179 11180 bool DidWarnAboutNonPOD = false; 11181 QualType CurrentType = ArgTy; 11182 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 11183 SmallVector<OffsetOfNode, 4> Comps; 11184 SmallVector<Expr*, 4> Exprs; 11185 for (unsigned i = 0; i != NumComponents; ++i) { 11186 const OffsetOfComponent &OC = CompPtr[i]; 11187 if (OC.isBrackets) { 11188 // Offset of an array sub-field. TODO: Should we allow vector elements? 11189 if (!CurrentType->isDependentType()) { 11190 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11191 if(!AT) 11192 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11193 << CurrentType); 11194 CurrentType = AT->getElementType(); 11195 } else 11196 CurrentType = Context.DependentTy; 11197 11198 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11199 if (IdxRval.isInvalid()) 11200 return ExprError(); 11201 Expr *Idx = IdxRval.get(); 11202 11203 // The expression must be an integral expression. 11204 // FIXME: An integral constant expression? 11205 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11206 !Idx->getType()->isIntegerType()) 11207 return ExprError(Diag(Idx->getLocStart(), 11208 diag::err_typecheck_subscript_not_integer) 11209 << Idx->getSourceRange()); 11210 11211 // Record this array index. 11212 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11213 Exprs.push_back(Idx); 11214 continue; 11215 } 11216 11217 // Offset of a field. 11218 if (CurrentType->isDependentType()) { 11219 // We have the offset of a field, but we can't look into the dependent 11220 // type. Just record the identifier of the field. 11221 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11222 CurrentType = Context.DependentTy; 11223 continue; 11224 } 11225 11226 // We need to have a complete type to look into. 11227 if (RequireCompleteType(OC.LocStart, CurrentType, 11228 diag::err_offsetof_incomplete_type)) 11229 return ExprError(); 11230 11231 // Look for the designated field. 11232 const RecordType *RC = CurrentType->getAs<RecordType>(); 11233 if (!RC) 11234 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11235 << CurrentType); 11236 RecordDecl *RD = RC->getDecl(); 11237 11238 // C++ [lib.support.types]p5: 11239 // The macro offsetof accepts a restricted set of type arguments in this 11240 // International Standard. type shall be a POD structure or a POD union 11241 // (clause 9). 11242 // C++11 [support.types]p4: 11243 // If type is not a standard-layout class (Clause 9), the results are 11244 // undefined. 11245 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11246 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11247 unsigned DiagID = 11248 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11249 : diag::ext_offsetof_non_pod_type; 11250 11251 if (!IsSafe && !DidWarnAboutNonPOD && 11252 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11253 PDiag(DiagID) 11254 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 11255 << CurrentType)) 11256 DidWarnAboutNonPOD = true; 11257 } 11258 11259 // Look for the field. 11260 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11261 LookupQualifiedName(R, RD); 11262 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11263 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11264 if (!MemberDecl) { 11265 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11266 MemberDecl = IndirectMemberDecl->getAnonField(); 11267 } 11268 11269 if (!MemberDecl) 11270 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11271 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11272 OC.LocEnd)); 11273 11274 // C99 7.17p3: 11275 // (If the specified member is a bit-field, the behavior is undefined.) 11276 // 11277 // We diagnose this as an error. 11278 if (MemberDecl->isBitField()) { 11279 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11280 << MemberDecl->getDeclName() 11281 << SourceRange(BuiltinLoc, RParenLoc); 11282 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11283 return ExprError(); 11284 } 11285 11286 RecordDecl *Parent = MemberDecl->getParent(); 11287 if (IndirectMemberDecl) 11288 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11289 11290 // If the member was found in a base class, introduce OffsetOfNodes for 11291 // the base class indirections. 11292 CXXBasePaths Paths; 11293 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 11294 if (Paths.getDetectedVirtual()) { 11295 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11296 << MemberDecl->getDeclName() 11297 << SourceRange(BuiltinLoc, RParenLoc); 11298 return ExprError(); 11299 } 11300 11301 CXXBasePath &Path = Paths.front(); 11302 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 11303 B != BEnd; ++B) 11304 Comps.push_back(OffsetOfNode(B->Base)); 11305 } 11306 11307 if (IndirectMemberDecl) { 11308 for (auto *FI : IndirectMemberDecl->chain()) { 11309 assert(isa<FieldDecl>(FI)); 11310 Comps.push_back(OffsetOfNode(OC.LocStart, 11311 cast<FieldDecl>(FI), OC.LocEnd)); 11312 } 11313 } else 11314 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11315 11316 CurrentType = MemberDecl->getType().getNonReferenceType(); 11317 } 11318 11319 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11320 Comps, Exprs, RParenLoc); 11321 } 11322 11323 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11324 SourceLocation BuiltinLoc, 11325 SourceLocation TypeLoc, 11326 ParsedType ParsedArgTy, 11327 OffsetOfComponent *CompPtr, 11328 unsigned NumComponents, 11329 SourceLocation RParenLoc) { 11330 11331 TypeSourceInfo *ArgTInfo; 11332 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11333 if (ArgTy.isNull()) 11334 return ExprError(); 11335 11336 if (!ArgTInfo) 11337 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11338 11339 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 11340 RParenLoc); 11341 } 11342 11343 11344 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11345 Expr *CondExpr, 11346 Expr *LHSExpr, Expr *RHSExpr, 11347 SourceLocation RPLoc) { 11348 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11349 11350 ExprValueKind VK = VK_RValue; 11351 ExprObjectKind OK = OK_Ordinary; 11352 QualType resType; 11353 bool ValueDependent = false; 11354 bool CondIsTrue = false; 11355 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11356 resType = Context.DependentTy; 11357 ValueDependent = true; 11358 } else { 11359 // The conditional expression is required to be a constant expression. 11360 llvm::APSInt condEval(32); 11361 ExprResult CondICE 11362 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11363 diag::err_typecheck_choose_expr_requires_constant, false); 11364 if (CondICE.isInvalid()) 11365 return ExprError(); 11366 CondExpr = CondICE.get(); 11367 CondIsTrue = condEval.getZExtValue(); 11368 11369 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11370 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11371 11372 resType = ActiveExpr->getType(); 11373 ValueDependent = ActiveExpr->isValueDependent(); 11374 VK = ActiveExpr->getValueKind(); 11375 OK = ActiveExpr->getObjectKind(); 11376 } 11377 11378 return new (Context) 11379 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11380 CondIsTrue, resType->isDependentType(), ValueDependent); 11381 } 11382 11383 //===----------------------------------------------------------------------===// 11384 // Clang Extensions. 11385 //===----------------------------------------------------------------------===// 11386 11387 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11388 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11389 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11390 11391 if (LangOpts.CPlusPlus) { 11392 Decl *ManglingContextDecl; 11393 if (MangleNumberingContext *MCtx = 11394 getCurrentMangleNumberContext(Block->getDeclContext(), 11395 ManglingContextDecl)) { 11396 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11397 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11398 } 11399 } 11400 11401 PushBlockScope(CurScope, Block); 11402 CurContext->addDecl(Block); 11403 if (CurScope) 11404 PushDeclContext(CurScope, Block); 11405 else 11406 CurContext = Block; 11407 11408 getCurBlock()->HasImplicitReturnType = true; 11409 11410 // Enter a new evaluation context to insulate the block from any 11411 // cleanups from the enclosing full-expression. 11412 PushExpressionEvaluationContext(PotentiallyEvaluated); 11413 } 11414 11415 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11416 Scope *CurScope) { 11417 assert(ParamInfo.getIdentifier() == nullptr && 11418 "block-id should have no identifier!"); 11419 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11420 BlockScopeInfo *CurBlock = getCurBlock(); 11421 11422 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11423 QualType T = Sig->getType(); 11424 11425 // FIXME: We should allow unexpanded parameter packs here, but that would, 11426 // in turn, make the block expression contain unexpanded parameter packs. 11427 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11428 // Drop the parameters. 11429 FunctionProtoType::ExtProtoInfo EPI; 11430 EPI.HasTrailingReturn = false; 11431 EPI.TypeQuals |= DeclSpec::TQ_const; 11432 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11433 Sig = Context.getTrivialTypeSourceInfo(T); 11434 } 11435 11436 // GetTypeForDeclarator always produces a function type for a block 11437 // literal signature. Furthermore, it is always a FunctionProtoType 11438 // unless the function was written with a typedef. 11439 assert(T->isFunctionType() && 11440 "GetTypeForDeclarator made a non-function block signature"); 11441 11442 // Look for an explicit signature in that function type. 11443 FunctionProtoTypeLoc ExplicitSignature; 11444 11445 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11446 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11447 11448 // Check whether that explicit signature was synthesized by 11449 // GetTypeForDeclarator. If so, don't save that as part of the 11450 // written signature. 11451 if (ExplicitSignature.getLocalRangeBegin() == 11452 ExplicitSignature.getLocalRangeEnd()) { 11453 // This would be much cheaper if we stored TypeLocs instead of 11454 // TypeSourceInfos. 11455 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11456 unsigned Size = Result.getFullDataSize(); 11457 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11458 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11459 11460 ExplicitSignature = FunctionProtoTypeLoc(); 11461 } 11462 } 11463 11464 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11465 CurBlock->FunctionType = T; 11466 11467 const FunctionType *Fn = T->getAs<FunctionType>(); 11468 QualType RetTy = Fn->getReturnType(); 11469 bool isVariadic = 11470 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11471 11472 CurBlock->TheDecl->setIsVariadic(isVariadic); 11473 11474 // Context.DependentTy is used as a placeholder for a missing block 11475 // return type. TODO: what should we do with declarators like: 11476 // ^ * { ... } 11477 // If the answer is "apply template argument deduction".... 11478 if (RetTy != Context.DependentTy) { 11479 CurBlock->ReturnType = RetTy; 11480 CurBlock->TheDecl->setBlockMissingReturnType(false); 11481 CurBlock->HasImplicitReturnType = false; 11482 } 11483 11484 // Push block parameters from the declarator if we had them. 11485 SmallVector<ParmVarDecl*, 8> Params; 11486 if (ExplicitSignature) { 11487 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11488 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11489 if (Param->getIdentifier() == nullptr && 11490 !Param->isImplicit() && 11491 !Param->isInvalidDecl() && 11492 !getLangOpts().CPlusPlus) 11493 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11494 Params.push_back(Param); 11495 } 11496 11497 // Fake up parameter variables if we have a typedef, like 11498 // ^ fntype { ... } 11499 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11500 for (const auto &I : Fn->param_types()) { 11501 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11502 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11503 Params.push_back(Param); 11504 } 11505 } 11506 11507 // Set the parameters on the block decl. 11508 if (!Params.empty()) { 11509 CurBlock->TheDecl->setParams(Params); 11510 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11511 CurBlock->TheDecl->param_end(), 11512 /*CheckParameterNames=*/false); 11513 } 11514 11515 // Finally we can process decl attributes. 11516 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11517 11518 // Put the parameter variables in scope. 11519 for (auto AI : CurBlock->TheDecl->params()) { 11520 AI->setOwningFunction(CurBlock->TheDecl); 11521 11522 // If this has an identifier, add it to the scope stack. 11523 if (AI->getIdentifier()) { 11524 CheckShadow(CurBlock->TheScope, AI); 11525 11526 PushOnScopeChains(AI, CurBlock->TheScope); 11527 } 11528 } 11529 } 11530 11531 /// ActOnBlockError - If there is an error parsing a block, this callback 11532 /// is invoked to pop the information about the block from the action impl. 11533 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11534 // Leave the expression-evaluation context. 11535 DiscardCleanupsInEvaluationContext(); 11536 PopExpressionEvaluationContext(); 11537 11538 // Pop off CurBlock, handle nested blocks. 11539 PopDeclContext(); 11540 PopFunctionScopeInfo(); 11541 } 11542 11543 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11544 /// literal was successfully completed. ^(int x){...} 11545 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11546 Stmt *Body, Scope *CurScope) { 11547 // If blocks are disabled, emit an error. 11548 if (!LangOpts.Blocks) 11549 Diag(CaretLoc, diag::err_blocks_disable); 11550 11551 // Leave the expression-evaluation context. 11552 if (hasAnyUnrecoverableErrorsInThisFunction()) 11553 DiscardCleanupsInEvaluationContext(); 11554 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11555 PopExpressionEvaluationContext(); 11556 11557 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11558 11559 if (BSI->HasImplicitReturnType) 11560 deduceClosureReturnType(*BSI); 11561 11562 PopDeclContext(); 11563 11564 QualType RetTy = Context.VoidTy; 11565 if (!BSI->ReturnType.isNull()) 11566 RetTy = BSI->ReturnType; 11567 11568 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11569 QualType BlockTy; 11570 11571 // Set the captured variables on the block. 11572 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11573 SmallVector<BlockDecl::Capture, 4> Captures; 11574 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 11575 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 11576 if (Cap.isThisCapture()) 11577 continue; 11578 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11579 Cap.isNested(), Cap.getInitExpr()); 11580 Captures.push_back(NewCap); 11581 } 11582 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 11583 11584 // If the user wrote a function type in some form, try to use that. 11585 if (!BSI->FunctionType.isNull()) { 11586 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11587 11588 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11589 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11590 11591 // Turn protoless block types into nullary block types. 11592 if (isa<FunctionNoProtoType>(FTy)) { 11593 FunctionProtoType::ExtProtoInfo EPI; 11594 EPI.ExtInfo = Ext; 11595 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11596 11597 // Otherwise, if we don't need to change anything about the function type, 11598 // preserve its sugar structure. 11599 } else if (FTy->getReturnType() == RetTy && 11600 (!NoReturn || FTy->getNoReturnAttr())) { 11601 BlockTy = BSI->FunctionType; 11602 11603 // Otherwise, make the minimal modifications to the function type. 11604 } else { 11605 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11606 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11607 EPI.TypeQuals = 0; // FIXME: silently? 11608 EPI.ExtInfo = Ext; 11609 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11610 } 11611 11612 // If we don't have a function type, just build one from nothing. 11613 } else { 11614 FunctionProtoType::ExtProtoInfo EPI; 11615 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11616 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11617 } 11618 11619 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11620 BSI->TheDecl->param_end()); 11621 BlockTy = Context.getBlockPointerType(BlockTy); 11622 11623 // If needed, diagnose invalid gotos and switches in the block. 11624 if (getCurFunction()->NeedsScopeChecking() && 11625 !PP.isCodeCompletionEnabled()) 11626 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11627 11628 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11629 11630 // Try to apply the named return value optimization. We have to check again 11631 // if we can do this, though, because blocks keep return statements around 11632 // to deduce an implicit return type. 11633 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11634 !BSI->TheDecl->isDependentContext()) 11635 computeNRVO(Body, BSI); 11636 11637 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11638 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11639 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11640 11641 // If the block isn't obviously global, i.e. it captures anything at 11642 // all, then we need to do a few things in the surrounding context: 11643 if (Result->getBlockDecl()->hasCaptures()) { 11644 // First, this expression has a new cleanup object. 11645 ExprCleanupObjects.push_back(Result->getBlockDecl()); 11646 ExprNeedsCleanups = true; 11647 11648 // It also gets a branch-protected scope if any of the captured 11649 // variables needs destruction. 11650 for (const auto &CI : Result->getBlockDecl()->captures()) { 11651 const VarDecl *var = CI.getVariable(); 11652 if (var->getType().isDestructedType() != QualType::DK_none) { 11653 getCurFunction()->setHasBranchProtectedScope(); 11654 break; 11655 } 11656 } 11657 } 11658 11659 return Result; 11660 } 11661 11662 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 11663 Expr *E, ParsedType Ty, 11664 SourceLocation RPLoc) { 11665 TypeSourceInfo *TInfo; 11666 GetTypeFromParser(Ty, &TInfo); 11667 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 11668 } 11669 11670 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 11671 Expr *E, TypeSourceInfo *TInfo, 11672 SourceLocation RPLoc) { 11673 Expr *OrigExpr = E; 11674 bool IsMS = false; 11675 11676 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 11677 // as Microsoft ABI on an actual Microsoft platform, where 11678 // __builtin_ms_va_list and __builtin_va_list are the same.) 11679 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 11680 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 11681 QualType MSVaListType = Context.getBuiltinMSVaListType(); 11682 if (Context.hasSameType(MSVaListType, E->getType())) { 11683 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11684 return ExprError(); 11685 IsMS = true; 11686 } 11687 } 11688 11689 // Get the va_list type 11690 QualType VaListType = Context.getBuiltinVaListType(); 11691 if (!IsMS) { 11692 if (VaListType->isArrayType()) { 11693 // Deal with implicit array decay; for example, on x86-64, 11694 // va_list is an array, but it's supposed to decay to 11695 // a pointer for va_arg. 11696 VaListType = Context.getArrayDecayedType(VaListType); 11697 // Make sure the input expression also decays appropriately. 11698 ExprResult Result = UsualUnaryConversions(E); 11699 if (Result.isInvalid()) 11700 return ExprError(); 11701 E = Result.get(); 11702 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 11703 // If va_list is a record type and we are compiling in C++ mode, 11704 // check the argument using reference binding. 11705 InitializedEntity Entity = InitializedEntity::InitializeParameter( 11706 Context, Context.getLValueReferenceType(VaListType), false); 11707 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 11708 if (Init.isInvalid()) 11709 return ExprError(); 11710 E = Init.getAs<Expr>(); 11711 } else { 11712 // Otherwise, the va_list argument must be an l-value because 11713 // it is modified by va_arg. 11714 if (!E->isTypeDependent() && 11715 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11716 return ExprError(); 11717 } 11718 } 11719 11720 if (!IsMS && !E->isTypeDependent() && 11721 !Context.hasSameType(VaListType, E->getType())) 11722 return ExprError(Diag(E->getLocStart(), 11723 diag::err_first_argument_to_va_arg_not_of_type_va_list) 11724 << OrigExpr->getType() << E->getSourceRange()); 11725 11726 if (!TInfo->getType()->isDependentType()) { 11727 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 11728 diag::err_second_parameter_to_va_arg_incomplete, 11729 TInfo->getTypeLoc())) 11730 return ExprError(); 11731 11732 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 11733 TInfo->getType(), 11734 diag::err_second_parameter_to_va_arg_abstract, 11735 TInfo->getTypeLoc())) 11736 return ExprError(); 11737 11738 if (!TInfo->getType().isPODType(Context)) { 11739 Diag(TInfo->getTypeLoc().getBeginLoc(), 11740 TInfo->getType()->isObjCLifetimeType() 11741 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 11742 : diag::warn_second_parameter_to_va_arg_not_pod) 11743 << TInfo->getType() 11744 << TInfo->getTypeLoc().getSourceRange(); 11745 } 11746 11747 // Check for va_arg where arguments of the given type will be promoted 11748 // (i.e. this va_arg is guaranteed to have undefined behavior). 11749 QualType PromoteType; 11750 if (TInfo->getType()->isPromotableIntegerType()) { 11751 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 11752 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 11753 PromoteType = QualType(); 11754 } 11755 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 11756 PromoteType = Context.DoubleTy; 11757 if (!PromoteType.isNull()) 11758 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 11759 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 11760 << TInfo->getType() 11761 << PromoteType 11762 << TInfo->getTypeLoc().getSourceRange()); 11763 } 11764 11765 QualType T = TInfo->getType().getNonLValueExprType(Context); 11766 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 11767 } 11768 11769 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 11770 // The type of __null will be int or long, depending on the size of 11771 // pointers on the target. 11772 QualType Ty; 11773 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 11774 if (pw == Context.getTargetInfo().getIntWidth()) 11775 Ty = Context.IntTy; 11776 else if (pw == Context.getTargetInfo().getLongWidth()) 11777 Ty = Context.LongTy; 11778 else if (pw == Context.getTargetInfo().getLongLongWidth()) 11779 Ty = Context.LongLongTy; 11780 else { 11781 llvm_unreachable("I don't know size of pointer!"); 11782 } 11783 11784 return new (Context) GNUNullExpr(Ty, TokenLoc); 11785 } 11786 11787 bool 11788 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 11789 if (!getLangOpts().ObjC1) 11790 return false; 11791 11792 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 11793 if (!PT) 11794 return false; 11795 11796 if (!PT->isObjCIdType()) { 11797 // Check if the destination is the 'NSString' interface. 11798 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 11799 if (!ID || !ID->getIdentifier()->isStr("NSString")) 11800 return false; 11801 } 11802 11803 // Ignore any parens, implicit casts (should only be 11804 // array-to-pointer decays), and not-so-opaque values. The last is 11805 // important for making this trigger for property assignments. 11806 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 11807 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 11808 if (OV->getSourceExpr()) 11809 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 11810 11811 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 11812 if (!SL || !SL->isAscii()) 11813 return false; 11814 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 11815 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 11816 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 11817 return true; 11818 } 11819 11820 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 11821 SourceLocation Loc, 11822 QualType DstType, QualType SrcType, 11823 Expr *SrcExpr, AssignmentAction Action, 11824 bool *Complained) { 11825 if (Complained) 11826 *Complained = false; 11827 11828 // Decode the result (notice that AST's are still created for extensions). 11829 bool CheckInferredResultType = false; 11830 bool isInvalid = false; 11831 unsigned DiagKind = 0; 11832 FixItHint Hint; 11833 ConversionFixItGenerator ConvHints; 11834 bool MayHaveConvFixit = false; 11835 bool MayHaveFunctionDiff = false; 11836 const ObjCInterfaceDecl *IFace = nullptr; 11837 const ObjCProtocolDecl *PDecl = nullptr; 11838 11839 switch (ConvTy) { 11840 case Compatible: 11841 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 11842 return false; 11843 11844 case PointerToInt: 11845 DiagKind = diag::ext_typecheck_convert_pointer_int; 11846 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11847 MayHaveConvFixit = true; 11848 break; 11849 case IntToPointer: 11850 DiagKind = diag::ext_typecheck_convert_int_pointer; 11851 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11852 MayHaveConvFixit = true; 11853 break; 11854 case IncompatiblePointer: 11855 DiagKind = 11856 (Action == AA_Passing_CFAudited ? 11857 diag::err_arc_typecheck_convert_incompatible_pointer : 11858 diag::ext_typecheck_convert_incompatible_pointer); 11859 CheckInferredResultType = DstType->isObjCObjectPointerType() && 11860 SrcType->isObjCObjectPointerType(); 11861 if (Hint.isNull() && !CheckInferredResultType) { 11862 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11863 } 11864 else if (CheckInferredResultType) { 11865 SrcType = SrcType.getUnqualifiedType(); 11866 DstType = DstType.getUnqualifiedType(); 11867 } 11868 MayHaveConvFixit = true; 11869 break; 11870 case IncompatiblePointerSign: 11871 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 11872 break; 11873 case FunctionVoidPointer: 11874 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 11875 break; 11876 case IncompatiblePointerDiscardsQualifiers: { 11877 // Perform array-to-pointer decay if necessary. 11878 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 11879 11880 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 11881 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 11882 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 11883 DiagKind = diag::err_typecheck_incompatible_address_space; 11884 break; 11885 11886 11887 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 11888 DiagKind = diag::err_typecheck_incompatible_ownership; 11889 break; 11890 } 11891 11892 llvm_unreachable("unknown error case for discarding qualifiers!"); 11893 // fallthrough 11894 } 11895 case CompatiblePointerDiscardsQualifiers: 11896 // If the qualifiers lost were because we were applying the 11897 // (deprecated) C++ conversion from a string literal to a char* 11898 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 11899 // Ideally, this check would be performed in 11900 // checkPointerTypesForAssignment. However, that would require a 11901 // bit of refactoring (so that the second argument is an 11902 // expression, rather than a type), which should be done as part 11903 // of a larger effort to fix checkPointerTypesForAssignment for 11904 // C++ semantics. 11905 if (getLangOpts().CPlusPlus && 11906 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 11907 return false; 11908 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 11909 break; 11910 case IncompatibleNestedPointerQualifiers: 11911 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 11912 break; 11913 case IntToBlockPointer: 11914 DiagKind = diag::err_int_to_block_pointer; 11915 break; 11916 case IncompatibleBlockPointer: 11917 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 11918 break; 11919 case IncompatibleObjCQualifiedId: { 11920 if (SrcType->isObjCQualifiedIdType()) { 11921 const ObjCObjectPointerType *srcOPT = 11922 SrcType->getAs<ObjCObjectPointerType>(); 11923 for (auto *srcProto : srcOPT->quals()) { 11924 PDecl = srcProto; 11925 break; 11926 } 11927 if (const ObjCInterfaceType *IFaceT = 11928 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11929 IFace = IFaceT->getDecl(); 11930 } 11931 else if (DstType->isObjCQualifiedIdType()) { 11932 const ObjCObjectPointerType *dstOPT = 11933 DstType->getAs<ObjCObjectPointerType>(); 11934 for (auto *dstProto : dstOPT->quals()) { 11935 PDecl = dstProto; 11936 break; 11937 } 11938 if (const ObjCInterfaceType *IFaceT = 11939 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11940 IFace = IFaceT->getDecl(); 11941 } 11942 DiagKind = diag::warn_incompatible_qualified_id; 11943 break; 11944 } 11945 case IncompatibleVectors: 11946 DiagKind = diag::warn_incompatible_vectors; 11947 break; 11948 case IncompatibleObjCWeakRef: 11949 DiagKind = diag::err_arc_weak_unavailable_assign; 11950 break; 11951 case Incompatible: 11952 DiagKind = diag::err_typecheck_convert_incompatible; 11953 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11954 MayHaveConvFixit = true; 11955 isInvalid = true; 11956 MayHaveFunctionDiff = true; 11957 break; 11958 } 11959 11960 QualType FirstType, SecondType; 11961 switch (Action) { 11962 case AA_Assigning: 11963 case AA_Initializing: 11964 // The destination type comes first. 11965 FirstType = DstType; 11966 SecondType = SrcType; 11967 break; 11968 11969 case AA_Returning: 11970 case AA_Passing: 11971 case AA_Passing_CFAudited: 11972 case AA_Converting: 11973 case AA_Sending: 11974 case AA_Casting: 11975 // The source type comes first. 11976 FirstType = SrcType; 11977 SecondType = DstType; 11978 break; 11979 } 11980 11981 PartialDiagnostic FDiag = PDiag(DiagKind); 11982 if (Action == AA_Passing_CFAudited) 11983 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 11984 else 11985 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 11986 11987 // If we can fix the conversion, suggest the FixIts. 11988 assert(ConvHints.isNull() || Hint.isNull()); 11989 if (!ConvHints.isNull()) { 11990 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 11991 HE = ConvHints.Hints.end(); HI != HE; ++HI) 11992 FDiag << *HI; 11993 } else { 11994 FDiag << Hint; 11995 } 11996 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 11997 11998 if (MayHaveFunctionDiff) 11999 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12000 12001 Diag(Loc, FDiag); 12002 if (DiagKind == diag::warn_incompatible_qualified_id && 12003 PDecl && IFace && !IFace->hasDefinition()) 12004 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12005 << IFace->getName() << PDecl->getName(); 12006 12007 if (SecondType == Context.OverloadTy) 12008 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12009 FirstType); 12010 12011 if (CheckInferredResultType) 12012 EmitRelatedResultTypeNote(SrcExpr); 12013 12014 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12015 EmitRelatedResultTypeNoteForReturn(DstType); 12016 12017 if (Complained) 12018 *Complained = true; 12019 return isInvalid; 12020 } 12021 12022 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12023 llvm::APSInt *Result) { 12024 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12025 public: 12026 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12027 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12028 } 12029 } Diagnoser; 12030 12031 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12032 } 12033 12034 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12035 llvm::APSInt *Result, 12036 unsigned DiagID, 12037 bool AllowFold) { 12038 class IDDiagnoser : public VerifyICEDiagnoser { 12039 unsigned DiagID; 12040 12041 public: 12042 IDDiagnoser(unsigned DiagID) 12043 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12044 12045 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12046 S.Diag(Loc, DiagID) << SR; 12047 } 12048 } Diagnoser(DiagID); 12049 12050 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12051 } 12052 12053 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12054 SourceRange SR) { 12055 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12056 } 12057 12058 ExprResult 12059 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12060 VerifyICEDiagnoser &Diagnoser, 12061 bool AllowFold) { 12062 SourceLocation DiagLoc = E->getLocStart(); 12063 12064 if (getLangOpts().CPlusPlus11) { 12065 // C++11 [expr.const]p5: 12066 // If an expression of literal class type is used in a context where an 12067 // integral constant expression is required, then that class type shall 12068 // have a single non-explicit conversion function to an integral or 12069 // unscoped enumeration type 12070 ExprResult Converted; 12071 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12072 public: 12073 CXX11ConvertDiagnoser(bool Silent) 12074 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12075 Silent, true) {} 12076 12077 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12078 QualType T) override { 12079 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12080 } 12081 12082 SemaDiagnosticBuilder diagnoseIncomplete( 12083 Sema &S, SourceLocation Loc, QualType T) override { 12084 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12085 } 12086 12087 SemaDiagnosticBuilder diagnoseExplicitConv( 12088 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12089 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12090 } 12091 12092 SemaDiagnosticBuilder noteExplicitConv( 12093 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12094 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12095 << ConvTy->isEnumeralType() << ConvTy; 12096 } 12097 12098 SemaDiagnosticBuilder diagnoseAmbiguous( 12099 Sema &S, SourceLocation Loc, QualType T) override { 12100 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12101 } 12102 12103 SemaDiagnosticBuilder noteAmbiguous( 12104 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12105 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12106 << ConvTy->isEnumeralType() << ConvTy; 12107 } 12108 12109 SemaDiagnosticBuilder diagnoseConversion( 12110 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12111 llvm_unreachable("conversion functions are permitted"); 12112 } 12113 } ConvertDiagnoser(Diagnoser.Suppress); 12114 12115 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12116 ConvertDiagnoser); 12117 if (Converted.isInvalid()) 12118 return Converted; 12119 E = Converted.get(); 12120 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12121 return ExprError(); 12122 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12123 // An ICE must be of integral or unscoped enumeration type. 12124 if (!Diagnoser.Suppress) 12125 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12126 return ExprError(); 12127 } 12128 12129 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12130 // in the non-ICE case. 12131 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12132 if (Result) 12133 *Result = E->EvaluateKnownConstInt(Context); 12134 return E; 12135 } 12136 12137 Expr::EvalResult EvalResult; 12138 SmallVector<PartialDiagnosticAt, 8> Notes; 12139 EvalResult.Diag = &Notes; 12140 12141 // Try to evaluate the expression, and produce diagnostics explaining why it's 12142 // not a constant expression as a side-effect. 12143 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12144 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12145 12146 // In C++11, we can rely on diagnostics being produced for any expression 12147 // which is not a constant expression. If no diagnostics were produced, then 12148 // this is a constant expression. 12149 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12150 if (Result) 12151 *Result = EvalResult.Val.getInt(); 12152 return E; 12153 } 12154 12155 // If our only note is the usual "invalid subexpression" note, just point 12156 // the caret at its location rather than producing an essentially 12157 // redundant note. 12158 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12159 diag::note_invalid_subexpr_in_const_expr) { 12160 DiagLoc = Notes[0].first; 12161 Notes.clear(); 12162 } 12163 12164 if (!Folded || !AllowFold) { 12165 if (!Diagnoser.Suppress) { 12166 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12167 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12168 Diag(Notes[I].first, Notes[I].second); 12169 } 12170 12171 return ExprError(); 12172 } 12173 12174 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12175 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12176 Diag(Notes[I].first, Notes[I].second); 12177 12178 if (Result) 12179 *Result = EvalResult.Val.getInt(); 12180 return E; 12181 } 12182 12183 namespace { 12184 // Handle the case where we conclude a expression which we speculatively 12185 // considered to be unevaluated is actually evaluated. 12186 class TransformToPE : public TreeTransform<TransformToPE> { 12187 typedef TreeTransform<TransformToPE> BaseTransform; 12188 12189 public: 12190 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12191 12192 // Make sure we redo semantic analysis 12193 bool AlwaysRebuild() { return true; } 12194 12195 // Make sure we handle LabelStmts correctly. 12196 // FIXME: This does the right thing, but maybe we need a more general 12197 // fix to TreeTransform? 12198 StmtResult TransformLabelStmt(LabelStmt *S) { 12199 S->getDecl()->setStmt(nullptr); 12200 return BaseTransform::TransformLabelStmt(S); 12201 } 12202 12203 // We need to special-case DeclRefExprs referring to FieldDecls which 12204 // are not part of a member pointer formation; normal TreeTransforming 12205 // doesn't catch this case because of the way we represent them in the AST. 12206 // FIXME: This is a bit ugly; is it really the best way to handle this 12207 // case? 12208 // 12209 // Error on DeclRefExprs referring to FieldDecls. 12210 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12211 if (isa<FieldDecl>(E->getDecl()) && 12212 !SemaRef.isUnevaluatedContext()) 12213 return SemaRef.Diag(E->getLocation(), 12214 diag::err_invalid_non_static_member_use) 12215 << E->getDecl() << E->getSourceRange(); 12216 12217 return BaseTransform::TransformDeclRefExpr(E); 12218 } 12219 12220 // Exception: filter out member pointer formation 12221 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12222 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12223 return E; 12224 12225 return BaseTransform::TransformUnaryOperator(E); 12226 } 12227 12228 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12229 // Lambdas never need to be transformed. 12230 return E; 12231 } 12232 }; 12233 } 12234 12235 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12236 assert(isUnevaluatedContext() && 12237 "Should only transform unevaluated expressions"); 12238 ExprEvalContexts.back().Context = 12239 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12240 if (isUnevaluatedContext()) 12241 return E; 12242 return TransformToPE(*this).TransformExpr(E); 12243 } 12244 12245 void 12246 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12247 Decl *LambdaContextDecl, 12248 bool IsDecltype) { 12249 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12250 ExprNeedsCleanups, LambdaContextDecl, 12251 IsDecltype); 12252 ExprNeedsCleanups = false; 12253 if (!MaybeODRUseExprs.empty()) 12254 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12255 } 12256 12257 void 12258 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12259 ReuseLambdaContextDecl_t, 12260 bool IsDecltype) { 12261 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12262 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12263 } 12264 12265 void Sema::PopExpressionEvaluationContext() { 12266 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12267 unsigned NumTypos = Rec.NumTypos; 12268 12269 if (!Rec.Lambdas.empty()) { 12270 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12271 unsigned D; 12272 if (Rec.isUnevaluated()) { 12273 // C++11 [expr.prim.lambda]p2: 12274 // A lambda-expression shall not appear in an unevaluated operand 12275 // (Clause 5). 12276 D = diag::err_lambda_unevaluated_operand; 12277 } else { 12278 // C++1y [expr.const]p2: 12279 // A conditional-expression e is a core constant expression unless the 12280 // evaluation of e, following the rules of the abstract machine, would 12281 // evaluate [...] a lambda-expression. 12282 D = diag::err_lambda_in_constant_expression; 12283 } 12284 for (const auto *L : Rec.Lambdas) 12285 Diag(L->getLocStart(), D); 12286 } else { 12287 // Mark the capture expressions odr-used. This was deferred 12288 // during lambda expression creation. 12289 for (auto *Lambda : Rec.Lambdas) { 12290 for (auto *C : Lambda->capture_inits()) 12291 MarkDeclarationsReferencedInExpr(C); 12292 } 12293 } 12294 } 12295 12296 // When are coming out of an unevaluated context, clear out any 12297 // temporaries that we may have created as part of the evaluation of 12298 // the expression in that context: they aren't relevant because they 12299 // will never be constructed. 12300 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12301 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12302 ExprCleanupObjects.end()); 12303 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12304 CleanupVarDeclMarking(); 12305 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12306 // Otherwise, merge the contexts together. 12307 } else { 12308 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12309 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12310 Rec.SavedMaybeODRUseExprs.end()); 12311 } 12312 12313 // Pop the current expression evaluation context off the stack. 12314 ExprEvalContexts.pop_back(); 12315 12316 if (!ExprEvalContexts.empty()) 12317 ExprEvalContexts.back().NumTypos += NumTypos; 12318 else 12319 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12320 "last ExpressionEvaluationContextRecord"); 12321 } 12322 12323 void Sema::DiscardCleanupsInEvaluationContext() { 12324 ExprCleanupObjects.erase( 12325 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12326 ExprCleanupObjects.end()); 12327 ExprNeedsCleanups = false; 12328 MaybeODRUseExprs.clear(); 12329 } 12330 12331 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12332 if (!E->getType()->isVariablyModifiedType()) 12333 return E; 12334 return TransformToPotentiallyEvaluated(E); 12335 } 12336 12337 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12338 // Do not mark anything as "used" within a dependent context; wait for 12339 // an instantiation. 12340 if (SemaRef.CurContext->isDependentContext()) 12341 return false; 12342 12343 switch (SemaRef.ExprEvalContexts.back().Context) { 12344 case Sema::Unevaluated: 12345 case Sema::UnevaluatedAbstract: 12346 // We are in an expression that is not potentially evaluated; do nothing. 12347 // (Depending on how you read the standard, we actually do need to do 12348 // something here for null pointer constants, but the standard's 12349 // definition of a null pointer constant is completely crazy.) 12350 return false; 12351 12352 case Sema::ConstantEvaluated: 12353 case Sema::PotentiallyEvaluated: 12354 // We are in a potentially evaluated expression (or a constant-expression 12355 // in C++03); we need to do implicit template instantiation, implicitly 12356 // define class members, and mark most declarations as used. 12357 return true; 12358 12359 case Sema::PotentiallyEvaluatedIfUsed: 12360 // Referenced declarations will only be used if the construct in the 12361 // containing expression is used. 12362 return false; 12363 } 12364 llvm_unreachable("Invalid context"); 12365 } 12366 12367 /// \brief Mark a function referenced, and check whether it is odr-used 12368 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12369 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12370 bool OdrUse) { 12371 assert(Func && "No function?"); 12372 12373 Func->setReferenced(); 12374 12375 // C++11 [basic.def.odr]p3: 12376 // A function whose name appears as a potentially-evaluated expression is 12377 // odr-used if it is the unique lookup result or the selected member of a 12378 // set of overloaded functions [...]. 12379 // 12380 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12381 // can just check that here. Skip the rest of this function if we've already 12382 // marked the function as used. 12383 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12384 !IsPotentiallyEvaluatedContext(*this)) { 12385 // C++11 [temp.inst]p3: 12386 // Unless a function template specialization has been explicitly 12387 // instantiated or explicitly specialized, the function template 12388 // specialization is implicitly instantiated when the specialization is 12389 // referenced in a context that requires a function definition to exist. 12390 // 12391 // We consider constexpr function templates to be referenced in a context 12392 // that requires a definition to exist whenever they are referenced. 12393 // 12394 // FIXME: This instantiates constexpr functions too frequently. If this is 12395 // really an unevaluated context (and we're not just in the definition of a 12396 // function template or overload resolution or other cases which we 12397 // incorrectly consider to be unevaluated contexts), and we're not in a 12398 // subexpression which we actually need to evaluate (for instance, a 12399 // template argument, array bound or an expression in a braced-init-list), 12400 // we are not permitted to instantiate this constexpr function definition. 12401 // 12402 // FIXME: This also implicitly defines special members too frequently. They 12403 // are only supposed to be implicitly defined if they are odr-used, but they 12404 // are not odr-used from constant expressions in unevaluated contexts. 12405 // However, they cannot be referenced if they are deleted, and they are 12406 // deleted whenever the implicit definition of the special member would 12407 // fail. 12408 if (!Func->isConstexpr() || Func->getBody()) 12409 return; 12410 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12411 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12412 return; 12413 } 12414 12415 // Note that this declaration has been used. 12416 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12417 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12418 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12419 if (Constructor->isDefaultConstructor()) { 12420 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12421 return; 12422 DefineImplicitDefaultConstructor(Loc, Constructor); 12423 } else if (Constructor->isCopyConstructor()) { 12424 DefineImplicitCopyConstructor(Loc, Constructor); 12425 } else if (Constructor->isMoveConstructor()) { 12426 DefineImplicitMoveConstructor(Loc, Constructor); 12427 } 12428 } else if (Constructor->getInheritedConstructor()) { 12429 DefineInheritingConstructor(Loc, Constructor); 12430 } 12431 } else if (CXXDestructorDecl *Destructor = 12432 dyn_cast<CXXDestructorDecl>(Func)) { 12433 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12434 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12435 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12436 return; 12437 DefineImplicitDestructor(Loc, Destructor); 12438 } 12439 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12440 MarkVTableUsed(Loc, Destructor->getParent()); 12441 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12442 if (MethodDecl->isOverloadedOperator() && 12443 MethodDecl->getOverloadedOperator() == OO_Equal) { 12444 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12445 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12446 if (MethodDecl->isCopyAssignmentOperator()) 12447 DefineImplicitCopyAssignment(Loc, MethodDecl); 12448 else 12449 DefineImplicitMoveAssignment(Loc, MethodDecl); 12450 } 12451 } else if (isa<CXXConversionDecl>(MethodDecl) && 12452 MethodDecl->getParent()->isLambda()) { 12453 CXXConversionDecl *Conversion = 12454 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12455 if (Conversion->isLambdaToBlockPointerConversion()) 12456 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12457 else 12458 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12459 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12460 MarkVTableUsed(Loc, MethodDecl->getParent()); 12461 } 12462 12463 // Recursive functions should be marked when used from another function. 12464 // FIXME: Is this really right? 12465 if (CurContext == Func) return; 12466 12467 // Resolve the exception specification for any function which is 12468 // used: CodeGen will need it. 12469 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12470 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12471 ResolveExceptionSpec(Loc, FPT); 12472 12473 if (!OdrUse) return; 12474 12475 // Implicit instantiation of function templates and member functions of 12476 // class templates. 12477 if (Func->isImplicitlyInstantiable()) { 12478 bool AlreadyInstantiated = false; 12479 SourceLocation PointOfInstantiation = Loc; 12480 if (FunctionTemplateSpecializationInfo *SpecInfo 12481 = Func->getTemplateSpecializationInfo()) { 12482 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12483 SpecInfo->setPointOfInstantiation(Loc); 12484 else if (SpecInfo->getTemplateSpecializationKind() 12485 == TSK_ImplicitInstantiation) { 12486 AlreadyInstantiated = true; 12487 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12488 } 12489 } else if (MemberSpecializationInfo *MSInfo 12490 = Func->getMemberSpecializationInfo()) { 12491 if (MSInfo->getPointOfInstantiation().isInvalid()) 12492 MSInfo->setPointOfInstantiation(Loc); 12493 else if (MSInfo->getTemplateSpecializationKind() 12494 == TSK_ImplicitInstantiation) { 12495 AlreadyInstantiated = true; 12496 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12497 } 12498 } 12499 12500 if (!AlreadyInstantiated || Func->isConstexpr()) { 12501 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12502 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12503 ActiveTemplateInstantiations.size()) 12504 PendingLocalImplicitInstantiations.push_back( 12505 std::make_pair(Func, PointOfInstantiation)); 12506 else if (Func->isConstexpr()) 12507 // Do not defer instantiations of constexpr functions, to avoid the 12508 // expression evaluator needing to call back into Sema if it sees a 12509 // call to such a function. 12510 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12511 else { 12512 PendingInstantiations.push_back(std::make_pair(Func, 12513 PointOfInstantiation)); 12514 // Notify the consumer that a function was implicitly instantiated. 12515 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12516 } 12517 } 12518 } else { 12519 // Walk redefinitions, as some of them may be instantiable. 12520 for (auto i : Func->redecls()) { 12521 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12522 MarkFunctionReferenced(Loc, i); 12523 } 12524 } 12525 12526 // Keep track of used but undefined functions. 12527 if (!Func->isDefined()) { 12528 if (mightHaveNonExternalLinkage(Func)) 12529 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12530 else if (Func->getMostRecentDecl()->isInlined() && 12531 !LangOpts.GNUInline && 12532 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12533 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12534 } 12535 12536 // Normally the most current decl is marked used while processing the use and 12537 // any subsequent decls are marked used by decl merging. This fails with 12538 // template instantiation since marking can happen at the end of the file 12539 // and, because of the two phase lookup, this function is called with at 12540 // decl in the middle of a decl chain. We loop to maintain the invariant 12541 // that once a decl is used, all decls after it are also used. 12542 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12543 F->markUsed(Context); 12544 if (F == Func) 12545 break; 12546 } 12547 } 12548 12549 static void 12550 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12551 VarDecl *var, DeclContext *DC) { 12552 DeclContext *VarDC = var->getDeclContext(); 12553 12554 // If the parameter still belongs to the translation unit, then 12555 // we're actually just using one parameter in the declaration of 12556 // the next. 12557 if (isa<ParmVarDecl>(var) && 12558 isa<TranslationUnitDecl>(VarDC)) 12559 return; 12560 12561 // For C code, don't diagnose about capture if we're not actually in code 12562 // right now; it's impossible to write a non-constant expression outside of 12563 // function context, so we'll get other (more useful) diagnostics later. 12564 // 12565 // For C++, things get a bit more nasty... it would be nice to suppress this 12566 // diagnostic for certain cases like using a local variable in an array bound 12567 // for a member of a local class, but the correct predicate is not obvious. 12568 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12569 return; 12570 12571 if (isa<CXXMethodDecl>(VarDC) && 12572 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12573 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12574 << var->getIdentifier(); 12575 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12576 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12577 << var->getIdentifier() << fn->getDeclName(); 12578 } else if (isa<BlockDecl>(VarDC)) { 12579 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12580 << var->getIdentifier(); 12581 } else { 12582 // FIXME: Is there any other context where a local variable can be 12583 // declared? 12584 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12585 << var->getIdentifier(); 12586 } 12587 12588 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12589 << var->getIdentifier(); 12590 12591 // FIXME: Add additional diagnostic info about class etc. which prevents 12592 // capture. 12593 } 12594 12595 12596 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12597 bool &SubCapturesAreNested, 12598 QualType &CaptureType, 12599 QualType &DeclRefType) { 12600 // Check whether we've already captured it. 12601 if (CSI->CaptureMap.count(Var)) { 12602 // If we found a capture, any subcaptures are nested. 12603 SubCapturesAreNested = true; 12604 12605 // Retrieve the capture type for this variable. 12606 CaptureType = CSI->getCapture(Var).getCaptureType(); 12607 12608 // Compute the type of an expression that refers to this variable. 12609 DeclRefType = CaptureType.getNonReferenceType(); 12610 12611 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 12612 if (Cap.isCopyCapture() && 12613 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 12614 DeclRefType.addConst(); 12615 return true; 12616 } 12617 return false; 12618 } 12619 12620 // Only block literals, captured statements, and lambda expressions can 12621 // capture; other scopes don't work. 12622 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 12623 SourceLocation Loc, 12624 const bool Diagnose, Sema &S) { 12625 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 12626 return getLambdaAwareParentOfDeclContext(DC); 12627 else if (Var->hasLocalStorage()) { 12628 if (Diagnose) 12629 diagnoseUncapturableValueReference(S, Loc, Var, DC); 12630 } 12631 return nullptr; 12632 } 12633 12634 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12635 // certain types of variables (unnamed, variably modified types etc.) 12636 // so check for eligibility. 12637 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 12638 SourceLocation Loc, 12639 const bool Diagnose, Sema &S) { 12640 12641 bool IsBlock = isa<BlockScopeInfo>(CSI); 12642 bool IsLambda = isa<LambdaScopeInfo>(CSI); 12643 12644 // Lambdas are not allowed to capture unnamed variables 12645 // (e.g. anonymous unions). 12646 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 12647 // assuming that's the intent. 12648 if (IsLambda && !Var->getDeclName()) { 12649 if (Diagnose) { 12650 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 12651 S.Diag(Var->getLocation(), diag::note_declared_at); 12652 } 12653 return false; 12654 } 12655 12656 // Prohibit variably-modified types in blocks; they're difficult to deal with. 12657 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 12658 if (Diagnose) { 12659 S.Diag(Loc, diag::err_ref_vm_type); 12660 S.Diag(Var->getLocation(), diag::note_previous_decl) 12661 << Var->getDeclName(); 12662 } 12663 return false; 12664 } 12665 // Prohibit structs with flexible array members too. 12666 // We cannot capture what is in the tail end of the struct. 12667 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 12668 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 12669 if (Diagnose) { 12670 if (IsBlock) 12671 S.Diag(Loc, diag::err_ref_flexarray_type); 12672 else 12673 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 12674 << Var->getDeclName(); 12675 S.Diag(Var->getLocation(), diag::note_previous_decl) 12676 << Var->getDeclName(); 12677 } 12678 return false; 12679 } 12680 } 12681 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12682 // Lambdas and captured statements are not allowed to capture __block 12683 // variables; they don't support the expected semantics. 12684 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 12685 if (Diagnose) { 12686 S.Diag(Loc, diag::err_capture_block_variable) 12687 << Var->getDeclName() << !IsLambda; 12688 S.Diag(Var->getLocation(), diag::note_previous_decl) 12689 << Var->getDeclName(); 12690 } 12691 return false; 12692 } 12693 12694 return true; 12695 } 12696 12697 // Returns true if the capture by block was successful. 12698 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 12699 SourceLocation Loc, 12700 const bool BuildAndDiagnose, 12701 QualType &CaptureType, 12702 QualType &DeclRefType, 12703 const bool Nested, 12704 Sema &S) { 12705 Expr *CopyExpr = nullptr; 12706 bool ByRef = false; 12707 12708 // Blocks are not allowed to capture arrays. 12709 if (CaptureType->isArrayType()) { 12710 if (BuildAndDiagnose) { 12711 S.Diag(Loc, diag::err_ref_array_type); 12712 S.Diag(Var->getLocation(), diag::note_previous_decl) 12713 << Var->getDeclName(); 12714 } 12715 return false; 12716 } 12717 12718 // Forbid the block-capture of autoreleasing variables. 12719 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12720 if (BuildAndDiagnose) { 12721 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 12722 << /*block*/ 0; 12723 S.Diag(Var->getLocation(), diag::note_previous_decl) 12724 << Var->getDeclName(); 12725 } 12726 return false; 12727 } 12728 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12729 if (HasBlocksAttr || CaptureType->isReferenceType()) { 12730 // Block capture by reference does not change the capture or 12731 // declaration reference types. 12732 ByRef = true; 12733 } else { 12734 // Block capture by copy introduces 'const'. 12735 CaptureType = CaptureType.getNonReferenceType().withConst(); 12736 DeclRefType = CaptureType; 12737 12738 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 12739 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 12740 // The capture logic needs the destructor, so make sure we mark it. 12741 // Usually this is unnecessary because most local variables have 12742 // their destructors marked at declaration time, but parameters are 12743 // an exception because it's technically only the call site that 12744 // actually requires the destructor. 12745 if (isa<ParmVarDecl>(Var)) 12746 S.FinalizeVarWithDestructor(Var, Record); 12747 12748 // Enter a new evaluation context to insulate the copy 12749 // full-expression. 12750 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 12751 12752 // According to the blocks spec, the capture of a variable from 12753 // the stack requires a const copy constructor. This is not true 12754 // of the copy/move done to move a __block variable to the heap. 12755 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 12756 DeclRefType.withConst(), 12757 VK_LValue, Loc); 12758 12759 ExprResult Result 12760 = S.PerformCopyInitialization( 12761 InitializedEntity::InitializeBlock(Var->getLocation(), 12762 CaptureType, false), 12763 Loc, DeclRef); 12764 12765 // Build a full-expression copy expression if initialization 12766 // succeeded and used a non-trivial constructor. Recover from 12767 // errors by pretending that the copy isn't necessary. 12768 if (!Result.isInvalid() && 12769 !cast<CXXConstructExpr>(Result.get())->getConstructor() 12770 ->isTrivial()) { 12771 Result = S.MaybeCreateExprWithCleanups(Result); 12772 CopyExpr = Result.get(); 12773 } 12774 } 12775 } 12776 } 12777 12778 // Actually capture the variable. 12779 if (BuildAndDiagnose) 12780 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 12781 SourceLocation(), CaptureType, CopyExpr); 12782 12783 return true; 12784 12785 } 12786 12787 12788 /// \brief Capture the given variable in the captured region. 12789 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 12790 VarDecl *Var, 12791 SourceLocation Loc, 12792 const bool BuildAndDiagnose, 12793 QualType &CaptureType, 12794 QualType &DeclRefType, 12795 const bool RefersToCapturedVariable, 12796 Sema &S) { 12797 12798 // By default, capture variables by reference. 12799 bool ByRef = true; 12800 // Using an LValue reference type is consistent with Lambdas (see below). 12801 if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var)) 12802 DeclRefType = DeclRefType.getUnqualifiedType(); 12803 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12804 Expr *CopyExpr = nullptr; 12805 if (BuildAndDiagnose) { 12806 // The current implementation assumes that all variables are captured 12807 // by references. Since there is no capture by copy, no expression 12808 // evaluation will be needed. 12809 RecordDecl *RD = RSI->TheRecordDecl; 12810 12811 FieldDecl *Field 12812 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 12813 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 12814 nullptr, false, ICIS_NoInit); 12815 Field->setImplicit(true); 12816 Field->setAccess(AS_private); 12817 RD->addDecl(Field); 12818 12819 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 12820 DeclRefType, VK_LValue, Loc); 12821 Var->setReferenced(true); 12822 Var->markUsed(S.Context); 12823 } 12824 12825 // Actually capture the variable. 12826 if (BuildAndDiagnose) 12827 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 12828 SourceLocation(), CaptureType, CopyExpr); 12829 12830 12831 return true; 12832 } 12833 12834 /// \brief Create a field within the lambda class for the variable 12835 /// being captured. 12836 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 12837 QualType FieldType, QualType DeclRefType, 12838 SourceLocation Loc, 12839 bool RefersToCapturedVariable) { 12840 CXXRecordDecl *Lambda = LSI->Lambda; 12841 12842 // Build the non-static data member. 12843 FieldDecl *Field 12844 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 12845 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 12846 nullptr, false, ICIS_NoInit); 12847 Field->setImplicit(true); 12848 Field->setAccess(AS_private); 12849 Lambda->addDecl(Field); 12850 } 12851 12852 /// \brief Capture the given variable in the lambda. 12853 static bool captureInLambda(LambdaScopeInfo *LSI, 12854 VarDecl *Var, 12855 SourceLocation Loc, 12856 const bool BuildAndDiagnose, 12857 QualType &CaptureType, 12858 QualType &DeclRefType, 12859 const bool RefersToCapturedVariable, 12860 const Sema::TryCaptureKind Kind, 12861 SourceLocation EllipsisLoc, 12862 const bool IsTopScope, 12863 Sema &S) { 12864 12865 // Determine whether we are capturing by reference or by value. 12866 bool ByRef = false; 12867 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 12868 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 12869 } else { 12870 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 12871 } 12872 12873 // Compute the type of the field that will capture this variable. 12874 if (ByRef) { 12875 // C++11 [expr.prim.lambda]p15: 12876 // An entity is captured by reference if it is implicitly or 12877 // explicitly captured but not captured by copy. It is 12878 // unspecified whether additional unnamed non-static data 12879 // members are declared in the closure type for entities 12880 // captured by reference. 12881 // 12882 // FIXME: It is not clear whether we want to build an lvalue reference 12883 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 12884 // to do the former, while EDG does the latter. Core issue 1249 will 12885 // clarify, but for now we follow GCC because it's a more permissive and 12886 // easily defensible position. 12887 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12888 } else { 12889 // C++11 [expr.prim.lambda]p14: 12890 // For each entity captured by copy, an unnamed non-static 12891 // data member is declared in the closure type. The 12892 // declaration order of these members is unspecified. The type 12893 // of such a data member is the type of the corresponding 12894 // captured entity if the entity is not a reference to an 12895 // object, or the referenced type otherwise. [Note: If the 12896 // captured entity is a reference to a function, the 12897 // corresponding data member is also a reference to a 12898 // function. - end note ] 12899 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 12900 if (!RefType->getPointeeType()->isFunctionType()) 12901 CaptureType = RefType->getPointeeType(); 12902 } 12903 12904 // Forbid the lambda copy-capture of autoreleasing variables. 12905 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12906 if (BuildAndDiagnose) { 12907 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 12908 S.Diag(Var->getLocation(), diag::note_previous_decl) 12909 << Var->getDeclName(); 12910 } 12911 return false; 12912 } 12913 12914 // Make sure that by-copy captures are of a complete and non-abstract type. 12915 if (BuildAndDiagnose) { 12916 if (!CaptureType->isDependentType() && 12917 S.RequireCompleteType(Loc, CaptureType, 12918 diag::err_capture_of_incomplete_type, 12919 Var->getDeclName())) 12920 return false; 12921 12922 if (S.RequireNonAbstractType(Loc, CaptureType, 12923 diag::err_capture_of_abstract_type)) 12924 return false; 12925 } 12926 } 12927 12928 // Capture this variable in the lambda. 12929 if (BuildAndDiagnose) 12930 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 12931 RefersToCapturedVariable); 12932 12933 // Compute the type of a reference to this captured variable. 12934 if (ByRef) 12935 DeclRefType = CaptureType.getNonReferenceType(); 12936 else { 12937 // C++ [expr.prim.lambda]p5: 12938 // The closure type for a lambda-expression has a public inline 12939 // function call operator [...]. This function call operator is 12940 // declared const (9.3.1) if and only if the lambda-expression’s 12941 // parameter-declaration-clause is not followed by mutable. 12942 DeclRefType = CaptureType.getNonReferenceType(); 12943 if (!LSI->Mutable && !CaptureType->isReferenceType()) 12944 DeclRefType.addConst(); 12945 } 12946 12947 // Add the capture. 12948 if (BuildAndDiagnose) 12949 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 12950 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 12951 12952 return true; 12953 } 12954 12955 bool Sema::tryCaptureVariable( 12956 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 12957 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 12958 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 12959 // An init-capture is notionally from the context surrounding its 12960 // declaration, but its parent DC is the lambda class. 12961 DeclContext *VarDC = Var->getDeclContext(); 12962 if (Var->isInitCapture()) 12963 VarDC = VarDC->getParent(); 12964 12965 DeclContext *DC = CurContext; 12966 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12967 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 12968 // We need to sync up the Declaration Context with the 12969 // FunctionScopeIndexToStopAt 12970 if (FunctionScopeIndexToStopAt) { 12971 unsigned FSIndex = FunctionScopes.size() - 1; 12972 while (FSIndex != MaxFunctionScopesIndex) { 12973 DC = getLambdaAwareParentOfDeclContext(DC); 12974 --FSIndex; 12975 } 12976 } 12977 12978 12979 // If the variable is declared in the current context, there is no need to 12980 // capture it. 12981 if (VarDC == DC) return true; 12982 12983 // Capture global variables if it is required to use private copy of this 12984 // variable. 12985 bool IsGlobal = !Var->hasLocalStorage(); 12986 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var))) 12987 return true; 12988 12989 // Walk up the stack to determine whether we can capture the variable, 12990 // performing the "simple" checks that don't depend on type. We stop when 12991 // we've either hit the declared scope of the variable or find an existing 12992 // capture of that variable. We start from the innermost capturing-entity 12993 // (the DC) and ensure that all intervening capturing-entities 12994 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 12995 // declcontext can either capture the variable or have already captured 12996 // the variable. 12997 CaptureType = Var->getType(); 12998 DeclRefType = CaptureType.getNonReferenceType(); 12999 bool Nested = false; 13000 bool Explicit = (Kind != TryCapture_Implicit); 13001 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13002 unsigned OpenMPLevel = 0; 13003 do { 13004 // Only block literals, captured statements, and lambda expressions can 13005 // capture; other scopes don't work. 13006 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13007 ExprLoc, 13008 BuildAndDiagnose, 13009 *this); 13010 // We need to check for the parent *first* because, if we *have* 13011 // private-captured a global variable, we need to recursively capture it in 13012 // intermediate blocks, lambdas, etc. 13013 if (!ParentDC) { 13014 if (IsGlobal) { 13015 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13016 break; 13017 } 13018 return true; 13019 } 13020 13021 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13022 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13023 13024 13025 // Check whether we've already captured it. 13026 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13027 DeclRefType)) 13028 break; 13029 // If we are instantiating a generic lambda call operator body, 13030 // we do not want to capture new variables. What was captured 13031 // during either a lambdas transformation or initial parsing 13032 // should be used. 13033 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13034 if (BuildAndDiagnose) { 13035 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13036 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13037 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13038 Diag(Var->getLocation(), diag::note_previous_decl) 13039 << Var->getDeclName(); 13040 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13041 } else 13042 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13043 } 13044 return true; 13045 } 13046 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13047 // certain types of variables (unnamed, variably modified types etc.) 13048 // so check for eligibility. 13049 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13050 return true; 13051 13052 // Try to capture variable-length arrays types. 13053 if (Var->getType()->isVariablyModifiedType()) { 13054 // We're going to walk down into the type and look for VLA 13055 // expressions. 13056 QualType QTy = Var->getType(); 13057 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13058 QTy = PVD->getOriginalType(); 13059 do { 13060 const Type *Ty = QTy.getTypePtr(); 13061 switch (Ty->getTypeClass()) { 13062 #define TYPE(Class, Base) 13063 #define ABSTRACT_TYPE(Class, Base) 13064 #define NON_CANONICAL_TYPE(Class, Base) 13065 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 13066 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 13067 #include "clang/AST/TypeNodes.def" 13068 QTy = QualType(); 13069 break; 13070 // These types are never variably-modified. 13071 case Type::Builtin: 13072 case Type::Complex: 13073 case Type::Vector: 13074 case Type::ExtVector: 13075 case Type::Record: 13076 case Type::Enum: 13077 case Type::Elaborated: 13078 case Type::TemplateSpecialization: 13079 case Type::ObjCObject: 13080 case Type::ObjCInterface: 13081 case Type::ObjCObjectPointer: 13082 llvm_unreachable("type class is never variably-modified!"); 13083 case Type::Adjusted: 13084 QTy = cast<AdjustedType>(Ty)->getOriginalType(); 13085 break; 13086 case Type::Decayed: 13087 QTy = cast<DecayedType>(Ty)->getPointeeType(); 13088 break; 13089 case Type::Pointer: 13090 QTy = cast<PointerType>(Ty)->getPointeeType(); 13091 break; 13092 case Type::BlockPointer: 13093 QTy = cast<BlockPointerType>(Ty)->getPointeeType(); 13094 break; 13095 case Type::LValueReference: 13096 case Type::RValueReference: 13097 QTy = cast<ReferenceType>(Ty)->getPointeeType(); 13098 break; 13099 case Type::MemberPointer: 13100 QTy = cast<MemberPointerType>(Ty)->getPointeeType(); 13101 break; 13102 case Type::ConstantArray: 13103 case Type::IncompleteArray: 13104 // Losing element qualification here is fine. 13105 QTy = cast<ArrayType>(Ty)->getElementType(); 13106 break; 13107 case Type::VariableArray: { 13108 // Losing element qualification here is fine. 13109 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 13110 13111 // Unknown size indication requires no size computation. 13112 // Otherwise, evaluate and record it. 13113 if (auto Size = VAT->getSizeExpr()) { 13114 if (!CSI->isVLATypeCaptured(VAT)) { 13115 RecordDecl *CapRecord = nullptr; 13116 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 13117 CapRecord = LSI->Lambda; 13118 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13119 CapRecord = CRSI->TheRecordDecl; 13120 } 13121 if (CapRecord) { 13122 auto ExprLoc = Size->getExprLoc(); 13123 auto SizeType = Context.getSizeType(); 13124 // Build the non-static data member. 13125 auto Field = FieldDecl::Create( 13126 Context, CapRecord, ExprLoc, ExprLoc, 13127 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 13128 /*BW*/ nullptr, /*Mutable*/ false, 13129 /*InitStyle*/ ICIS_NoInit); 13130 Field->setImplicit(true); 13131 Field->setAccess(AS_private); 13132 Field->setCapturedVLAType(VAT); 13133 CapRecord->addDecl(Field); 13134 13135 CSI->addVLATypeCapture(ExprLoc, SizeType); 13136 } 13137 } 13138 } 13139 QTy = VAT->getElementType(); 13140 break; 13141 } 13142 case Type::FunctionProto: 13143 case Type::FunctionNoProto: 13144 QTy = cast<FunctionType>(Ty)->getReturnType(); 13145 break; 13146 case Type::Paren: 13147 case Type::TypeOf: 13148 case Type::UnaryTransform: 13149 case Type::Attributed: 13150 case Type::SubstTemplateTypeParm: 13151 case Type::PackExpansion: 13152 // Keep walking after single level desugaring. 13153 QTy = QTy.getSingleStepDesugaredType(getASTContext()); 13154 break; 13155 case Type::Typedef: 13156 QTy = cast<TypedefType>(Ty)->desugar(); 13157 break; 13158 case Type::Decltype: 13159 QTy = cast<DecltypeType>(Ty)->desugar(); 13160 break; 13161 case Type::Auto: 13162 QTy = cast<AutoType>(Ty)->getDeducedType(); 13163 break; 13164 case Type::TypeOfExpr: 13165 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 13166 break; 13167 case Type::Atomic: 13168 QTy = cast<AtomicType>(Ty)->getValueType(); 13169 break; 13170 } 13171 } while (!QTy.isNull() && QTy->isVariablyModifiedType()); 13172 } 13173 13174 if (getLangOpts().OpenMP) { 13175 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13176 // OpenMP private variables should not be captured in outer scope, so 13177 // just break here. 13178 if (RSI->CapRegionKind == CR_OpenMP) { 13179 if (isOpenMPPrivateVar(Var, OpenMPLevel)) { 13180 Nested = true; 13181 DeclRefType = DeclRefType.getUnqualifiedType(); 13182 CaptureType = Context.getLValueReferenceType(DeclRefType); 13183 break; 13184 } 13185 ++OpenMPLevel; 13186 } 13187 } 13188 } 13189 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13190 // No capture-default, and this is not an explicit capture 13191 // so cannot capture this variable. 13192 if (BuildAndDiagnose) { 13193 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13194 Diag(Var->getLocation(), diag::note_previous_decl) 13195 << Var->getDeclName(); 13196 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13197 diag::note_lambda_decl); 13198 // FIXME: If we error out because an outer lambda can not implicitly 13199 // capture a variable that an inner lambda explicitly captures, we 13200 // should have the inner lambda do the explicit capture - because 13201 // it makes for cleaner diagnostics later. This would purely be done 13202 // so that the diagnostic does not misleadingly claim that a variable 13203 // can not be captured by a lambda implicitly even though it is captured 13204 // explicitly. Suggestion: 13205 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13206 // at the function head 13207 // - cache the StartingDeclContext - this must be a lambda 13208 // - captureInLambda in the innermost lambda the variable. 13209 } 13210 return true; 13211 } 13212 13213 FunctionScopesIndex--; 13214 DC = ParentDC; 13215 Explicit = false; 13216 } while (!VarDC->Equals(DC)); 13217 13218 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13219 // computing the type of the capture at each step, checking type-specific 13220 // requirements, and adding captures if requested. 13221 // If the variable had already been captured previously, we start capturing 13222 // at the lambda nested within that one. 13223 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13224 ++I) { 13225 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13226 13227 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13228 if (!captureInBlock(BSI, Var, ExprLoc, 13229 BuildAndDiagnose, CaptureType, 13230 DeclRefType, Nested, *this)) 13231 return true; 13232 Nested = true; 13233 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13234 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13235 BuildAndDiagnose, CaptureType, 13236 DeclRefType, Nested, *this)) 13237 return true; 13238 Nested = true; 13239 } else { 13240 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13241 if (!captureInLambda(LSI, Var, ExprLoc, 13242 BuildAndDiagnose, CaptureType, 13243 DeclRefType, Nested, Kind, EllipsisLoc, 13244 /*IsTopScope*/I == N - 1, *this)) 13245 return true; 13246 Nested = true; 13247 } 13248 } 13249 return false; 13250 } 13251 13252 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13253 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13254 QualType CaptureType; 13255 QualType DeclRefType; 13256 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13257 /*BuildAndDiagnose=*/true, CaptureType, 13258 DeclRefType, nullptr); 13259 } 13260 13261 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13262 QualType CaptureType; 13263 QualType DeclRefType; 13264 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13265 /*BuildAndDiagnose=*/false, CaptureType, 13266 DeclRefType, nullptr); 13267 } 13268 13269 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13270 QualType CaptureType; 13271 QualType DeclRefType; 13272 13273 // Determine whether we can capture this variable. 13274 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13275 /*BuildAndDiagnose=*/false, CaptureType, 13276 DeclRefType, nullptr)) 13277 return QualType(); 13278 13279 return DeclRefType; 13280 } 13281 13282 13283 13284 // If either the type of the variable or the initializer is dependent, 13285 // return false. Otherwise, determine whether the variable is a constant 13286 // expression. Use this if you need to know if a variable that might or 13287 // might not be dependent is truly a constant expression. 13288 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13289 ASTContext &Context) { 13290 13291 if (Var->getType()->isDependentType()) 13292 return false; 13293 const VarDecl *DefVD = nullptr; 13294 Var->getAnyInitializer(DefVD); 13295 if (!DefVD) 13296 return false; 13297 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13298 Expr *Init = cast<Expr>(Eval->Value); 13299 if (Init->isValueDependent()) 13300 return false; 13301 return IsVariableAConstantExpression(Var, Context); 13302 } 13303 13304 13305 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13306 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13307 // an object that satisfies the requirements for appearing in a 13308 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13309 // is immediately applied." This function handles the lvalue-to-rvalue 13310 // conversion part. 13311 MaybeODRUseExprs.erase(E->IgnoreParens()); 13312 13313 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13314 // to a variable that is a constant expression, and if so, identify it as 13315 // a reference to a variable that does not involve an odr-use of that 13316 // variable. 13317 if (LambdaScopeInfo *LSI = getCurLambda()) { 13318 Expr *SansParensExpr = E->IgnoreParens(); 13319 VarDecl *Var = nullptr; 13320 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13321 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13322 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13323 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13324 13325 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13326 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13327 } 13328 } 13329 13330 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13331 Res = CorrectDelayedTyposInExpr(Res); 13332 13333 if (!Res.isUsable()) 13334 return Res; 13335 13336 // If a constant-expression is a reference to a variable where we delay 13337 // deciding whether it is an odr-use, just assume we will apply the 13338 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13339 // (a non-type template argument), we have special handling anyway. 13340 UpdateMarkingForLValueToRValue(Res.get()); 13341 return Res; 13342 } 13343 13344 void Sema::CleanupVarDeclMarking() { 13345 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 13346 e = MaybeODRUseExprs.end(); 13347 i != e; ++i) { 13348 VarDecl *Var; 13349 SourceLocation Loc; 13350 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 13351 Var = cast<VarDecl>(DRE->getDecl()); 13352 Loc = DRE->getLocation(); 13353 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 13354 Var = cast<VarDecl>(ME->getMemberDecl()); 13355 Loc = ME->getMemberLoc(); 13356 } else { 13357 llvm_unreachable("Unexpected expression"); 13358 } 13359 13360 MarkVarDeclODRUsed(Var, Loc, *this, 13361 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13362 } 13363 13364 MaybeODRUseExprs.clear(); 13365 } 13366 13367 13368 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13369 VarDecl *Var, Expr *E) { 13370 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13371 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13372 Var->setReferenced(); 13373 13374 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13375 bool MarkODRUsed = true; 13376 13377 // If the context is not potentially evaluated, this is not an odr-use and 13378 // does not trigger instantiation. 13379 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13380 if (SemaRef.isUnevaluatedContext()) 13381 return; 13382 13383 // If we don't yet know whether this context is going to end up being an 13384 // evaluated context, and we're referencing a variable from an enclosing 13385 // scope, add a potential capture. 13386 // 13387 // FIXME: Is this necessary? These contexts are only used for default 13388 // arguments, where local variables can't be used. 13389 const bool RefersToEnclosingScope = 13390 (SemaRef.CurContext != Var->getDeclContext() && 13391 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13392 if (RefersToEnclosingScope) { 13393 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13394 // If a variable could potentially be odr-used, defer marking it so 13395 // until we finish analyzing the full expression for any 13396 // lvalue-to-rvalue 13397 // or discarded value conversions that would obviate odr-use. 13398 // Add it to the list of potential captures that will be analyzed 13399 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13400 // unless the variable is a reference that was initialized by a constant 13401 // expression (this will never need to be captured or odr-used). 13402 assert(E && "Capture variable should be used in an expression."); 13403 if (!Var->getType()->isReferenceType() || 13404 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13405 LSI->addPotentialCapture(E->IgnoreParens()); 13406 } 13407 } 13408 13409 if (!isTemplateInstantiation(TSK)) 13410 return; 13411 13412 // Instantiate, but do not mark as odr-used, variable templates. 13413 MarkODRUsed = false; 13414 } 13415 13416 VarTemplateSpecializationDecl *VarSpec = 13417 dyn_cast<VarTemplateSpecializationDecl>(Var); 13418 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13419 "Can't instantiate a partial template specialization."); 13420 13421 // Perform implicit instantiation of static data members, static data member 13422 // templates of class templates, and variable template specializations. Delay 13423 // instantiations of variable templates, except for those that could be used 13424 // in a constant expression. 13425 if (isTemplateInstantiation(TSK)) { 13426 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13427 13428 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13429 if (Var->getPointOfInstantiation().isInvalid()) { 13430 // This is a modification of an existing AST node. Notify listeners. 13431 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13432 L->StaticDataMemberInstantiated(Var); 13433 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13434 // Don't bother trying to instantiate it again, unless we might need 13435 // its initializer before we get to the end of the TU. 13436 TryInstantiating = false; 13437 } 13438 13439 if (Var->getPointOfInstantiation().isInvalid()) 13440 Var->setTemplateSpecializationKind(TSK, Loc); 13441 13442 if (TryInstantiating) { 13443 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13444 bool InstantiationDependent = false; 13445 bool IsNonDependent = 13446 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13447 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13448 : true; 13449 13450 // Do not instantiate specializations that are still type-dependent. 13451 if (IsNonDependent) { 13452 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13453 // Do not defer instantiations of variables which could be used in a 13454 // constant expression. 13455 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13456 } else { 13457 SemaRef.PendingInstantiations 13458 .push_back(std::make_pair(Var, PointOfInstantiation)); 13459 } 13460 } 13461 } 13462 } 13463 13464 if(!MarkODRUsed) return; 13465 13466 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13467 // the requirements for appearing in a constant expression (5.19) and, if 13468 // it is an object, the lvalue-to-rvalue conversion (4.1) 13469 // is immediately applied." We check the first part here, and 13470 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13471 // Note that we use the C++11 definition everywhere because nothing in 13472 // C++03 depends on whether we get the C++03 version correct. The second 13473 // part does not apply to references, since they are not objects. 13474 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13475 // A reference initialized by a constant expression can never be 13476 // odr-used, so simply ignore it. 13477 if (!Var->getType()->isReferenceType()) 13478 SemaRef.MaybeODRUseExprs.insert(E); 13479 } else 13480 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13481 /*MaxFunctionScopeIndex ptr*/ nullptr); 13482 } 13483 13484 /// \brief Mark a variable referenced, and check whether it is odr-used 13485 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13486 /// used directly for normal expressions referring to VarDecl. 13487 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13488 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13489 } 13490 13491 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13492 Decl *D, Expr *E, bool OdrUse) { 13493 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13494 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13495 return; 13496 } 13497 13498 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13499 13500 // If this is a call to a method via a cast, also mark the method in the 13501 // derived class used in case codegen can devirtualize the call. 13502 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13503 if (!ME) 13504 return; 13505 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13506 if (!MD) 13507 return; 13508 // Only attempt to devirtualize if this is truly a virtual call. 13509 bool IsVirtualCall = MD->isVirtual() && 13510 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13511 if (!IsVirtualCall) 13512 return; 13513 const Expr *Base = ME->getBase(); 13514 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13515 if (!MostDerivedClassDecl) 13516 return; 13517 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13518 if (!DM || DM->isPure()) 13519 return; 13520 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13521 } 13522 13523 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13524 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13525 // TODO: update this with DR# once a defect report is filed. 13526 // C++11 defect. The address of a pure member should not be an ODR use, even 13527 // if it's a qualified reference. 13528 bool OdrUse = true; 13529 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13530 if (Method->isVirtual()) 13531 OdrUse = false; 13532 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13533 } 13534 13535 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13536 void Sema::MarkMemberReferenced(MemberExpr *E) { 13537 // C++11 [basic.def.odr]p2: 13538 // A non-overloaded function whose name appears as a potentially-evaluated 13539 // expression or a member of a set of candidate functions, if selected by 13540 // overload resolution when referred to from a potentially-evaluated 13541 // expression, is odr-used, unless it is a pure virtual function and its 13542 // name is not explicitly qualified. 13543 bool OdrUse = true; 13544 if (E->performsVirtualDispatch(getLangOpts())) { 13545 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13546 if (Method->isPure()) 13547 OdrUse = false; 13548 } 13549 SourceLocation Loc = E->getMemberLoc().isValid() ? 13550 E->getMemberLoc() : E->getLocStart(); 13551 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13552 } 13553 13554 /// \brief Perform marking for a reference to an arbitrary declaration. It 13555 /// marks the declaration referenced, and performs odr-use checking for 13556 /// functions and variables. This method should not be used when building a 13557 /// normal expression which refers to a variable. 13558 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13559 if (OdrUse) { 13560 if (auto *VD = dyn_cast<VarDecl>(D)) { 13561 MarkVariableReferenced(Loc, VD); 13562 return; 13563 } 13564 } 13565 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13566 MarkFunctionReferenced(Loc, FD, OdrUse); 13567 return; 13568 } 13569 D->setReferenced(); 13570 } 13571 13572 namespace { 13573 // Mark all of the declarations referenced 13574 // FIXME: Not fully implemented yet! We need to have a better understanding 13575 // of when we're entering 13576 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13577 Sema &S; 13578 SourceLocation Loc; 13579 13580 public: 13581 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13582 13583 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13584 13585 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13586 bool TraverseRecordType(RecordType *T); 13587 }; 13588 } 13589 13590 bool MarkReferencedDecls::TraverseTemplateArgument( 13591 const TemplateArgument &Arg) { 13592 if (Arg.getKind() == TemplateArgument::Declaration) { 13593 if (Decl *D = Arg.getAsDecl()) 13594 S.MarkAnyDeclReferenced(Loc, D, true); 13595 } 13596 13597 return Inherited::TraverseTemplateArgument(Arg); 13598 } 13599 13600 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13601 if (ClassTemplateSpecializationDecl *Spec 13602 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13603 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13604 return TraverseTemplateArguments(Args.data(), Args.size()); 13605 } 13606 13607 return true; 13608 } 13609 13610 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13611 MarkReferencedDecls Marker(*this, Loc); 13612 Marker.TraverseType(Context.getCanonicalType(T)); 13613 } 13614 13615 namespace { 13616 /// \brief Helper class that marks all of the declarations referenced by 13617 /// potentially-evaluated subexpressions as "referenced". 13618 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13619 Sema &S; 13620 bool SkipLocalVariables; 13621 13622 public: 13623 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13624 13625 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13626 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13627 13628 void VisitDeclRefExpr(DeclRefExpr *E) { 13629 // If we were asked not to visit local variables, don't. 13630 if (SkipLocalVariables) { 13631 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13632 if (VD->hasLocalStorage()) 13633 return; 13634 } 13635 13636 S.MarkDeclRefReferenced(E); 13637 } 13638 13639 void VisitMemberExpr(MemberExpr *E) { 13640 S.MarkMemberReferenced(E); 13641 Inherited::VisitMemberExpr(E); 13642 } 13643 13644 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13645 S.MarkFunctionReferenced(E->getLocStart(), 13646 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13647 Visit(E->getSubExpr()); 13648 } 13649 13650 void VisitCXXNewExpr(CXXNewExpr *E) { 13651 if (E->getOperatorNew()) 13652 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13653 if (E->getOperatorDelete()) 13654 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13655 Inherited::VisitCXXNewExpr(E); 13656 } 13657 13658 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13659 if (E->getOperatorDelete()) 13660 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13661 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13662 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13663 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13664 S.MarkFunctionReferenced(E->getLocStart(), 13665 S.LookupDestructor(Record)); 13666 } 13667 13668 Inherited::VisitCXXDeleteExpr(E); 13669 } 13670 13671 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13672 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13673 Inherited::VisitCXXConstructExpr(E); 13674 } 13675 13676 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13677 Visit(E->getExpr()); 13678 } 13679 13680 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13681 Inherited::VisitImplicitCastExpr(E); 13682 13683 if (E->getCastKind() == CK_LValueToRValue) 13684 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13685 } 13686 }; 13687 } 13688 13689 /// \brief Mark any declarations that appear within this expression or any 13690 /// potentially-evaluated subexpressions as "referenced". 13691 /// 13692 /// \param SkipLocalVariables If true, don't mark local variables as 13693 /// 'referenced'. 13694 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13695 bool SkipLocalVariables) { 13696 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13697 } 13698 13699 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 13700 /// of the program being compiled. 13701 /// 13702 /// This routine emits the given diagnostic when the code currently being 13703 /// type-checked is "potentially evaluated", meaning that there is a 13704 /// possibility that the code will actually be executable. Code in sizeof() 13705 /// expressions, code used only during overload resolution, etc., are not 13706 /// potentially evaluated. This routine will suppress such diagnostics or, 13707 /// in the absolutely nutty case of potentially potentially evaluated 13708 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 13709 /// later. 13710 /// 13711 /// This routine should be used for all diagnostics that describe the run-time 13712 /// behavior of a program, such as passing a non-POD value through an ellipsis. 13713 /// Failure to do so will likely result in spurious diagnostics or failures 13714 /// during overload resolution or within sizeof/alignof/typeof/typeid. 13715 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 13716 const PartialDiagnostic &PD) { 13717 switch (ExprEvalContexts.back().Context) { 13718 case Unevaluated: 13719 case UnevaluatedAbstract: 13720 // The argument will never be evaluated, so don't complain. 13721 break; 13722 13723 case ConstantEvaluated: 13724 // Relevant diagnostics should be produced by constant evaluation. 13725 break; 13726 13727 case PotentiallyEvaluated: 13728 case PotentiallyEvaluatedIfUsed: 13729 if (Statement && getCurFunctionOrMethodDecl()) { 13730 FunctionScopes.back()->PossiblyUnreachableDiags. 13731 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 13732 } 13733 else 13734 Diag(Loc, PD); 13735 13736 return true; 13737 } 13738 13739 return false; 13740 } 13741 13742 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 13743 CallExpr *CE, FunctionDecl *FD) { 13744 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 13745 return false; 13746 13747 // If we're inside a decltype's expression, don't check for a valid return 13748 // type or construct temporaries until we know whether this is the last call. 13749 if (ExprEvalContexts.back().IsDecltype) { 13750 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 13751 return false; 13752 } 13753 13754 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 13755 FunctionDecl *FD; 13756 CallExpr *CE; 13757 13758 public: 13759 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 13760 : FD(FD), CE(CE) { } 13761 13762 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 13763 if (!FD) { 13764 S.Diag(Loc, diag::err_call_incomplete_return) 13765 << T << CE->getSourceRange(); 13766 return; 13767 } 13768 13769 S.Diag(Loc, diag::err_call_function_incomplete_return) 13770 << CE->getSourceRange() << FD->getDeclName() << T; 13771 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 13772 << FD->getDeclName(); 13773 } 13774 } Diagnoser(FD, CE); 13775 13776 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 13777 return true; 13778 13779 return false; 13780 } 13781 13782 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 13783 // will prevent this condition from triggering, which is what we want. 13784 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 13785 SourceLocation Loc; 13786 13787 unsigned diagnostic = diag::warn_condition_is_assignment; 13788 bool IsOrAssign = false; 13789 13790 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 13791 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 13792 return; 13793 13794 IsOrAssign = Op->getOpcode() == BO_OrAssign; 13795 13796 // Greylist some idioms by putting them into a warning subcategory. 13797 if (ObjCMessageExpr *ME 13798 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 13799 Selector Sel = ME->getSelector(); 13800 13801 // self = [<foo> init...] 13802 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 13803 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13804 13805 // <foo> = [<bar> nextObject] 13806 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 13807 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13808 } 13809 13810 Loc = Op->getOperatorLoc(); 13811 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 13812 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 13813 return; 13814 13815 IsOrAssign = Op->getOperator() == OO_PipeEqual; 13816 Loc = Op->getOperatorLoc(); 13817 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 13818 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 13819 else { 13820 // Not an assignment. 13821 return; 13822 } 13823 13824 Diag(Loc, diagnostic) << E->getSourceRange(); 13825 13826 SourceLocation Open = E->getLocStart(); 13827 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 13828 Diag(Loc, diag::note_condition_assign_silence) 13829 << FixItHint::CreateInsertion(Open, "(") 13830 << FixItHint::CreateInsertion(Close, ")"); 13831 13832 if (IsOrAssign) 13833 Diag(Loc, diag::note_condition_or_assign_to_comparison) 13834 << FixItHint::CreateReplacement(Loc, "!="); 13835 else 13836 Diag(Loc, diag::note_condition_assign_to_comparison) 13837 << FixItHint::CreateReplacement(Loc, "=="); 13838 } 13839 13840 /// \brief Redundant parentheses over an equality comparison can indicate 13841 /// that the user intended an assignment used as condition. 13842 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 13843 // Don't warn if the parens came from a macro. 13844 SourceLocation parenLoc = ParenE->getLocStart(); 13845 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 13846 return; 13847 // Don't warn for dependent expressions. 13848 if (ParenE->isTypeDependent()) 13849 return; 13850 13851 Expr *E = ParenE->IgnoreParens(); 13852 13853 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 13854 if (opE->getOpcode() == BO_EQ && 13855 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 13856 == Expr::MLV_Valid) { 13857 SourceLocation Loc = opE->getOperatorLoc(); 13858 13859 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 13860 SourceRange ParenERange = ParenE->getSourceRange(); 13861 Diag(Loc, diag::note_equality_comparison_silence) 13862 << FixItHint::CreateRemoval(ParenERange.getBegin()) 13863 << FixItHint::CreateRemoval(ParenERange.getEnd()); 13864 Diag(Loc, diag::note_equality_comparison_to_assign) 13865 << FixItHint::CreateReplacement(Loc, "="); 13866 } 13867 } 13868 13869 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 13870 DiagnoseAssignmentAsCondition(E); 13871 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 13872 DiagnoseEqualityWithExtraParens(parenE); 13873 13874 ExprResult result = CheckPlaceholderExpr(E); 13875 if (result.isInvalid()) return ExprError(); 13876 E = result.get(); 13877 13878 if (!E->isTypeDependent()) { 13879 if (getLangOpts().CPlusPlus) 13880 return CheckCXXBooleanCondition(E); // C++ 6.4p4 13881 13882 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 13883 if (ERes.isInvalid()) 13884 return ExprError(); 13885 E = ERes.get(); 13886 13887 QualType T = E->getType(); 13888 if (!T->isScalarType()) { // C99 6.8.4.1p1 13889 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 13890 << T << E->getSourceRange(); 13891 return ExprError(); 13892 } 13893 CheckBoolLikeConversion(E, Loc); 13894 } 13895 13896 return E; 13897 } 13898 13899 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 13900 Expr *SubExpr) { 13901 if (!SubExpr) 13902 return ExprError(); 13903 13904 return CheckBooleanCondition(SubExpr, Loc); 13905 } 13906 13907 namespace { 13908 /// A visitor for rebuilding a call to an __unknown_any expression 13909 /// to have an appropriate type. 13910 struct RebuildUnknownAnyFunction 13911 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 13912 13913 Sema &S; 13914 13915 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 13916 13917 ExprResult VisitStmt(Stmt *S) { 13918 llvm_unreachable("unexpected statement!"); 13919 } 13920 13921 ExprResult VisitExpr(Expr *E) { 13922 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 13923 << E->getSourceRange(); 13924 return ExprError(); 13925 } 13926 13927 /// Rebuild an expression which simply semantically wraps another 13928 /// expression which it shares the type and value kind of. 13929 template <class T> ExprResult rebuildSugarExpr(T *E) { 13930 ExprResult SubResult = Visit(E->getSubExpr()); 13931 if (SubResult.isInvalid()) return ExprError(); 13932 13933 Expr *SubExpr = SubResult.get(); 13934 E->setSubExpr(SubExpr); 13935 E->setType(SubExpr->getType()); 13936 E->setValueKind(SubExpr->getValueKind()); 13937 assert(E->getObjectKind() == OK_Ordinary); 13938 return E; 13939 } 13940 13941 ExprResult VisitParenExpr(ParenExpr *E) { 13942 return rebuildSugarExpr(E); 13943 } 13944 13945 ExprResult VisitUnaryExtension(UnaryOperator *E) { 13946 return rebuildSugarExpr(E); 13947 } 13948 13949 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 13950 ExprResult SubResult = Visit(E->getSubExpr()); 13951 if (SubResult.isInvalid()) return ExprError(); 13952 13953 Expr *SubExpr = SubResult.get(); 13954 E->setSubExpr(SubExpr); 13955 E->setType(S.Context.getPointerType(SubExpr->getType())); 13956 assert(E->getValueKind() == VK_RValue); 13957 assert(E->getObjectKind() == OK_Ordinary); 13958 return E; 13959 } 13960 13961 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 13962 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 13963 13964 E->setType(VD->getType()); 13965 13966 assert(E->getValueKind() == VK_RValue); 13967 if (S.getLangOpts().CPlusPlus && 13968 !(isa<CXXMethodDecl>(VD) && 13969 cast<CXXMethodDecl>(VD)->isInstance())) 13970 E->setValueKind(VK_LValue); 13971 13972 return E; 13973 } 13974 13975 ExprResult VisitMemberExpr(MemberExpr *E) { 13976 return resolveDecl(E, E->getMemberDecl()); 13977 } 13978 13979 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 13980 return resolveDecl(E, E->getDecl()); 13981 } 13982 }; 13983 } 13984 13985 /// Given a function expression of unknown-any type, try to rebuild it 13986 /// to have a function type. 13987 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 13988 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 13989 if (Result.isInvalid()) return ExprError(); 13990 return S.DefaultFunctionArrayConversion(Result.get()); 13991 } 13992 13993 namespace { 13994 /// A visitor for rebuilding an expression of type __unknown_anytype 13995 /// into one which resolves the type directly on the referring 13996 /// expression. Strict preservation of the original source 13997 /// structure is not a goal. 13998 struct RebuildUnknownAnyExpr 13999 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14000 14001 Sema &S; 14002 14003 /// The current destination type. 14004 QualType DestType; 14005 14006 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14007 : S(S), DestType(CastType) {} 14008 14009 ExprResult VisitStmt(Stmt *S) { 14010 llvm_unreachable("unexpected statement!"); 14011 } 14012 14013 ExprResult VisitExpr(Expr *E) { 14014 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14015 << E->getSourceRange(); 14016 return ExprError(); 14017 } 14018 14019 ExprResult VisitCallExpr(CallExpr *E); 14020 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14021 14022 /// Rebuild an expression which simply semantically wraps another 14023 /// expression which it shares the type and value kind of. 14024 template <class T> ExprResult rebuildSugarExpr(T *E) { 14025 ExprResult SubResult = Visit(E->getSubExpr()); 14026 if (SubResult.isInvalid()) return ExprError(); 14027 Expr *SubExpr = SubResult.get(); 14028 E->setSubExpr(SubExpr); 14029 E->setType(SubExpr->getType()); 14030 E->setValueKind(SubExpr->getValueKind()); 14031 assert(E->getObjectKind() == OK_Ordinary); 14032 return E; 14033 } 14034 14035 ExprResult VisitParenExpr(ParenExpr *E) { 14036 return rebuildSugarExpr(E); 14037 } 14038 14039 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14040 return rebuildSugarExpr(E); 14041 } 14042 14043 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14044 const PointerType *Ptr = DestType->getAs<PointerType>(); 14045 if (!Ptr) { 14046 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14047 << E->getSourceRange(); 14048 return ExprError(); 14049 } 14050 assert(E->getValueKind() == VK_RValue); 14051 assert(E->getObjectKind() == OK_Ordinary); 14052 E->setType(DestType); 14053 14054 // Build the sub-expression as if it were an object of the pointee type. 14055 DestType = Ptr->getPointeeType(); 14056 ExprResult SubResult = Visit(E->getSubExpr()); 14057 if (SubResult.isInvalid()) return ExprError(); 14058 E->setSubExpr(SubResult.get()); 14059 return E; 14060 } 14061 14062 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14063 14064 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14065 14066 ExprResult VisitMemberExpr(MemberExpr *E) { 14067 return resolveDecl(E, E->getMemberDecl()); 14068 } 14069 14070 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14071 return resolveDecl(E, E->getDecl()); 14072 } 14073 }; 14074 } 14075 14076 /// Rebuilds a call expression which yielded __unknown_anytype. 14077 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14078 Expr *CalleeExpr = E->getCallee(); 14079 14080 enum FnKind { 14081 FK_MemberFunction, 14082 FK_FunctionPointer, 14083 FK_BlockPointer 14084 }; 14085 14086 FnKind Kind; 14087 QualType CalleeType = CalleeExpr->getType(); 14088 if (CalleeType == S.Context.BoundMemberTy) { 14089 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14090 Kind = FK_MemberFunction; 14091 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14092 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14093 CalleeType = Ptr->getPointeeType(); 14094 Kind = FK_FunctionPointer; 14095 } else { 14096 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14097 Kind = FK_BlockPointer; 14098 } 14099 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14100 14101 // Verify that this is a legal result type of a function. 14102 if (DestType->isArrayType() || DestType->isFunctionType()) { 14103 unsigned diagID = diag::err_func_returning_array_function; 14104 if (Kind == FK_BlockPointer) 14105 diagID = diag::err_block_returning_array_function; 14106 14107 S.Diag(E->getExprLoc(), diagID) 14108 << DestType->isFunctionType() << DestType; 14109 return ExprError(); 14110 } 14111 14112 // Otherwise, go ahead and set DestType as the call's result. 14113 E->setType(DestType.getNonLValueExprType(S.Context)); 14114 E->setValueKind(Expr::getValueKindForType(DestType)); 14115 assert(E->getObjectKind() == OK_Ordinary); 14116 14117 // Rebuild the function type, replacing the result type with DestType. 14118 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14119 if (Proto) { 14120 // __unknown_anytype(...) is a special case used by the debugger when 14121 // it has no idea what a function's signature is. 14122 // 14123 // We want to build this call essentially under the K&R 14124 // unprototyped rules, but making a FunctionNoProtoType in C++ 14125 // would foul up all sorts of assumptions. However, we cannot 14126 // simply pass all arguments as variadic arguments, nor can we 14127 // portably just call the function under a non-variadic type; see 14128 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14129 // However, it turns out that in practice it is generally safe to 14130 // call a function declared as "A foo(B,C,D);" under the prototype 14131 // "A foo(B,C,D,...);". The only known exception is with the 14132 // Windows ABI, where any variadic function is implicitly cdecl 14133 // regardless of its normal CC. Therefore we change the parameter 14134 // types to match the types of the arguments. 14135 // 14136 // This is a hack, but it is far superior to moving the 14137 // corresponding target-specific code from IR-gen to Sema/AST. 14138 14139 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14140 SmallVector<QualType, 8> ArgTypes; 14141 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14142 ArgTypes.reserve(E->getNumArgs()); 14143 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14144 Expr *Arg = E->getArg(i); 14145 QualType ArgType = Arg->getType(); 14146 if (E->isLValue()) { 14147 ArgType = S.Context.getLValueReferenceType(ArgType); 14148 } else if (E->isXValue()) { 14149 ArgType = S.Context.getRValueReferenceType(ArgType); 14150 } 14151 ArgTypes.push_back(ArgType); 14152 } 14153 ParamTypes = ArgTypes; 14154 } 14155 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14156 Proto->getExtProtoInfo()); 14157 } else { 14158 DestType = S.Context.getFunctionNoProtoType(DestType, 14159 FnType->getExtInfo()); 14160 } 14161 14162 // Rebuild the appropriate pointer-to-function type. 14163 switch (Kind) { 14164 case FK_MemberFunction: 14165 // Nothing to do. 14166 break; 14167 14168 case FK_FunctionPointer: 14169 DestType = S.Context.getPointerType(DestType); 14170 break; 14171 14172 case FK_BlockPointer: 14173 DestType = S.Context.getBlockPointerType(DestType); 14174 break; 14175 } 14176 14177 // Finally, we can recurse. 14178 ExprResult CalleeResult = Visit(CalleeExpr); 14179 if (!CalleeResult.isUsable()) return ExprError(); 14180 E->setCallee(CalleeResult.get()); 14181 14182 // Bind a temporary if necessary. 14183 return S.MaybeBindToTemporary(E); 14184 } 14185 14186 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14187 // Verify that this is a legal result type of a call. 14188 if (DestType->isArrayType() || DestType->isFunctionType()) { 14189 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14190 << DestType->isFunctionType() << DestType; 14191 return ExprError(); 14192 } 14193 14194 // Rewrite the method result type if available. 14195 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14196 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14197 Method->setReturnType(DestType); 14198 } 14199 14200 // Change the type of the message. 14201 E->setType(DestType.getNonReferenceType()); 14202 E->setValueKind(Expr::getValueKindForType(DestType)); 14203 14204 return S.MaybeBindToTemporary(E); 14205 } 14206 14207 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14208 // The only case we should ever see here is a function-to-pointer decay. 14209 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14210 assert(E->getValueKind() == VK_RValue); 14211 assert(E->getObjectKind() == OK_Ordinary); 14212 14213 E->setType(DestType); 14214 14215 // Rebuild the sub-expression as the pointee (function) type. 14216 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14217 14218 ExprResult Result = Visit(E->getSubExpr()); 14219 if (!Result.isUsable()) return ExprError(); 14220 14221 E->setSubExpr(Result.get()); 14222 return E; 14223 } else if (E->getCastKind() == CK_LValueToRValue) { 14224 assert(E->getValueKind() == VK_RValue); 14225 assert(E->getObjectKind() == OK_Ordinary); 14226 14227 assert(isa<BlockPointerType>(E->getType())); 14228 14229 E->setType(DestType); 14230 14231 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14232 DestType = S.Context.getLValueReferenceType(DestType); 14233 14234 ExprResult Result = Visit(E->getSubExpr()); 14235 if (!Result.isUsable()) return ExprError(); 14236 14237 E->setSubExpr(Result.get()); 14238 return E; 14239 } else { 14240 llvm_unreachable("Unhandled cast type!"); 14241 } 14242 } 14243 14244 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14245 ExprValueKind ValueKind = VK_LValue; 14246 QualType Type = DestType; 14247 14248 // We know how to make this work for certain kinds of decls: 14249 14250 // - functions 14251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14252 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14253 DestType = Ptr->getPointeeType(); 14254 ExprResult Result = resolveDecl(E, VD); 14255 if (Result.isInvalid()) return ExprError(); 14256 return S.ImpCastExprToType(Result.get(), Type, 14257 CK_FunctionToPointerDecay, VK_RValue); 14258 } 14259 14260 if (!Type->isFunctionType()) { 14261 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14262 << VD << E->getSourceRange(); 14263 return ExprError(); 14264 } 14265 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14266 // We must match the FunctionDecl's type to the hack introduced in 14267 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14268 // type. See the lengthy commentary in that routine. 14269 QualType FDT = FD->getType(); 14270 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14271 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14272 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14273 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14274 SourceLocation Loc = FD->getLocation(); 14275 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14276 FD->getDeclContext(), 14277 Loc, Loc, FD->getNameInfo().getName(), 14278 DestType, FD->getTypeSourceInfo(), 14279 SC_None, false/*isInlineSpecified*/, 14280 FD->hasPrototype(), 14281 false/*isConstexprSpecified*/); 14282 14283 if (FD->getQualifier()) 14284 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14285 14286 SmallVector<ParmVarDecl*, 16> Params; 14287 for (const auto &AI : FT->param_types()) { 14288 ParmVarDecl *Param = 14289 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14290 Param->setScopeInfo(0, Params.size()); 14291 Params.push_back(Param); 14292 } 14293 NewFD->setParams(Params); 14294 DRE->setDecl(NewFD); 14295 VD = DRE->getDecl(); 14296 } 14297 } 14298 14299 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14300 if (MD->isInstance()) { 14301 ValueKind = VK_RValue; 14302 Type = S.Context.BoundMemberTy; 14303 } 14304 14305 // Function references aren't l-values in C. 14306 if (!S.getLangOpts().CPlusPlus) 14307 ValueKind = VK_RValue; 14308 14309 // - variables 14310 } else if (isa<VarDecl>(VD)) { 14311 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14312 Type = RefTy->getPointeeType(); 14313 } else if (Type->isFunctionType()) { 14314 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14315 << VD << E->getSourceRange(); 14316 return ExprError(); 14317 } 14318 14319 // - nothing else 14320 } else { 14321 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14322 << VD << E->getSourceRange(); 14323 return ExprError(); 14324 } 14325 14326 // Modifying the declaration like this is friendly to IR-gen but 14327 // also really dangerous. 14328 VD->setType(DestType); 14329 E->setType(Type); 14330 E->setValueKind(ValueKind); 14331 return E; 14332 } 14333 14334 /// Check a cast of an unknown-any type. We intentionally only 14335 /// trigger this for C-style casts. 14336 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14337 Expr *CastExpr, CastKind &CastKind, 14338 ExprValueKind &VK, CXXCastPath &Path) { 14339 // Rewrite the casted expression from scratch. 14340 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14341 if (!result.isUsable()) return ExprError(); 14342 14343 CastExpr = result.get(); 14344 VK = CastExpr->getValueKind(); 14345 CastKind = CK_NoOp; 14346 14347 return CastExpr; 14348 } 14349 14350 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14351 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14352 } 14353 14354 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14355 Expr *arg, QualType ¶mType) { 14356 // If the syntactic form of the argument is not an explicit cast of 14357 // any sort, just do default argument promotion. 14358 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14359 if (!castArg) { 14360 ExprResult result = DefaultArgumentPromotion(arg); 14361 if (result.isInvalid()) return ExprError(); 14362 paramType = result.get()->getType(); 14363 return result; 14364 } 14365 14366 // Otherwise, use the type that was written in the explicit cast. 14367 assert(!arg->hasPlaceholderType()); 14368 paramType = castArg->getTypeAsWritten(); 14369 14370 // Copy-initialize a parameter of that type. 14371 InitializedEntity entity = 14372 InitializedEntity::InitializeParameter(Context, paramType, 14373 /*consumed*/ false); 14374 return PerformCopyInitialization(entity, callLoc, arg); 14375 } 14376 14377 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14378 Expr *orig = E; 14379 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14380 while (true) { 14381 E = E->IgnoreParenImpCasts(); 14382 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14383 E = call->getCallee(); 14384 diagID = diag::err_uncasted_call_of_unknown_any; 14385 } else { 14386 break; 14387 } 14388 } 14389 14390 SourceLocation loc; 14391 NamedDecl *d; 14392 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14393 loc = ref->getLocation(); 14394 d = ref->getDecl(); 14395 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14396 loc = mem->getMemberLoc(); 14397 d = mem->getMemberDecl(); 14398 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14399 diagID = diag::err_uncasted_call_of_unknown_any; 14400 loc = msg->getSelectorStartLoc(); 14401 d = msg->getMethodDecl(); 14402 if (!d) { 14403 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14404 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14405 << orig->getSourceRange(); 14406 return ExprError(); 14407 } 14408 } else { 14409 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14410 << E->getSourceRange(); 14411 return ExprError(); 14412 } 14413 14414 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14415 14416 // Never recoverable. 14417 return ExprError(); 14418 } 14419 14420 /// Check for operands with placeholder types and complain if found. 14421 /// Returns true if there was an error and no recovery was possible. 14422 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14423 if (!getLangOpts().CPlusPlus) { 14424 // C cannot handle TypoExpr nodes on either side of a binop because it 14425 // doesn't handle dependent types properly, so make sure any TypoExprs have 14426 // been dealt with before checking the operands. 14427 ExprResult Result = CorrectDelayedTyposInExpr(E); 14428 if (!Result.isUsable()) return ExprError(); 14429 E = Result.get(); 14430 } 14431 14432 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14433 if (!placeholderType) return E; 14434 14435 switch (placeholderType->getKind()) { 14436 14437 // Overloaded expressions. 14438 case BuiltinType::Overload: { 14439 // Try to resolve a single function template specialization. 14440 // This is obligatory. 14441 ExprResult result = E; 14442 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14443 return result; 14444 14445 // If that failed, try to recover with a call. 14446 } else { 14447 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14448 /*complain*/ true); 14449 return result; 14450 } 14451 } 14452 14453 // Bound member functions. 14454 case BuiltinType::BoundMember: { 14455 ExprResult result = E; 14456 const Expr *BME = E->IgnoreParens(); 14457 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14458 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14459 if (isa<CXXPseudoDestructorExpr>(BME)) { 14460 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14461 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14462 if (ME->getMemberNameInfo().getName().getNameKind() == 14463 DeclarationName::CXXDestructorName) 14464 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14465 } 14466 tryToRecoverWithCall(result, PD, 14467 /*complain*/ true); 14468 return result; 14469 } 14470 14471 // ARC unbridged casts. 14472 case BuiltinType::ARCUnbridgedCast: { 14473 Expr *realCast = stripARCUnbridgedCast(E); 14474 diagnoseARCUnbridgedCast(realCast); 14475 return realCast; 14476 } 14477 14478 // Expressions of unknown type. 14479 case BuiltinType::UnknownAny: 14480 return diagnoseUnknownAnyExpr(*this, E); 14481 14482 // Pseudo-objects. 14483 case BuiltinType::PseudoObject: 14484 return checkPseudoObjectRValue(E); 14485 14486 case BuiltinType::BuiltinFn: { 14487 // Accept __noop without parens by implicitly converting it to a call expr. 14488 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14489 if (DRE) { 14490 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14491 if (FD->getBuiltinID() == Builtin::BI__noop) { 14492 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14493 CK_BuiltinFnToFnPtr).get(); 14494 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14495 VK_RValue, SourceLocation()); 14496 } 14497 } 14498 14499 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14500 return ExprError(); 14501 } 14502 14503 // Expressions of unknown type. 14504 case BuiltinType::OMPArraySection: 14505 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14506 return ExprError(); 14507 14508 // Everything else should be impossible. 14509 #define BUILTIN_TYPE(Id, SingletonId) \ 14510 case BuiltinType::Id: 14511 #define PLACEHOLDER_TYPE(Id, SingletonId) 14512 #include "clang/AST/BuiltinTypes.def" 14513 break; 14514 } 14515 14516 llvm_unreachable("invalid placeholder type!"); 14517 } 14518 14519 bool Sema::CheckCaseExpression(Expr *E) { 14520 if (E->isTypeDependent()) 14521 return true; 14522 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14523 return E->getType()->isIntegralOrEnumerationType(); 14524 return false; 14525 } 14526 14527 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14528 ExprResult 14529 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14530 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14531 "Unknown Objective-C Boolean value!"); 14532 QualType BoolT = Context.ObjCBuiltinBoolTy; 14533 if (!Context.getBOOLDecl()) { 14534 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14535 Sema::LookupOrdinaryName); 14536 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14537 NamedDecl *ND = Result.getFoundDecl(); 14538 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14539 Context.setBOOLDecl(TD); 14540 } 14541 } 14542 if (Context.getBOOLDecl()) 14543 BoolT = Context.getBOOLType(); 14544 return new (Context) 14545 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14546 } 14547