1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/ExprOpenMP.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (D->hasAttr<UnusedAttr>()) { 80 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 81 if (DC && !DC->hasAttr<UnusedAttr>()) 82 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 83 } 84 } 85 86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 87 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 88 if (!OMD) 89 return false; 90 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 91 if (!OID) 92 return false; 93 94 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 95 if (ObjCMethodDecl *CatMeth = 96 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 97 if (!CatMeth->hasAttr<AvailabilityAttr>()) 98 return true; 99 return false; 100 } 101 102 static AvailabilityResult 103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 104 const ObjCInterfaceDecl *UnknownObjCClass, 105 bool ObjCPropertyAccess) { 106 // See if this declaration is unavailable or deprecated. 107 std::string Message; 108 AvailabilityResult Result = D->getAvailability(&Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(&Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(&Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(&Message); 136 } 137 138 const ObjCPropertyDecl *ObjCPDecl = nullptr; 139 if (Result == AR_Deprecated || Result == AR_Unavailable || 140 AR_NotYetIntroduced) { 141 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 142 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 143 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 144 if (PDeclResult == Result) 145 ObjCPDecl = PD; 146 } 147 } 148 } 149 150 switch (Result) { 151 case AR_Available: 152 break; 153 154 case AR_Deprecated: 155 if (S.getCurContextAvailability() != AR_Deprecated) 156 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 157 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 158 ObjCPropertyAccess); 159 break; 160 161 case AR_NotYetIntroduced: { 162 // Don't do this for enums, they can't be redeclared. 163 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 164 break; 165 166 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 167 // Objective-C method declarations in categories are not modelled as 168 // redeclarations, so manually look for a redeclaration in a category 169 // if necessary. 170 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 171 Warn = false; 172 // In general, D will point to the most recent redeclaration. However, 173 // for `@class A;` decls, this isn't true -- manually go through the 174 // redecl chain in that case. 175 if (Warn && isa<ObjCInterfaceDecl>(D)) 176 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 177 Redecl = Redecl->getPreviousDecl()) 178 if (!Redecl->hasAttr<AvailabilityAttr>() || 179 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 180 Warn = false; 181 182 if (Warn) 183 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 184 UnknownObjCClass, ObjCPDecl, 185 ObjCPropertyAccess); 186 break; 187 } 188 189 case AR_Unavailable: 190 if (S.getCurContextAvailability() != AR_Unavailable) 191 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 192 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 193 ObjCPropertyAccess); 194 break; 195 196 } 197 return Result; 198 } 199 200 /// \brief Emit a note explaining that this function is deleted. 201 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 202 assert(Decl->isDeleted()); 203 204 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 205 206 if (Method && Method->isDeleted() && Method->isDefaulted()) { 207 // If the method was explicitly defaulted, point at that declaration. 208 if (!Method->isImplicit()) 209 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 210 211 // Try to diagnose why this special member function was implicitly 212 // deleted. This might fail, if that reason no longer applies. 213 CXXSpecialMember CSM = getSpecialMember(Method); 214 if (CSM != CXXInvalid) 215 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 216 217 return; 218 } 219 220 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 221 if (CXXConstructorDecl *BaseCD = 222 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 223 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 224 if (BaseCD->isDeleted()) { 225 NoteDeletedFunction(BaseCD); 226 } else { 227 // FIXME: An explanation of why exactly it can't be inherited 228 // would be nice. 229 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 230 } 231 return; 232 } 233 } 234 235 Diag(Decl->getLocation(), diag::note_availability_specified_here) 236 << Decl << true; 237 } 238 239 /// \brief Determine whether a FunctionDecl was ever declared with an 240 /// explicit storage class. 241 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 242 for (auto I : D->redecls()) { 243 if (I->getStorageClass() != SC_None) 244 return true; 245 } 246 return false; 247 } 248 249 /// \brief Check whether we're in an extern inline function and referring to a 250 /// variable or function with internal linkage (C11 6.7.4p3). 251 /// 252 /// This is only a warning because we used to silently accept this code, but 253 /// in many cases it will not behave correctly. This is not enabled in C++ mode 254 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 255 /// and so while there may still be user mistakes, most of the time we can't 256 /// prove that there are errors. 257 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 258 const NamedDecl *D, 259 SourceLocation Loc) { 260 // This is disabled under C++; there are too many ways for this to fire in 261 // contexts where the warning is a false positive, or where it is technically 262 // correct but benign. 263 if (S.getLangOpts().CPlusPlus) 264 return; 265 266 // Check if this is an inlined function or method. 267 FunctionDecl *Current = S.getCurFunctionDecl(); 268 if (!Current) 269 return; 270 if (!Current->isInlined()) 271 return; 272 if (!Current->isExternallyVisible()) 273 return; 274 275 // Check if the decl has internal linkage. 276 if (D->getFormalLinkage() != InternalLinkage) 277 return; 278 279 // Downgrade from ExtWarn to Extension if 280 // (1) the supposedly external inline function is in the main file, 281 // and probably won't be included anywhere else. 282 // (2) the thing we're referencing is a pure function. 283 // (3) the thing we're referencing is another inline function. 284 // This last can give us false negatives, but it's better than warning on 285 // wrappers for simple C library functions. 286 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 287 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 288 if (!DowngradeWarning && UsedFn) 289 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 290 291 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 292 : diag::ext_internal_in_extern_inline) 293 << /*IsVar=*/!UsedFn << D; 294 295 S.MaybeSuggestAddingStaticToDecl(Current); 296 297 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 298 << D; 299 } 300 301 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 302 const FunctionDecl *First = Cur->getFirstDecl(); 303 304 // Suggest "static" on the function, if possible. 305 if (!hasAnyExplicitStorageClass(First)) { 306 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 307 Diag(DeclBegin, diag::note_convert_inline_to_static) 308 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 309 } 310 } 311 312 /// \brief Determine whether the use of this declaration is valid, and 313 /// emit any corresponding diagnostics. 314 /// 315 /// This routine diagnoses various problems with referencing 316 /// declarations that can occur when using a declaration. For example, 317 /// it might warn if a deprecated or unavailable declaration is being 318 /// used, or produce an error (and return true) if a C++0x deleted 319 /// function is being used. 320 /// 321 /// \returns true if there was an error (this declaration cannot be 322 /// referenced), false otherwise. 323 /// 324 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 325 const ObjCInterfaceDecl *UnknownObjCClass, 326 bool ObjCPropertyAccess) { 327 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 328 // If there were any diagnostics suppressed by template argument deduction, 329 // emit them now. 330 SuppressedDiagnosticsMap::iterator 331 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 332 if (Pos != SuppressedDiagnostics.end()) { 333 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 334 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 335 Diag(Suppressed[I].first, Suppressed[I].second); 336 337 // Clear out the list of suppressed diagnostics, so that we don't emit 338 // them again for this specialization. However, we don't obsolete this 339 // entry from the table, because we want to avoid ever emitting these 340 // diagnostics again. 341 Suppressed.clear(); 342 } 343 344 // C++ [basic.start.main]p3: 345 // The function 'main' shall not be used within a program. 346 if (cast<FunctionDecl>(D)->isMain()) 347 Diag(Loc, diag::ext_main_used); 348 } 349 350 // See if this is an auto-typed variable whose initializer we are parsing. 351 if (ParsingInitForAutoVars.count(D)) { 352 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 353 354 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 355 << D->getDeclName() << (unsigned)AT->getKeyword(); 356 return true; 357 } 358 359 // See if this is a deleted function. 360 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 361 if (FD->isDeleted()) { 362 Diag(Loc, diag::err_deleted_function_use); 363 NoteDeletedFunction(FD); 364 return true; 365 } 366 367 // If the function has a deduced return type, and we can't deduce it, 368 // then we can't use it either. 369 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 370 DeduceReturnType(FD, Loc)) 371 return true; 372 } 373 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 374 ObjCPropertyAccess); 375 376 DiagnoseUnusedOfDecl(*this, D, Loc); 377 378 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 379 380 return false; 381 } 382 383 /// \brief Retrieve the message suffix that should be added to a 384 /// diagnostic complaining about the given function being deleted or 385 /// unavailable. 386 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 387 std::string Message; 388 if (FD->getAvailability(&Message)) 389 return ": " + Message; 390 391 return std::string(); 392 } 393 394 /// DiagnoseSentinelCalls - This routine checks whether a call or 395 /// message-send is to a declaration with the sentinel attribute, and 396 /// if so, it checks that the requirements of the sentinel are 397 /// satisfied. 398 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 399 ArrayRef<Expr *> Args) { 400 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 401 if (!attr) 402 return; 403 404 // The number of formal parameters of the declaration. 405 unsigned numFormalParams; 406 407 // The kind of declaration. This is also an index into a %select in 408 // the diagnostic. 409 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 410 411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 412 numFormalParams = MD->param_size(); 413 calleeType = CT_Method; 414 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 415 numFormalParams = FD->param_size(); 416 calleeType = CT_Function; 417 } else if (isa<VarDecl>(D)) { 418 QualType type = cast<ValueDecl>(D)->getType(); 419 const FunctionType *fn = nullptr; 420 if (const PointerType *ptr = type->getAs<PointerType>()) { 421 fn = ptr->getPointeeType()->getAs<FunctionType>(); 422 if (!fn) return; 423 calleeType = CT_Function; 424 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 425 fn = ptr->getPointeeType()->castAs<FunctionType>(); 426 calleeType = CT_Block; 427 } else { 428 return; 429 } 430 431 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 432 numFormalParams = proto->getNumParams(); 433 } else { 434 numFormalParams = 0; 435 } 436 } else { 437 return; 438 } 439 440 // "nullPos" is the number of formal parameters at the end which 441 // effectively count as part of the variadic arguments. This is 442 // useful if you would prefer to not have *any* formal parameters, 443 // but the language forces you to have at least one. 444 unsigned nullPos = attr->getNullPos(); 445 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 446 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 447 448 // The number of arguments which should follow the sentinel. 449 unsigned numArgsAfterSentinel = attr->getSentinel(); 450 451 // If there aren't enough arguments for all the formal parameters, 452 // the sentinel, and the args after the sentinel, complain. 453 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 454 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 455 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 456 return; 457 } 458 459 // Otherwise, find the sentinel expression. 460 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 461 if (!sentinelExpr) return; 462 if (sentinelExpr->isValueDependent()) return; 463 if (Context.isSentinelNullExpr(sentinelExpr)) return; 464 465 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 466 // or 'NULL' if those are actually defined in the context. Only use 467 // 'nil' for ObjC methods, where it's much more likely that the 468 // variadic arguments form a list of object pointers. 469 SourceLocation MissingNilLoc 470 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 471 std::string NullValue; 472 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 473 NullValue = "nil"; 474 else if (getLangOpts().CPlusPlus11) 475 NullValue = "nullptr"; 476 else if (PP.isMacroDefined("NULL")) 477 NullValue = "NULL"; 478 else 479 NullValue = "(void*) 0"; 480 481 if (MissingNilLoc.isInvalid()) 482 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 483 else 484 Diag(MissingNilLoc, diag::warn_missing_sentinel) 485 << int(calleeType) 486 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 487 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 488 } 489 490 SourceRange Sema::getExprRange(Expr *E) const { 491 return E ? E->getSourceRange() : SourceRange(); 492 } 493 494 //===----------------------------------------------------------------------===// 495 // Standard Promotions and Conversions 496 //===----------------------------------------------------------------------===// 497 498 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 499 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 500 // Handle any placeholder expressions which made it here. 501 if (E->getType()->isPlaceholderType()) { 502 ExprResult result = CheckPlaceholderExpr(E); 503 if (result.isInvalid()) return ExprError(); 504 E = result.get(); 505 } 506 507 QualType Ty = E->getType(); 508 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 509 510 if (Ty->isFunctionType()) { 511 // If we are here, we are not calling a function but taking 512 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 513 if (getLangOpts().OpenCL) { 514 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 515 return ExprError(); 516 } 517 E = ImpCastExprToType(E, Context.getPointerType(Ty), 518 CK_FunctionToPointerDecay).get(); 519 } else if (Ty->isArrayType()) { 520 // In C90 mode, arrays only promote to pointers if the array expression is 521 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 522 // type 'array of type' is converted to an expression that has type 'pointer 523 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 524 // that has type 'array of type' ...". The relevant change is "an lvalue" 525 // (C90) to "an expression" (C99). 526 // 527 // C++ 4.2p1: 528 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 529 // T" can be converted to an rvalue of type "pointer to T". 530 // 531 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 532 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 533 CK_ArrayToPointerDecay).get(); 534 } 535 return E; 536 } 537 538 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 539 // Check to see if we are dereferencing a null pointer. If so, 540 // and if not volatile-qualified, this is undefined behavior that the 541 // optimizer will delete, so warn about it. People sometimes try to use this 542 // to get a deterministic trap and are surprised by clang's behavior. This 543 // only handles the pattern "*null", which is a very syntactic check. 544 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 545 if (UO->getOpcode() == UO_Deref && 546 UO->getSubExpr()->IgnoreParenCasts()-> 547 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 548 !UO->getType().isVolatileQualified()) { 549 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 550 S.PDiag(diag::warn_indirection_through_null) 551 << UO->getSubExpr()->getSourceRange()); 552 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 553 S.PDiag(diag::note_indirection_through_null)); 554 } 555 } 556 557 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 558 SourceLocation AssignLoc, 559 const Expr* RHS) { 560 const ObjCIvarDecl *IV = OIRE->getDecl(); 561 if (!IV) 562 return; 563 564 DeclarationName MemberName = IV->getDeclName(); 565 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 566 if (!Member || !Member->isStr("isa")) 567 return; 568 569 const Expr *Base = OIRE->getBase(); 570 QualType BaseType = Base->getType(); 571 if (OIRE->isArrow()) 572 BaseType = BaseType->getPointeeType(); 573 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 574 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 575 ObjCInterfaceDecl *ClassDeclared = nullptr; 576 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 577 if (!ClassDeclared->getSuperClass() 578 && (*ClassDeclared->ivar_begin()) == IV) { 579 if (RHS) { 580 NamedDecl *ObjectSetClass = 581 S.LookupSingleName(S.TUScope, 582 &S.Context.Idents.get("object_setClass"), 583 SourceLocation(), S.LookupOrdinaryName); 584 if (ObjectSetClass) { 585 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 586 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 587 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 588 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 589 AssignLoc), ",") << 590 FixItHint::CreateInsertion(RHSLocEnd, ")"); 591 } 592 else 593 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 594 } else { 595 NamedDecl *ObjectGetClass = 596 S.LookupSingleName(S.TUScope, 597 &S.Context.Idents.get("object_getClass"), 598 SourceLocation(), S.LookupOrdinaryName); 599 if (ObjectGetClass) 600 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 601 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 602 FixItHint::CreateReplacement( 603 SourceRange(OIRE->getOpLoc(), 604 OIRE->getLocEnd()), ")"); 605 else 606 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 607 } 608 S.Diag(IV->getLocation(), diag::note_ivar_decl); 609 } 610 } 611 } 612 613 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 614 // Handle any placeholder expressions which made it here. 615 if (E->getType()->isPlaceholderType()) { 616 ExprResult result = CheckPlaceholderExpr(E); 617 if (result.isInvalid()) return ExprError(); 618 E = result.get(); 619 } 620 621 // C++ [conv.lval]p1: 622 // A glvalue of a non-function, non-array type T can be 623 // converted to a prvalue. 624 if (!E->isGLValue()) return E; 625 626 QualType T = E->getType(); 627 assert(!T.isNull() && "r-value conversion on typeless expression?"); 628 629 // We don't want to throw lvalue-to-rvalue casts on top of 630 // expressions of certain types in C++. 631 if (getLangOpts().CPlusPlus && 632 (E->getType() == Context.OverloadTy || 633 T->isDependentType() || 634 T->isRecordType())) 635 return E; 636 637 // The C standard is actually really unclear on this point, and 638 // DR106 tells us what the result should be but not why. It's 639 // generally best to say that void types just doesn't undergo 640 // lvalue-to-rvalue at all. Note that expressions of unqualified 641 // 'void' type are never l-values, but qualified void can be. 642 if (T->isVoidType()) 643 return E; 644 645 // OpenCL usually rejects direct accesses to values of 'half' type. 646 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 647 T->isHalfType()) { 648 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 649 << 0 << T; 650 return ExprError(); 651 } 652 653 CheckForNullPointerDereference(*this, E); 654 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 655 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 656 &Context.Idents.get("object_getClass"), 657 SourceLocation(), LookupOrdinaryName); 658 if (ObjectGetClass) 659 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 660 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 661 FixItHint::CreateReplacement( 662 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 663 else 664 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 665 } 666 else if (const ObjCIvarRefExpr *OIRE = 667 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 668 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 669 670 // C++ [conv.lval]p1: 671 // [...] If T is a non-class type, the type of the prvalue is the 672 // cv-unqualified version of T. Otherwise, the type of the 673 // rvalue is T. 674 // 675 // C99 6.3.2.1p2: 676 // If the lvalue has qualified type, the value has the unqualified 677 // version of the type of the lvalue; otherwise, the value has the 678 // type of the lvalue. 679 if (T.hasQualifiers()) 680 T = T.getUnqualifiedType(); 681 682 if (T->isMemberPointerType() && 683 Context.getTargetInfo().getCXXABI().isMicrosoft()) 684 RequireCompleteType(E->getExprLoc(), T, 0); 685 686 UpdateMarkingForLValueToRValue(E); 687 688 // Loading a __weak object implicitly retains the value, so we need a cleanup to 689 // balance that. 690 if (getLangOpts().ObjCAutoRefCount && 691 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 692 ExprNeedsCleanups = true; 693 694 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 695 nullptr, VK_RValue); 696 697 // C11 6.3.2.1p2: 698 // ... if the lvalue has atomic type, the value has the non-atomic version 699 // of the type of the lvalue ... 700 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 701 T = Atomic->getValueType().getUnqualifiedType(); 702 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 703 nullptr, VK_RValue); 704 } 705 706 return Res; 707 } 708 709 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 710 ExprResult Res = DefaultFunctionArrayConversion(E); 711 if (Res.isInvalid()) 712 return ExprError(); 713 Res = DefaultLvalueConversion(Res.get()); 714 if (Res.isInvalid()) 715 return ExprError(); 716 return Res; 717 } 718 719 /// CallExprUnaryConversions - a special case of an unary conversion 720 /// performed on a function designator of a call expression. 721 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 722 QualType Ty = E->getType(); 723 ExprResult Res = E; 724 // Only do implicit cast for a function type, but not for a pointer 725 // to function type. 726 if (Ty->isFunctionType()) { 727 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 728 CK_FunctionToPointerDecay).get(); 729 if (Res.isInvalid()) 730 return ExprError(); 731 } 732 Res = DefaultLvalueConversion(Res.get()); 733 if (Res.isInvalid()) 734 return ExprError(); 735 return Res.get(); 736 } 737 738 /// UsualUnaryConversions - Performs various conversions that are common to most 739 /// operators (C99 6.3). The conversions of array and function types are 740 /// sometimes suppressed. For example, the array->pointer conversion doesn't 741 /// apply if the array is an argument to the sizeof or address (&) operators. 742 /// In these instances, this routine should *not* be called. 743 ExprResult Sema::UsualUnaryConversions(Expr *E) { 744 // First, convert to an r-value. 745 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 746 if (Res.isInvalid()) 747 return ExprError(); 748 E = Res.get(); 749 750 QualType Ty = E->getType(); 751 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 752 753 // Half FP have to be promoted to float unless it is natively supported 754 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 755 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 756 757 // Try to perform integral promotions if the object has a theoretically 758 // promotable type. 759 if (Ty->isIntegralOrUnscopedEnumerationType()) { 760 // C99 6.3.1.1p2: 761 // 762 // The following may be used in an expression wherever an int or 763 // unsigned int may be used: 764 // - an object or expression with an integer type whose integer 765 // conversion rank is less than or equal to the rank of int 766 // and unsigned int. 767 // - A bit-field of type _Bool, int, signed int, or unsigned int. 768 // 769 // If an int can represent all values of the original type, the 770 // value is converted to an int; otherwise, it is converted to an 771 // unsigned int. These are called the integer promotions. All 772 // other types are unchanged by the integer promotions. 773 774 QualType PTy = Context.isPromotableBitField(E); 775 if (!PTy.isNull()) { 776 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 777 return E; 778 } 779 if (Ty->isPromotableIntegerType()) { 780 QualType PT = Context.getPromotedIntegerType(Ty); 781 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 782 return E; 783 } 784 } 785 return E; 786 } 787 788 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 789 /// do not have a prototype. Arguments that have type float or __fp16 790 /// are promoted to double. All other argument types are converted by 791 /// UsualUnaryConversions(). 792 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 793 QualType Ty = E->getType(); 794 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 795 796 ExprResult Res = UsualUnaryConversions(E); 797 if (Res.isInvalid()) 798 return ExprError(); 799 E = Res.get(); 800 801 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 802 // double. 803 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 804 if (BTy && (BTy->getKind() == BuiltinType::Half || 805 BTy->getKind() == BuiltinType::Float)) 806 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 807 808 // C++ performs lvalue-to-rvalue conversion as a default argument 809 // promotion, even on class types, but note: 810 // C++11 [conv.lval]p2: 811 // When an lvalue-to-rvalue conversion occurs in an unevaluated 812 // operand or a subexpression thereof the value contained in the 813 // referenced object is not accessed. Otherwise, if the glvalue 814 // has a class type, the conversion copy-initializes a temporary 815 // of type T from the glvalue and the result of the conversion 816 // is a prvalue for the temporary. 817 // FIXME: add some way to gate this entire thing for correctness in 818 // potentially potentially evaluated contexts. 819 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 820 ExprResult Temp = PerformCopyInitialization( 821 InitializedEntity::InitializeTemporary(E->getType()), 822 E->getExprLoc(), E); 823 if (Temp.isInvalid()) 824 return ExprError(); 825 E = Temp.get(); 826 } 827 828 return E; 829 } 830 831 /// Determine the degree of POD-ness for an expression. 832 /// Incomplete types are considered POD, since this check can be performed 833 /// when we're in an unevaluated context. 834 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 835 if (Ty->isIncompleteType()) { 836 // C++11 [expr.call]p7: 837 // After these conversions, if the argument does not have arithmetic, 838 // enumeration, pointer, pointer to member, or class type, the program 839 // is ill-formed. 840 // 841 // Since we've already performed array-to-pointer and function-to-pointer 842 // decay, the only such type in C++ is cv void. This also handles 843 // initializer lists as variadic arguments. 844 if (Ty->isVoidType()) 845 return VAK_Invalid; 846 847 if (Ty->isObjCObjectType()) 848 return VAK_Invalid; 849 return VAK_Valid; 850 } 851 852 if (Ty.isCXX98PODType(Context)) 853 return VAK_Valid; 854 855 // C++11 [expr.call]p7: 856 // Passing a potentially-evaluated argument of class type (Clause 9) 857 // having a non-trivial copy constructor, a non-trivial move constructor, 858 // or a non-trivial destructor, with no corresponding parameter, 859 // is conditionally-supported with implementation-defined semantics. 860 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 861 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 862 if (!Record->hasNonTrivialCopyConstructor() && 863 !Record->hasNonTrivialMoveConstructor() && 864 !Record->hasNonTrivialDestructor()) 865 return VAK_ValidInCXX11; 866 867 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 868 return VAK_Valid; 869 870 if (Ty->isObjCObjectType()) 871 return VAK_Invalid; 872 873 if (getLangOpts().MSVCCompat) 874 return VAK_MSVCUndefined; 875 876 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 877 // permitted to reject them. We should consider doing so. 878 return VAK_Undefined; 879 } 880 881 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 882 // Don't allow one to pass an Objective-C interface to a vararg. 883 const QualType &Ty = E->getType(); 884 VarArgKind VAK = isValidVarArgType(Ty); 885 886 // Complain about passing non-POD types through varargs. 887 switch (VAK) { 888 case VAK_ValidInCXX11: 889 DiagRuntimeBehavior( 890 E->getLocStart(), nullptr, 891 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 892 << Ty << CT); 893 // Fall through. 894 case VAK_Valid: 895 if (Ty->isRecordType()) { 896 // This is unlikely to be what the user intended. If the class has a 897 // 'c_str' member function, the user probably meant to call that. 898 DiagRuntimeBehavior(E->getLocStart(), nullptr, 899 PDiag(diag::warn_pass_class_arg_to_vararg) 900 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 901 } 902 break; 903 904 case VAK_Undefined: 905 case VAK_MSVCUndefined: 906 DiagRuntimeBehavior( 907 E->getLocStart(), nullptr, 908 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 909 << getLangOpts().CPlusPlus11 << Ty << CT); 910 break; 911 912 case VAK_Invalid: 913 if (Ty->isObjCObjectType()) 914 DiagRuntimeBehavior( 915 E->getLocStart(), nullptr, 916 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 917 << Ty << CT); 918 else 919 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 920 << isa<InitListExpr>(E) << Ty << CT; 921 break; 922 } 923 } 924 925 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 926 /// will create a trap if the resulting type is not a POD type. 927 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 928 FunctionDecl *FDecl) { 929 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 930 // Strip the unbridged-cast placeholder expression off, if applicable. 931 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 932 (CT == VariadicMethod || 933 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 934 E = stripARCUnbridgedCast(E); 935 936 // Otherwise, do normal placeholder checking. 937 } else { 938 ExprResult ExprRes = CheckPlaceholderExpr(E); 939 if (ExprRes.isInvalid()) 940 return ExprError(); 941 E = ExprRes.get(); 942 } 943 } 944 945 ExprResult ExprRes = DefaultArgumentPromotion(E); 946 if (ExprRes.isInvalid()) 947 return ExprError(); 948 E = ExprRes.get(); 949 950 // Diagnostics regarding non-POD argument types are 951 // emitted along with format string checking in Sema::CheckFunctionCall(). 952 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 953 // Turn this into a trap. 954 CXXScopeSpec SS; 955 SourceLocation TemplateKWLoc; 956 UnqualifiedId Name; 957 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 958 E->getLocStart()); 959 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 960 Name, true, false); 961 if (TrapFn.isInvalid()) 962 return ExprError(); 963 964 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 965 E->getLocStart(), None, 966 E->getLocEnd()); 967 if (Call.isInvalid()) 968 return ExprError(); 969 970 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 971 Call.get(), E); 972 if (Comma.isInvalid()) 973 return ExprError(); 974 return Comma.get(); 975 } 976 977 if (!getLangOpts().CPlusPlus && 978 RequireCompleteType(E->getExprLoc(), E->getType(), 979 diag::err_call_incomplete_argument)) 980 return ExprError(); 981 982 return E; 983 } 984 985 /// \brief Converts an integer to complex float type. Helper function of 986 /// UsualArithmeticConversions() 987 /// 988 /// \return false if the integer expression is an integer type and is 989 /// successfully converted to the complex type. 990 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 991 ExprResult &ComplexExpr, 992 QualType IntTy, 993 QualType ComplexTy, 994 bool SkipCast) { 995 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 996 if (SkipCast) return false; 997 if (IntTy->isIntegerType()) { 998 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 999 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1000 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1001 CK_FloatingRealToComplex); 1002 } else { 1003 assert(IntTy->isComplexIntegerType()); 1004 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1005 CK_IntegralComplexToFloatingComplex); 1006 } 1007 return false; 1008 } 1009 1010 /// \brief Handle arithmetic conversion with complex types. Helper function of 1011 /// UsualArithmeticConversions() 1012 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1013 ExprResult &RHS, QualType LHSType, 1014 QualType RHSType, 1015 bool IsCompAssign) { 1016 // if we have an integer operand, the result is the complex type. 1017 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1018 /*skipCast*/false)) 1019 return LHSType; 1020 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1021 /*skipCast*/IsCompAssign)) 1022 return RHSType; 1023 1024 // This handles complex/complex, complex/float, or float/complex. 1025 // When both operands are complex, the shorter operand is converted to the 1026 // type of the longer, and that is the type of the result. This corresponds 1027 // to what is done when combining two real floating-point operands. 1028 // The fun begins when size promotion occur across type domains. 1029 // From H&S 6.3.4: When one operand is complex and the other is a real 1030 // floating-point type, the less precise type is converted, within it's 1031 // real or complex domain, to the precision of the other type. For example, 1032 // when combining a "long double" with a "double _Complex", the 1033 // "double _Complex" is promoted to "long double _Complex". 1034 1035 // Compute the rank of the two types, regardless of whether they are complex. 1036 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1037 1038 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1039 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1040 QualType LHSElementType = 1041 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1042 QualType RHSElementType = 1043 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1044 1045 QualType ResultType = S.Context.getComplexType(LHSElementType); 1046 if (Order < 0) { 1047 // Promote the precision of the LHS if not an assignment. 1048 ResultType = S.Context.getComplexType(RHSElementType); 1049 if (!IsCompAssign) { 1050 if (LHSComplexType) 1051 LHS = 1052 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1053 else 1054 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1055 } 1056 } else if (Order > 0) { 1057 // Promote the precision of the RHS. 1058 if (RHSComplexType) 1059 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1060 else 1061 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1062 } 1063 return ResultType; 1064 } 1065 1066 /// \brief Hande arithmetic conversion from integer to float. Helper function 1067 /// of UsualArithmeticConversions() 1068 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1069 ExprResult &IntExpr, 1070 QualType FloatTy, QualType IntTy, 1071 bool ConvertFloat, bool ConvertInt) { 1072 if (IntTy->isIntegerType()) { 1073 if (ConvertInt) 1074 // Convert intExpr to the lhs floating point type. 1075 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1076 CK_IntegralToFloating); 1077 return FloatTy; 1078 } 1079 1080 // Convert both sides to the appropriate complex float. 1081 assert(IntTy->isComplexIntegerType()); 1082 QualType result = S.Context.getComplexType(FloatTy); 1083 1084 // _Complex int -> _Complex float 1085 if (ConvertInt) 1086 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1087 CK_IntegralComplexToFloatingComplex); 1088 1089 // float -> _Complex float 1090 if (ConvertFloat) 1091 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1092 CK_FloatingRealToComplex); 1093 1094 return result; 1095 } 1096 1097 /// \brief Handle arithmethic conversion with floating point types. Helper 1098 /// function of UsualArithmeticConversions() 1099 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1100 ExprResult &RHS, QualType LHSType, 1101 QualType RHSType, bool IsCompAssign) { 1102 bool LHSFloat = LHSType->isRealFloatingType(); 1103 bool RHSFloat = RHSType->isRealFloatingType(); 1104 1105 // If we have two real floating types, convert the smaller operand 1106 // to the bigger result. 1107 if (LHSFloat && RHSFloat) { 1108 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1109 if (order > 0) { 1110 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1111 return LHSType; 1112 } 1113 1114 assert(order < 0 && "illegal float comparison"); 1115 if (!IsCompAssign) 1116 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1117 return RHSType; 1118 } 1119 1120 if (LHSFloat) { 1121 // Half FP has to be promoted to float unless it is natively supported 1122 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1123 LHSType = S.Context.FloatTy; 1124 1125 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1126 /*convertFloat=*/!IsCompAssign, 1127 /*convertInt=*/ true); 1128 } 1129 assert(RHSFloat); 1130 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1131 /*convertInt=*/ true, 1132 /*convertFloat=*/!IsCompAssign); 1133 } 1134 1135 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1136 1137 namespace { 1138 /// These helper callbacks are placed in an anonymous namespace to 1139 /// permit their use as function template parameters. 1140 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1141 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1142 } 1143 1144 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1145 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1146 CK_IntegralComplexCast); 1147 } 1148 } 1149 1150 /// \brief Handle integer arithmetic conversions. Helper function of 1151 /// UsualArithmeticConversions() 1152 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1153 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1154 ExprResult &RHS, QualType LHSType, 1155 QualType RHSType, bool IsCompAssign) { 1156 // The rules for this case are in C99 6.3.1.8 1157 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1158 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1159 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1160 if (LHSSigned == RHSSigned) { 1161 // Same signedness; use the higher-ranked type 1162 if (order >= 0) { 1163 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1164 return LHSType; 1165 } else if (!IsCompAssign) 1166 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1167 return RHSType; 1168 } else if (order != (LHSSigned ? 1 : -1)) { 1169 // The unsigned type has greater than or equal rank to the 1170 // signed type, so use the unsigned type 1171 if (RHSSigned) { 1172 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1173 return LHSType; 1174 } else if (!IsCompAssign) 1175 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1176 return RHSType; 1177 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1178 // The two types are different widths; if we are here, that 1179 // means the signed type is larger than the unsigned type, so 1180 // use the signed type. 1181 if (LHSSigned) { 1182 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1183 return LHSType; 1184 } else if (!IsCompAssign) 1185 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1186 return RHSType; 1187 } else { 1188 // The signed type is higher-ranked than the unsigned type, 1189 // but isn't actually any bigger (like unsigned int and long 1190 // on most 32-bit systems). Use the unsigned type corresponding 1191 // to the signed type. 1192 QualType result = 1193 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1194 RHS = (*doRHSCast)(S, RHS.get(), result); 1195 if (!IsCompAssign) 1196 LHS = (*doLHSCast)(S, LHS.get(), result); 1197 return result; 1198 } 1199 } 1200 1201 /// \brief Handle conversions with GCC complex int extension. Helper function 1202 /// of UsualArithmeticConversions() 1203 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1204 ExprResult &RHS, QualType LHSType, 1205 QualType RHSType, 1206 bool IsCompAssign) { 1207 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1208 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1209 1210 if (LHSComplexInt && RHSComplexInt) { 1211 QualType LHSEltType = LHSComplexInt->getElementType(); 1212 QualType RHSEltType = RHSComplexInt->getElementType(); 1213 QualType ScalarType = 1214 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1215 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1216 1217 return S.Context.getComplexType(ScalarType); 1218 } 1219 1220 if (LHSComplexInt) { 1221 QualType LHSEltType = LHSComplexInt->getElementType(); 1222 QualType ScalarType = 1223 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1224 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1225 QualType ComplexType = S.Context.getComplexType(ScalarType); 1226 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1227 CK_IntegralRealToComplex); 1228 1229 return ComplexType; 1230 } 1231 1232 assert(RHSComplexInt); 1233 1234 QualType RHSEltType = RHSComplexInt->getElementType(); 1235 QualType ScalarType = 1236 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1237 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1238 QualType ComplexType = S.Context.getComplexType(ScalarType); 1239 1240 if (!IsCompAssign) 1241 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1242 CK_IntegralRealToComplex); 1243 return ComplexType; 1244 } 1245 1246 /// UsualArithmeticConversions - Performs various conversions that are common to 1247 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1248 /// routine returns the first non-arithmetic type found. The client is 1249 /// responsible for emitting appropriate error diagnostics. 1250 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1251 bool IsCompAssign) { 1252 if (!IsCompAssign) { 1253 LHS = UsualUnaryConversions(LHS.get()); 1254 if (LHS.isInvalid()) 1255 return QualType(); 1256 } 1257 1258 RHS = UsualUnaryConversions(RHS.get()); 1259 if (RHS.isInvalid()) 1260 return QualType(); 1261 1262 // For conversion purposes, we ignore any qualifiers. 1263 // For example, "const float" and "float" are equivalent. 1264 QualType LHSType = 1265 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1266 QualType RHSType = 1267 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1268 1269 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1270 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1271 LHSType = AtomicLHS->getValueType(); 1272 1273 // If both types are identical, no conversion is needed. 1274 if (LHSType == RHSType) 1275 return LHSType; 1276 1277 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1278 // The caller can deal with this (e.g. pointer + int). 1279 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1280 return QualType(); 1281 1282 // Apply unary and bitfield promotions to the LHS's type. 1283 QualType LHSUnpromotedType = LHSType; 1284 if (LHSType->isPromotableIntegerType()) 1285 LHSType = Context.getPromotedIntegerType(LHSType); 1286 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1287 if (!LHSBitfieldPromoteTy.isNull()) 1288 LHSType = LHSBitfieldPromoteTy; 1289 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1290 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1291 1292 // If both types are identical, no conversion is needed. 1293 if (LHSType == RHSType) 1294 return LHSType; 1295 1296 // At this point, we have two different arithmetic types. 1297 1298 // Handle complex types first (C99 6.3.1.8p1). 1299 if (LHSType->isComplexType() || RHSType->isComplexType()) 1300 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1301 IsCompAssign); 1302 1303 // Now handle "real" floating types (i.e. float, double, long double). 1304 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1305 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1306 IsCompAssign); 1307 1308 // Handle GCC complex int extension. 1309 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1310 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1311 IsCompAssign); 1312 1313 // Finally, we have two differing integer types. 1314 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1315 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1316 } 1317 1318 1319 //===----------------------------------------------------------------------===// 1320 // Semantic Analysis for various Expression Types 1321 //===----------------------------------------------------------------------===// 1322 1323 1324 ExprResult 1325 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1326 SourceLocation DefaultLoc, 1327 SourceLocation RParenLoc, 1328 Expr *ControllingExpr, 1329 ArrayRef<ParsedType> ArgTypes, 1330 ArrayRef<Expr *> ArgExprs) { 1331 unsigned NumAssocs = ArgTypes.size(); 1332 assert(NumAssocs == ArgExprs.size()); 1333 1334 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1335 for (unsigned i = 0; i < NumAssocs; ++i) { 1336 if (ArgTypes[i]) 1337 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1338 else 1339 Types[i] = nullptr; 1340 } 1341 1342 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1343 ControllingExpr, 1344 llvm::makeArrayRef(Types, NumAssocs), 1345 ArgExprs); 1346 delete [] Types; 1347 return ER; 1348 } 1349 1350 ExprResult 1351 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1352 SourceLocation DefaultLoc, 1353 SourceLocation RParenLoc, 1354 Expr *ControllingExpr, 1355 ArrayRef<TypeSourceInfo *> Types, 1356 ArrayRef<Expr *> Exprs) { 1357 unsigned NumAssocs = Types.size(); 1358 assert(NumAssocs == Exprs.size()); 1359 1360 // Decay and strip qualifiers for the controlling expression type, and handle 1361 // placeholder type replacement. See committee discussion from WG14 DR423. 1362 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1363 if (R.isInvalid()) 1364 return ExprError(); 1365 ControllingExpr = R.get(); 1366 1367 // The controlling expression is an unevaluated operand, so side effects are 1368 // likely unintended. 1369 if (ActiveTemplateInstantiations.empty() && 1370 ControllingExpr->HasSideEffects(Context, false)) 1371 Diag(ControllingExpr->getExprLoc(), 1372 diag::warn_side_effects_unevaluated_context); 1373 1374 bool TypeErrorFound = false, 1375 IsResultDependent = ControllingExpr->isTypeDependent(), 1376 ContainsUnexpandedParameterPack 1377 = ControllingExpr->containsUnexpandedParameterPack(); 1378 1379 for (unsigned i = 0; i < NumAssocs; ++i) { 1380 if (Exprs[i]->containsUnexpandedParameterPack()) 1381 ContainsUnexpandedParameterPack = true; 1382 1383 if (Types[i]) { 1384 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1385 ContainsUnexpandedParameterPack = true; 1386 1387 if (Types[i]->getType()->isDependentType()) { 1388 IsResultDependent = true; 1389 } else { 1390 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1391 // complete object type other than a variably modified type." 1392 unsigned D = 0; 1393 if (Types[i]->getType()->isIncompleteType()) 1394 D = diag::err_assoc_type_incomplete; 1395 else if (!Types[i]->getType()->isObjectType()) 1396 D = diag::err_assoc_type_nonobject; 1397 else if (Types[i]->getType()->isVariablyModifiedType()) 1398 D = diag::err_assoc_type_variably_modified; 1399 1400 if (D != 0) { 1401 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1402 << Types[i]->getTypeLoc().getSourceRange() 1403 << Types[i]->getType(); 1404 TypeErrorFound = true; 1405 } 1406 1407 // C11 6.5.1.1p2 "No two generic associations in the same generic 1408 // selection shall specify compatible types." 1409 for (unsigned j = i+1; j < NumAssocs; ++j) 1410 if (Types[j] && !Types[j]->getType()->isDependentType() && 1411 Context.typesAreCompatible(Types[i]->getType(), 1412 Types[j]->getType())) { 1413 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1414 diag::err_assoc_compatible_types) 1415 << Types[j]->getTypeLoc().getSourceRange() 1416 << Types[j]->getType() 1417 << Types[i]->getType(); 1418 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1419 diag::note_compat_assoc) 1420 << Types[i]->getTypeLoc().getSourceRange() 1421 << Types[i]->getType(); 1422 TypeErrorFound = true; 1423 } 1424 } 1425 } 1426 } 1427 if (TypeErrorFound) 1428 return ExprError(); 1429 1430 // If we determined that the generic selection is result-dependent, don't 1431 // try to compute the result expression. 1432 if (IsResultDependent) 1433 return new (Context) GenericSelectionExpr( 1434 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1435 ContainsUnexpandedParameterPack); 1436 1437 SmallVector<unsigned, 1> CompatIndices; 1438 unsigned DefaultIndex = -1U; 1439 for (unsigned i = 0; i < NumAssocs; ++i) { 1440 if (!Types[i]) 1441 DefaultIndex = i; 1442 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1443 Types[i]->getType())) 1444 CompatIndices.push_back(i); 1445 } 1446 1447 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1448 // type compatible with at most one of the types named in its generic 1449 // association list." 1450 if (CompatIndices.size() > 1) { 1451 // We strip parens here because the controlling expression is typically 1452 // parenthesized in macro definitions. 1453 ControllingExpr = ControllingExpr->IgnoreParens(); 1454 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1455 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1456 << (unsigned) CompatIndices.size(); 1457 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1458 E = CompatIndices.end(); I != E; ++I) { 1459 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1460 diag::note_compat_assoc) 1461 << Types[*I]->getTypeLoc().getSourceRange() 1462 << Types[*I]->getType(); 1463 } 1464 return ExprError(); 1465 } 1466 1467 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1468 // its controlling expression shall have type compatible with exactly one of 1469 // the types named in its generic association list." 1470 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1471 // We strip parens here because the controlling expression is typically 1472 // parenthesized in macro definitions. 1473 ControllingExpr = ControllingExpr->IgnoreParens(); 1474 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1475 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1476 return ExprError(); 1477 } 1478 1479 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1480 // type name that is compatible with the type of the controlling expression, 1481 // then the result expression of the generic selection is the expression 1482 // in that generic association. Otherwise, the result expression of the 1483 // generic selection is the expression in the default generic association." 1484 unsigned ResultIndex = 1485 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1486 1487 return new (Context) GenericSelectionExpr( 1488 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1489 ContainsUnexpandedParameterPack, ResultIndex); 1490 } 1491 1492 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1493 /// location of the token and the offset of the ud-suffix within it. 1494 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1495 unsigned Offset) { 1496 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1497 S.getLangOpts()); 1498 } 1499 1500 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1501 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1502 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1503 IdentifierInfo *UDSuffix, 1504 SourceLocation UDSuffixLoc, 1505 ArrayRef<Expr*> Args, 1506 SourceLocation LitEndLoc) { 1507 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1508 1509 QualType ArgTy[2]; 1510 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1511 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1512 if (ArgTy[ArgIdx]->isArrayType()) 1513 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1514 } 1515 1516 DeclarationName OpName = 1517 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1518 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1519 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1520 1521 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1522 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1523 /*AllowRaw*/false, /*AllowTemplate*/false, 1524 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1525 return ExprError(); 1526 1527 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1528 } 1529 1530 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1531 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1532 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1533 /// multiple tokens. However, the common case is that StringToks points to one 1534 /// string. 1535 /// 1536 ExprResult 1537 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1538 assert(!StringToks.empty() && "Must have at least one string!"); 1539 1540 StringLiteralParser Literal(StringToks, PP); 1541 if (Literal.hadError) 1542 return ExprError(); 1543 1544 SmallVector<SourceLocation, 4> StringTokLocs; 1545 for (unsigned i = 0; i != StringToks.size(); ++i) 1546 StringTokLocs.push_back(StringToks[i].getLocation()); 1547 1548 QualType CharTy = Context.CharTy; 1549 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1550 if (Literal.isWide()) { 1551 CharTy = Context.getWideCharType(); 1552 Kind = StringLiteral::Wide; 1553 } else if (Literal.isUTF8()) { 1554 Kind = StringLiteral::UTF8; 1555 } else if (Literal.isUTF16()) { 1556 CharTy = Context.Char16Ty; 1557 Kind = StringLiteral::UTF16; 1558 } else if (Literal.isUTF32()) { 1559 CharTy = Context.Char32Ty; 1560 Kind = StringLiteral::UTF32; 1561 } else if (Literal.isPascal()) { 1562 CharTy = Context.UnsignedCharTy; 1563 } 1564 1565 QualType CharTyConst = CharTy; 1566 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1567 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1568 CharTyConst.addConst(); 1569 1570 // Get an array type for the string, according to C99 6.4.5. This includes 1571 // the nul terminator character as well as the string length for pascal 1572 // strings. 1573 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1574 llvm::APInt(32, Literal.GetNumStringChars()+1), 1575 ArrayType::Normal, 0); 1576 1577 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1578 if (getLangOpts().OpenCL) { 1579 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1580 } 1581 1582 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1583 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1584 Kind, Literal.Pascal, StrTy, 1585 &StringTokLocs[0], 1586 StringTokLocs.size()); 1587 if (Literal.getUDSuffix().empty()) 1588 return Lit; 1589 1590 // We're building a user-defined literal. 1591 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1592 SourceLocation UDSuffixLoc = 1593 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1594 Literal.getUDSuffixOffset()); 1595 1596 // Make sure we're allowed user-defined literals here. 1597 if (!UDLScope) 1598 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1599 1600 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1601 // operator "" X (str, len) 1602 QualType SizeType = Context.getSizeType(); 1603 1604 DeclarationName OpName = 1605 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1606 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1607 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1608 1609 QualType ArgTy[] = { 1610 Context.getArrayDecayedType(StrTy), SizeType 1611 }; 1612 1613 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1614 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1615 /*AllowRaw*/false, /*AllowTemplate*/false, 1616 /*AllowStringTemplate*/true)) { 1617 1618 case LOLR_Cooked: { 1619 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1620 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1621 StringTokLocs[0]); 1622 Expr *Args[] = { Lit, LenArg }; 1623 1624 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1625 } 1626 1627 case LOLR_StringTemplate: { 1628 TemplateArgumentListInfo ExplicitArgs; 1629 1630 unsigned CharBits = Context.getIntWidth(CharTy); 1631 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1632 llvm::APSInt Value(CharBits, CharIsUnsigned); 1633 1634 TemplateArgument TypeArg(CharTy); 1635 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1636 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1637 1638 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1639 Value = Lit->getCodeUnit(I); 1640 TemplateArgument Arg(Context, Value, CharTy); 1641 TemplateArgumentLocInfo ArgInfo; 1642 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1643 } 1644 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1645 &ExplicitArgs); 1646 } 1647 case LOLR_Raw: 1648 case LOLR_Template: 1649 llvm_unreachable("unexpected literal operator lookup result"); 1650 case LOLR_Error: 1651 return ExprError(); 1652 } 1653 llvm_unreachable("unexpected literal operator lookup result"); 1654 } 1655 1656 ExprResult 1657 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1658 SourceLocation Loc, 1659 const CXXScopeSpec *SS) { 1660 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1661 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1662 } 1663 1664 /// BuildDeclRefExpr - Build an expression that references a 1665 /// declaration that does not require a closure capture. 1666 ExprResult 1667 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1668 const DeclarationNameInfo &NameInfo, 1669 const CXXScopeSpec *SS, NamedDecl *FoundD, 1670 const TemplateArgumentListInfo *TemplateArgs) { 1671 if (getLangOpts().CUDA) 1672 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1673 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1674 if (CheckCUDATarget(Caller, Callee)) { 1675 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1676 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1677 << IdentifyCUDATarget(Caller); 1678 Diag(D->getLocation(), diag::note_previous_decl) 1679 << D->getIdentifier(); 1680 return ExprError(); 1681 } 1682 } 1683 1684 bool RefersToCapturedVariable = 1685 isa<VarDecl>(D) && 1686 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1687 1688 DeclRefExpr *E; 1689 if (isa<VarTemplateSpecializationDecl>(D)) { 1690 VarTemplateSpecializationDecl *VarSpec = 1691 cast<VarTemplateSpecializationDecl>(D); 1692 1693 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1694 : NestedNameSpecifierLoc(), 1695 VarSpec->getTemplateKeywordLoc(), D, 1696 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1697 FoundD, TemplateArgs); 1698 } else { 1699 assert(!TemplateArgs && "No template arguments for non-variable" 1700 " template specialization references"); 1701 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1702 : NestedNameSpecifierLoc(), 1703 SourceLocation(), D, RefersToCapturedVariable, 1704 NameInfo, Ty, VK, FoundD); 1705 } 1706 1707 MarkDeclRefReferenced(E); 1708 1709 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1710 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1711 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1712 recordUseOfEvaluatedWeak(E); 1713 1714 // Just in case we're building an illegal pointer-to-member. 1715 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1716 if (FD && FD->isBitField()) 1717 E->setObjectKind(OK_BitField); 1718 1719 return E; 1720 } 1721 1722 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1723 /// possibly a list of template arguments. 1724 /// 1725 /// If this produces template arguments, it is permitted to call 1726 /// DecomposeTemplateName. 1727 /// 1728 /// This actually loses a lot of source location information for 1729 /// non-standard name kinds; we should consider preserving that in 1730 /// some way. 1731 void 1732 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1733 TemplateArgumentListInfo &Buffer, 1734 DeclarationNameInfo &NameInfo, 1735 const TemplateArgumentListInfo *&TemplateArgs) { 1736 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1737 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1738 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1739 1740 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1741 Id.TemplateId->NumArgs); 1742 translateTemplateArguments(TemplateArgsPtr, Buffer); 1743 1744 TemplateName TName = Id.TemplateId->Template.get(); 1745 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1746 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1747 TemplateArgs = &Buffer; 1748 } else { 1749 NameInfo = GetNameFromUnqualifiedId(Id); 1750 TemplateArgs = nullptr; 1751 } 1752 } 1753 1754 static void emitEmptyLookupTypoDiagnostic( 1755 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1756 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1757 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1758 DeclContext *Ctx = 1759 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1760 if (!TC) { 1761 // Emit a special diagnostic for failed member lookups. 1762 // FIXME: computing the declaration context might fail here (?) 1763 if (Ctx) 1764 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1765 << SS.getRange(); 1766 else 1767 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1768 return; 1769 } 1770 1771 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1772 bool DroppedSpecifier = 1773 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1774 unsigned NoteID = 1775 (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl())) 1776 ? diag::note_implicit_param_decl 1777 : diag::note_previous_decl; 1778 if (!Ctx) 1779 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1780 SemaRef.PDiag(NoteID)); 1781 else 1782 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1783 << Typo << Ctx << DroppedSpecifier 1784 << SS.getRange(), 1785 SemaRef.PDiag(NoteID)); 1786 } 1787 1788 /// Diagnose an empty lookup. 1789 /// 1790 /// \return false if new lookup candidates were found 1791 bool 1792 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1793 std::unique_ptr<CorrectionCandidateCallback> CCC, 1794 TemplateArgumentListInfo *ExplicitTemplateArgs, 1795 ArrayRef<Expr *> Args, TypoExpr **Out) { 1796 DeclarationName Name = R.getLookupName(); 1797 1798 unsigned diagnostic = diag::err_undeclared_var_use; 1799 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1800 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1801 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1802 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1803 diagnostic = diag::err_undeclared_use; 1804 diagnostic_suggest = diag::err_undeclared_use_suggest; 1805 } 1806 1807 // If the original lookup was an unqualified lookup, fake an 1808 // unqualified lookup. This is useful when (for example) the 1809 // original lookup would not have found something because it was a 1810 // dependent name. 1811 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1812 while (DC) { 1813 if (isa<CXXRecordDecl>(DC)) { 1814 LookupQualifiedName(R, DC); 1815 1816 if (!R.empty()) { 1817 // Don't give errors about ambiguities in this lookup. 1818 R.suppressDiagnostics(); 1819 1820 // During a default argument instantiation the CurContext points 1821 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1822 // function parameter list, hence add an explicit check. 1823 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1824 ActiveTemplateInstantiations.back().Kind == 1825 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1826 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1827 bool isInstance = CurMethod && 1828 CurMethod->isInstance() && 1829 DC == CurMethod->getParent() && !isDefaultArgument; 1830 1831 // Give a code modification hint to insert 'this->'. 1832 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1833 // Actually quite difficult! 1834 if (getLangOpts().MSVCCompat) 1835 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1836 if (isInstance) { 1837 Diag(R.getNameLoc(), diagnostic) << Name 1838 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1839 CheckCXXThisCapture(R.getNameLoc()); 1840 } else { 1841 Diag(R.getNameLoc(), diagnostic) << Name; 1842 } 1843 1844 // Do we really want to note all of these? 1845 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1846 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1847 1848 // Return true if we are inside a default argument instantiation 1849 // and the found name refers to an instance member function, otherwise 1850 // the function calling DiagnoseEmptyLookup will try to create an 1851 // implicit member call and this is wrong for default argument. 1852 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1853 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1854 return true; 1855 } 1856 1857 // Tell the callee to try to recover. 1858 return false; 1859 } 1860 1861 R.clear(); 1862 } 1863 1864 // In Microsoft mode, if we are performing lookup from within a friend 1865 // function definition declared at class scope then we must set 1866 // DC to the lexical parent to be able to search into the parent 1867 // class. 1868 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1869 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1870 DC->getLexicalParent()->isRecord()) 1871 DC = DC->getLexicalParent(); 1872 else 1873 DC = DC->getParent(); 1874 } 1875 1876 // We didn't find anything, so try to correct for a typo. 1877 TypoCorrection Corrected; 1878 if (S && Out) { 1879 SourceLocation TypoLoc = R.getNameLoc(); 1880 assert(!ExplicitTemplateArgs && 1881 "Diagnosing an empty lookup with explicit template args!"); 1882 *Out = CorrectTypoDelayed( 1883 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1884 [=](const TypoCorrection &TC) { 1885 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1886 diagnostic, diagnostic_suggest); 1887 }, 1888 nullptr, CTK_ErrorRecovery); 1889 if (*Out) 1890 return true; 1891 } else if (S && (Corrected = 1892 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1893 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1894 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1895 bool DroppedSpecifier = 1896 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1897 R.setLookupName(Corrected.getCorrection()); 1898 1899 bool AcceptableWithRecovery = false; 1900 bool AcceptableWithoutRecovery = false; 1901 NamedDecl *ND = Corrected.getCorrectionDecl(); 1902 if (ND) { 1903 if (Corrected.isOverloaded()) { 1904 OverloadCandidateSet OCS(R.getNameLoc(), 1905 OverloadCandidateSet::CSK_Normal); 1906 OverloadCandidateSet::iterator Best; 1907 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1908 CDEnd = Corrected.end(); 1909 CD != CDEnd; ++CD) { 1910 if (FunctionTemplateDecl *FTD = 1911 dyn_cast<FunctionTemplateDecl>(*CD)) 1912 AddTemplateOverloadCandidate( 1913 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1914 Args, OCS); 1915 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1916 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1917 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1918 Args, OCS); 1919 } 1920 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1921 case OR_Success: 1922 ND = Best->Function; 1923 Corrected.setCorrectionDecl(ND); 1924 break; 1925 default: 1926 // FIXME: Arbitrarily pick the first declaration for the note. 1927 Corrected.setCorrectionDecl(ND); 1928 break; 1929 } 1930 } 1931 R.addDecl(ND); 1932 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1933 CXXRecordDecl *Record = nullptr; 1934 if (Corrected.getCorrectionSpecifier()) { 1935 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1936 Record = Ty->getAsCXXRecordDecl(); 1937 } 1938 if (!Record) 1939 Record = cast<CXXRecordDecl>( 1940 ND->getDeclContext()->getRedeclContext()); 1941 R.setNamingClass(Record); 1942 } 1943 1944 AcceptableWithRecovery = 1945 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1946 // FIXME: If we ended up with a typo for a type name or 1947 // Objective-C class name, we're in trouble because the parser 1948 // is in the wrong place to recover. Suggest the typo 1949 // correction, but don't make it a fix-it since we're not going 1950 // to recover well anyway. 1951 AcceptableWithoutRecovery = 1952 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1953 } else { 1954 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1955 // because we aren't able to recover. 1956 AcceptableWithoutRecovery = true; 1957 } 1958 1959 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1960 unsigned NoteID = (Corrected.getCorrectionDecl() && 1961 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1962 ? diag::note_implicit_param_decl 1963 : diag::note_previous_decl; 1964 if (SS.isEmpty()) 1965 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1966 PDiag(NoteID), AcceptableWithRecovery); 1967 else 1968 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1969 << Name << computeDeclContext(SS, false) 1970 << DroppedSpecifier << SS.getRange(), 1971 PDiag(NoteID), AcceptableWithRecovery); 1972 1973 // Tell the callee whether to try to recover. 1974 return !AcceptableWithRecovery; 1975 } 1976 } 1977 R.clear(); 1978 1979 // Emit a special diagnostic for failed member lookups. 1980 // FIXME: computing the declaration context might fail here (?) 1981 if (!SS.isEmpty()) { 1982 Diag(R.getNameLoc(), diag::err_no_member) 1983 << Name << computeDeclContext(SS, false) 1984 << SS.getRange(); 1985 return true; 1986 } 1987 1988 // Give up, we can't recover. 1989 Diag(R.getNameLoc(), diagnostic) << Name; 1990 return true; 1991 } 1992 1993 /// In Microsoft mode, if we are inside a template class whose parent class has 1994 /// dependent base classes, and we can't resolve an unqualified identifier, then 1995 /// assume the identifier is a member of a dependent base class. We can only 1996 /// recover successfully in static methods, instance methods, and other contexts 1997 /// where 'this' is available. This doesn't precisely match MSVC's 1998 /// instantiation model, but it's close enough. 1999 static Expr * 2000 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2001 DeclarationNameInfo &NameInfo, 2002 SourceLocation TemplateKWLoc, 2003 const TemplateArgumentListInfo *TemplateArgs) { 2004 // Only try to recover from lookup into dependent bases in static methods or 2005 // contexts where 'this' is available. 2006 QualType ThisType = S.getCurrentThisType(); 2007 const CXXRecordDecl *RD = nullptr; 2008 if (!ThisType.isNull()) 2009 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2010 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2011 RD = MD->getParent(); 2012 if (!RD || !RD->hasAnyDependentBases()) 2013 return nullptr; 2014 2015 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2016 // is available, suggest inserting 'this->' as a fixit. 2017 SourceLocation Loc = NameInfo.getLoc(); 2018 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2019 DB << NameInfo.getName() << RD; 2020 2021 if (!ThisType.isNull()) { 2022 DB << FixItHint::CreateInsertion(Loc, "this->"); 2023 return CXXDependentScopeMemberExpr::Create( 2024 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2025 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2026 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2027 } 2028 2029 // Synthesize a fake NNS that points to the derived class. This will 2030 // perform name lookup during template instantiation. 2031 CXXScopeSpec SS; 2032 auto *NNS = 2033 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2034 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2035 return DependentScopeDeclRefExpr::Create( 2036 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2037 TemplateArgs); 2038 } 2039 2040 ExprResult 2041 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2042 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2043 bool HasTrailingLParen, bool IsAddressOfOperand, 2044 std::unique_ptr<CorrectionCandidateCallback> CCC, 2045 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2046 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2047 "cannot be direct & operand and have a trailing lparen"); 2048 if (SS.isInvalid()) 2049 return ExprError(); 2050 2051 TemplateArgumentListInfo TemplateArgsBuffer; 2052 2053 // Decompose the UnqualifiedId into the following data. 2054 DeclarationNameInfo NameInfo; 2055 const TemplateArgumentListInfo *TemplateArgs; 2056 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2057 2058 DeclarationName Name = NameInfo.getName(); 2059 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2060 SourceLocation NameLoc = NameInfo.getLoc(); 2061 2062 // C++ [temp.dep.expr]p3: 2063 // An id-expression is type-dependent if it contains: 2064 // -- an identifier that was declared with a dependent type, 2065 // (note: handled after lookup) 2066 // -- a template-id that is dependent, 2067 // (note: handled in BuildTemplateIdExpr) 2068 // -- a conversion-function-id that specifies a dependent type, 2069 // -- a nested-name-specifier that contains a class-name that 2070 // names a dependent type. 2071 // Determine whether this is a member of an unknown specialization; 2072 // we need to handle these differently. 2073 bool DependentID = false; 2074 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2075 Name.getCXXNameType()->isDependentType()) { 2076 DependentID = true; 2077 } else if (SS.isSet()) { 2078 if (DeclContext *DC = computeDeclContext(SS, false)) { 2079 if (RequireCompleteDeclContext(SS, DC)) 2080 return ExprError(); 2081 } else { 2082 DependentID = true; 2083 } 2084 } 2085 2086 if (DependentID) 2087 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2088 IsAddressOfOperand, TemplateArgs); 2089 2090 // Perform the required lookup. 2091 LookupResult R(*this, NameInfo, 2092 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2093 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2094 if (TemplateArgs) { 2095 // Lookup the template name again to correctly establish the context in 2096 // which it was found. This is really unfortunate as we already did the 2097 // lookup to determine that it was a template name in the first place. If 2098 // this becomes a performance hit, we can work harder to preserve those 2099 // results until we get here but it's likely not worth it. 2100 bool MemberOfUnknownSpecialization; 2101 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2102 MemberOfUnknownSpecialization); 2103 2104 if (MemberOfUnknownSpecialization || 2105 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2106 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2107 IsAddressOfOperand, TemplateArgs); 2108 } else { 2109 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2110 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2111 2112 // If the result might be in a dependent base class, this is a dependent 2113 // id-expression. 2114 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2115 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2116 IsAddressOfOperand, TemplateArgs); 2117 2118 // If this reference is in an Objective-C method, then we need to do 2119 // some special Objective-C lookup, too. 2120 if (IvarLookupFollowUp) { 2121 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2122 if (E.isInvalid()) 2123 return ExprError(); 2124 2125 if (Expr *Ex = E.getAs<Expr>()) 2126 return Ex; 2127 } 2128 } 2129 2130 if (R.isAmbiguous()) 2131 return ExprError(); 2132 2133 // This could be an implicitly declared function reference (legal in C90, 2134 // extension in C99, forbidden in C++). 2135 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2136 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2137 if (D) R.addDecl(D); 2138 } 2139 2140 // Determine whether this name might be a candidate for 2141 // argument-dependent lookup. 2142 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2143 2144 if (R.empty() && !ADL) { 2145 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2146 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2147 TemplateKWLoc, TemplateArgs)) 2148 return E; 2149 } 2150 2151 // Don't diagnose an empty lookup for inline assembly. 2152 if (IsInlineAsmIdentifier) 2153 return ExprError(); 2154 2155 // If this name wasn't predeclared and if this is not a function 2156 // call, diagnose the problem. 2157 TypoExpr *TE = nullptr; 2158 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2159 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2160 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2161 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2162 "Typo correction callback misconfigured"); 2163 if (CCC) { 2164 // Make sure the callback knows what the typo being diagnosed is. 2165 CCC->setTypoName(II); 2166 if (SS.isValid()) 2167 CCC->setTypoNNS(SS.getScopeRep()); 2168 } 2169 if (DiagnoseEmptyLookup(S, SS, R, 2170 CCC ? std::move(CCC) : std::move(DefaultValidator), 2171 nullptr, None, &TE)) { 2172 if (TE && KeywordReplacement) { 2173 auto &State = getTypoExprState(TE); 2174 auto BestTC = State.Consumer->getNextCorrection(); 2175 if (BestTC.isKeyword()) { 2176 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2177 if (State.DiagHandler) 2178 State.DiagHandler(BestTC); 2179 KeywordReplacement->startToken(); 2180 KeywordReplacement->setKind(II->getTokenID()); 2181 KeywordReplacement->setIdentifierInfo(II); 2182 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2183 // Clean up the state associated with the TypoExpr, since it has 2184 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2185 clearDelayedTypo(TE); 2186 // Signal that a correction to a keyword was performed by returning a 2187 // valid-but-null ExprResult. 2188 return (Expr*)nullptr; 2189 } 2190 State.Consumer->resetCorrectionStream(); 2191 } 2192 return TE ? TE : ExprError(); 2193 } 2194 2195 assert(!R.empty() && 2196 "DiagnoseEmptyLookup returned false but added no results"); 2197 2198 // If we found an Objective-C instance variable, let 2199 // LookupInObjCMethod build the appropriate expression to 2200 // reference the ivar. 2201 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2202 R.clear(); 2203 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2204 // In a hopelessly buggy code, Objective-C instance variable 2205 // lookup fails and no expression will be built to reference it. 2206 if (!E.isInvalid() && !E.get()) 2207 return ExprError(); 2208 return E; 2209 } 2210 } 2211 2212 // This is guaranteed from this point on. 2213 assert(!R.empty() || ADL); 2214 2215 // Check whether this might be a C++ implicit instance member access. 2216 // C++ [class.mfct.non-static]p3: 2217 // When an id-expression that is not part of a class member access 2218 // syntax and not used to form a pointer to member is used in the 2219 // body of a non-static member function of class X, if name lookup 2220 // resolves the name in the id-expression to a non-static non-type 2221 // member of some class C, the id-expression is transformed into a 2222 // class member access expression using (*this) as the 2223 // postfix-expression to the left of the . operator. 2224 // 2225 // But we don't actually need to do this for '&' operands if R 2226 // resolved to a function or overloaded function set, because the 2227 // expression is ill-formed if it actually works out to be a 2228 // non-static member function: 2229 // 2230 // C++ [expr.ref]p4: 2231 // Otherwise, if E1.E2 refers to a non-static member function. . . 2232 // [t]he expression can be used only as the left-hand operand of a 2233 // member function call. 2234 // 2235 // There are other safeguards against such uses, but it's important 2236 // to get this right here so that we don't end up making a 2237 // spuriously dependent expression if we're inside a dependent 2238 // instance method. 2239 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2240 bool MightBeImplicitMember; 2241 if (!IsAddressOfOperand) 2242 MightBeImplicitMember = true; 2243 else if (!SS.isEmpty()) 2244 MightBeImplicitMember = false; 2245 else if (R.isOverloadedResult()) 2246 MightBeImplicitMember = false; 2247 else if (R.isUnresolvableResult()) 2248 MightBeImplicitMember = true; 2249 else 2250 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2251 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2252 isa<MSPropertyDecl>(R.getFoundDecl()); 2253 2254 if (MightBeImplicitMember) 2255 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2256 R, TemplateArgs, S); 2257 } 2258 2259 if (TemplateArgs || TemplateKWLoc.isValid()) { 2260 2261 // In C++1y, if this is a variable template id, then check it 2262 // in BuildTemplateIdExpr(). 2263 // The single lookup result must be a variable template declaration. 2264 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2265 Id.TemplateId->Kind == TNK_Var_template) { 2266 assert(R.getAsSingle<VarTemplateDecl>() && 2267 "There should only be one declaration found."); 2268 } 2269 2270 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2271 } 2272 2273 return BuildDeclarationNameExpr(SS, R, ADL); 2274 } 2275 2276 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2277 /// declaration name, generally during template instantiation. 2278 /// There's a large number of things which don't need to be done along 2279 /// this path. 2280 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2281 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2282 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2283 DeclContext *DC = computeDeclContext(SS, false); 2284 if (!DC) 2285 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2286 NameInfo, /*TemplateArgs=*/nullptr); 2287 2288 if (RequireCompleteDeclContext(SS, DC)) 2289 return ExprError(); 2290 2291 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2292 LookupQualifiedName(R, DC); 2293 2294 if (R.isAmbiguous()) 2295 return ExprError(); 2296 2297 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2298 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2299 NameInfo, /*TemplateArgs=*/nullptr); 2300 2301 if (R.empty()) { 2302 Diag(NameInfo.getLoc(), diag::err_no_member) 2303 << NameInfo.getName() << DC << SS.getRange(); 2304 return ExprError(); 2305 } 2306 2307 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2308 // Diagnose a missing typename if this resolved unambiguously to a type in 2309 // a dependent context. If we can recover with a type, downgrade this to 2310 // a warning in Microsoft compatibility mode. 2311 unsigned DiagID = diag::err_typename_missing; 2312 if (RecoveryTSI && getLangOpts().MSVCCompat) 2313 DiagID = diag::ext_typename_missing; 2314 SourceLocation Loc = SS.getBeginLoc(); 2315 auto D = Diag(Loc, DiagID); 2316 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2317 << SourceRange(Loc, NameInfo.getEndLoc()); 2318 2319 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2320 // context. 2321 if (!RecoveryTSI) 2322 return ExprError(); 2323 2324 // Only issue the fixit if we're prepared to recover. 2325 D << FixItHint::CreateInsertion(Loc, "typename "); 2326 2327 // Recover by pretending this was an elaborated type. 2328 QualType Ty = Context.getTypeDeclType(TD); 2329 TypeLocBuilder TLB; 2330 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2331 2332 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2333 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2334 QTL.setElaboratedKeywordLoc(SourceLocation()); 2335 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2336 2337 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2338 2339 return ExprEmpty(); 2340 } 2341 2342 // Defend against this resolving to an implicit member access. We usually 2343 // won't get here if this might be a legitimate a class member (we end up in 2344 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2345 // a pointer-to-member or in an unevaluated context in C++11. 2346 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2347 return BuildPossibleImplicitMemberExpr(SS, 2348 /*TemplateKWLoc=*/SourceLocation(), 2349 R, /*TemplateArgs=*/nullptr, S); 2350 2351 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2352 } 2353 2354 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2355 /// detected that we're currently inside an ObjC method. Perform some 2356 /// additional lookup. 2357 /// 2358 /// Ideally, most of this would be done by lookup, but there's 2359 /// actually quite a lot of extra work involved. 2360 /// 2361 /// Returns a null sentinel to indicate trivial success. 2362 ExprResult 2363 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2364 IdentifierInfo *II, bool AllowBuiltinCreation) { 2365 SourceLocation Loc = Lookup.getNameLoc(); 2366 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2367 2368 // Check for error condition which is already reported. 2369 if (!CurMethod) 2370 return ExprError(); 2371 2372 // There are two cases to handle here. 1) scoped lookup could have failed, 2373 // in which case we should look for an ivar. 2) scoped lookup could have 2374 // found a decl, but that decl is outside the current instance method (i.e. 2375 // a global variable). In these two cases, we do a lookup for an ivar with 2376 // this name, if the lookup sucedes, we replace it our current decl. 2377 2378 // If we're in a class method, we don't normally want to look for 2379 // ivars. But if we don't find anything else, and there's an 2380 // ivar, that's an error. 2381 bool IsClassMethod = CurMethod->isClassMethod(); 2382 2383 bool LookForIvars; 2384 if (Lookup.empty()) 2385 LookForIvars = true; 2386 else if (IsClassMethod) 2387 LookForIvars = false; 2388 else 2389 LookForIvars = (Lookup.isSingleResult() && 2390 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2391 ObjCInterfaceDecl *IFace = nullptr; 2392 if (LookForIvars) { 2393 IFace = CurMethod->getClassInterface(); 2394 ObjCInterfaceDecl *ClassDeclared; 2395 ObjCIvarDecl *IV = nullptr; 2396 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2397 // Diagnose using an ivar in a class method. 2398 if (IsClassMethod) 2399 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2400 << IV->getDeclName()); 2401 2402 // If we're referencing an invalid decl, just return this as a silent 2403 // error node. The error diagnostic was already emitted on the decl. 2404 if (IV->isInvalidDecl()) 2405 return ExprError(); 2406 2407 // Check if referencing a field with __attribute__((deprecated)). 2408 if (DiagnoseUseOfDecl(IV, Loc)) 2409 return ExprError(); 2410 2411 // Diagnose the use of an ivar outside of the declaring class. 2412 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2413 !declaresSameEntity(ClassDeclared, IFace) && 2414 !getLangOpts().DebuggerSupport) 2415 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2416 2417 // FIXME: This should use a new expr for a direct reference, don't 2418 // turn this into Self->ivar, just return a BareIVarExpr or something. 2419 IdentifierInfo &II = Context.Idents.get("self"); 2420 UnqualifiedId SelfName; 2421 SelfName.setIdentifier(&II, SourceLocation()); 2422 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2423 CXXScopeSpec SelfScopeSpec; 2424 SourceLocation TemplateKWLoc; 2425 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2426 SelfName, false, false); 2427 if (SelfExpr.isInvalid()) 2428 return ExprError(); 2429 2430 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2431 if (SelfExpr.isInvalid()) 2432 return ExprError(); 2433 2434 MarkAnyDeclReferenced(Loc, IV, true); 2435 2436 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2437 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2438 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2439 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2440 2441 ObjCIvarRefExpr *Result = new (Context) 2442 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2443 IV->getLocation(), SelfExpr.get(), true, true); 2444 2445 if (getLangOpts().ObjCAutoRefCount) { 2446 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2447 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2448 recordUseOfEvaluatedWeak(Result); 2449 } 2450 if (CurContext->isClosure()) 2451 Diag(Loc, diag::warn_implicitly_retains_self) 2452 << FixItHint::CreateInsertion(Loc, "self->"); 2453 } 2454 2455 return Result; 2456 } 2457 } else if (CurMethod->isInstanceMethod()) { 2458 // We should warn if a local variable hides an ivar. 2459 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2460 ObjCInterfaceDecl *ClassDeclared; 2461 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2462 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2463 declaresSameEntity(IFace, ClassDeclared)) 2464 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2465 } 2466 } 2467 } else if (Lookup.isSingleResult() && 2468 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2469 // If accessing a stand-alone ivar in a class method, this is an error. 2470 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2471 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2472 << IV->getDeclName()); 2473 } 2474 2475 if (Lookup.empty() && II && AllowBuiltinCreation) { 2476 // FIXME. Consolidate this with similar code in LookupName. 2477 if (unsigned BuiltinID = II->getBuiltinID()) { 2478 if (!(getLangOpts().CPlusPlus && 2479 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2480 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2481 S, Lookup.isForRedeclaration(), 2482 Lookup.getNameLoc()); 2483 if (D) Lookup.addDecl(D); 2484 } 2485 } 2486 } 2487 // Sentinel value saying that we didn't do anything special. 2488 return ExprResult((Expr *)nullptr); 2489 } 2490 2491 /// \brief Cast a base object to a member's actual type. 2492 /// 2493 /// Logically this happens in three phases: 2494 /// 2495 /// * First we cast from the base type to the naming class. 2496 /// The naming class is the class into which we were looking 2497 /// when we found the member; it's the qualifier type if a 2498 /// qualifier was provided, and otherwise it's the base type. 2499 /// 2500 /// * Next we cast from the naming class to the declaring class. 2501 /// If the member we found was brought into a class's scope by 2502 /// a using declaration, this is that class; otherwise it's 2503 /// the class declaring the member. 2504 /// 2505 /// * Finally we cast from the declaring class to the "true" 2506 /// declaring class of the member. This conversion does not 2507 /// obey access control. 2508 ExprResult 2509 Sema::PerformObjectMemberConversion(Expr *From, 2510 NestedNameSpecifier *Qualifier, 2511 NamedDecl *FoundDecl, 2512 NamedDecl *Member) { 2513 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2514 if (!RD) 2515 return From; 2516 2517 QualType DestRecordType; 2518 QualType DestType; 2519 QualType FromRecordType; 2520 QualType FromType = From->getType(); 2521 bool PointerConversions = false; 2522 if (isa<FieldDecl>(Member)) { 2523 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2524 2525 if (FromType->getAs<PointerType>()) { 2526 DestType = Context.getPointerType(DestRecordType); 2527 FromRecordType = FromType->getPointeeType(); 2528 PointerConversions = true; 2529 } else { 2530 DestType = DestRecordType; 2531 FromRecordType = FromType; 2532 } 2533 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2534 if (Method->isStatic()) 2535 return From; 2536 2537 DestType = Method->getThisType(Context); 2538 DestRecordType = DestType->getPointeeType(); 2539 2540 if (FromType->getAs<PointerType>()) { 2541 FromRecordType = FromType->getPointeeType(); 2542 PointerConversions = true; 2543 } else { 2544 FromRecordType = FromType; 2545 DestType = DestRecordType; 2546 } 2547 } else { 2548 // No conversion necessary. 2549 return From; 2550 } 2551 2552 if (DestType->isDependentType() || FromType->isDependentType()) 2553 return From; 2554 2555 // If the unqualified types are the same, no conversion is necessary. 2556 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2557 return From; 2558 2559 SourceRange FromRange = From->getSourceRange(); 2560 SourceLocation FromLoc = FromRange.getBegin(); 2561 2562 ExprValueKind VK = From->getValueKind(); 2563 2564 // C++ [class.member.lookup]p8: 2565 // [...] Ambiguities can often be resolved by qualifying a name with its 2566 // class name. 2567 // 2568 // If the member was a qualified name and the qualified referred to a 2569 // specific base subobject type, we'll cast to that intermediate type 2570 // first and then to the object in which the member is declared. That allows 2571 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2572 // 2573 // class Base { public: int x; }; 2574 // class Derived1 : public Base { }; 2575 // class Derived2 : public Base { }; 2576 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2577 // 2578 // void VeryDerived::f() { 2579 // x = 17; // error: ambiguous base subobjects 2580 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2581 // } 2582 if (Qualifier && Qualifier->getAsType()) { 2583 QualType QType = QualType(Qualifier->getAsType(), 0); 2584 assert(QType->isRecordType() && "lookup done with non-record type"); 2585 2586 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2587 2588 // In C++98, the qualifier type doesn't actually have to be a base 2589 // type of the object type, in which case we just ignore it. 2590 // Otherwise build the appropriate casts. 2591 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2592 CXXCastPath BasePath; 2593 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2594 FromLoc, FromRange, &BasePath)) 2595 return ExprError(); 2596 2597 if (PointerConversions) 2598 QType = Context.getPointerType(QType); 2599 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2600 VK, &BasePath).get(); 2601 2602 FromType = QType; 2603 FromRecordType = QRecordType; 2604 2605 // If the qualifier type was the same as the destination type, 2606 // we're done. 2607 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2608 return From; 2609 } 2610 } 2611 2612 bool IgnoreAccess = false; 2613 2614 // If we actually found the member through a using declaration, cast 2615 // down to the using declaration's type. 2616 // 2617 // Pointer equality is fine here because only one declaration of a 2618 // class ever has member declarations. 2619 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2620 assert(isa<UsingShadowDecl>(FoundDecl)); 2621 QualType URecordType = Context.getTypeDeclType( 2622 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2623 2624 // We only need to do this if the naming-class to declaring-class 2625 // conversion is non-trivial. 2626 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2627 assert(IsDerivedFrom(FromRecordType, URecordType)); 2628 CXXCastPath BasePath; 2629 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2630 FromLoc, FromRange, &BasePath)) 2631 return ExprError(); 2632 2633 QualType UType = URecordType; 2634 if (PointerConversions) 2635 UType = Context.getPointerType(UType); 2636 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2637 VK, &BasePath).get(); 2638 FromType = UType; 2639 FromRecordType = URecordType; 2640 } 2641 2642 // We don't do access control for the conversion from the 2643 // declaring class to the true declaring class. 2644 IgnoreAccess = true; 2645 } 2646 2647 CXXCastPath BasePath; 2648 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2649 FromLoc, FromRange, &BasePath, 2650 IgnoreAccess)) 2651 return ExprError(); 2652 2653 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2654 VK, &BasePath); 2655 } 2656 2657 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2658 const LookupResult &R, 2659 bool HasTrailingLParen) { 2660 // Only when used directly as the postfix-expression of a call. 2661 if (!HasTrailingLParen) 2662 return false; 2663 2664 // Never if a scope specifier was provided. 2665 if (SS.isSet()) 2666 return false; 2667 2668 // Only in C++ or ObjC++. 2669 if (!getLangOpts().CPlusPlus) 2670 return false; 2671 2672 // Turn off ADL when we find certain kinds of declarations during 2673 // normal lookup: 2674 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2675 NamedDecl *D = *I; 2676 2677 // C++0x [basic.lookup.argdep]p3: 2678 // -- a declaration of a class member 2679 // Since using decls preserve this property, we check this on the 2680 // original decl. 2681 if (D->isCXXClassMember()) 2682 return false; 2683 2684 // C++0x [basic.lookup.argdep]p3: 2685 // -- a block-scope function declaration that is not a 2686 // using-declaration 2687 // NOTE: we also trigger this for function templates (in fact, we 2688 // don't check the decl type at all, since all other decl types 2689 // turn off ADL anyway). 2690 if (isa<UsingShadowDecl>(D)) 2691 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2692 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2693 return false; 2694 2695 // C++0x [basic.lookup.argdep]p3: 2696 // -- a declaration that is neither a function or a function 2697 // template 2698 // And also for builtin functions. 2699 if (isa<FunctionDecl>(D)) { 2700 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2701 2702 // But also builtin functions. 2703 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2704 return false; 2705 } else if (!isa<FunctionTemplateDecl>(D)) 2706 return false; 2707 } 2708 2709 return true; 2710 } 2711 2712 2713 /// Diagnoses obvious problems with the use of the given declaration 2714 /// as an expression. This is only actually called for lookups that 2715 /// were not overloaded, and it doesn't promise that the declaration 2716 /// will in fact be used. 2717 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2718 if (isa<TypedefNameDecl>(D)) { 2719 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2720 return true; 2721 } 2722 2723 if (isa<ObjCInterfaceDecl>(D)) { 2724 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2725 return true; 2726 } 2727 2728 if (isa<NamespaceDecl>(D)) { 2729 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2730 return true; 2731 } 2732 2733 return false; 2734 } 2735 2736 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2737 LookupResult &R, bool NeedsADL, 2738 bool AcceptInvalidDecl) { 2739 // If this is a single, fully-resolved result and we don't need ADL, 2740 // just build an ordinary singleton decl ref. 2741 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2742 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2743 R.getRepresentativeDecl(), nullptr, 2744 AcceptInvalidDecl); 2745 2746 // We only need to check the declaration if there's exactly one 2747 // result, because in the overloaded case the results can only be 2748 // functions and function templates. 2749 if (R.isSingleResult() && 2750 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2751 return ExprError(); 2752 2753 // Otherwise, just build an unresolved lookup expression. Suppress 2754 // any lookup-related diagnostics; we'll hash these out later, when 2755 // we've picked a target. 2756 R.suppressDiagnostics(); 2757 2758 UnresolvedLookupExpr *ULE 2759 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2760 SS.getWithLocInContext(Context), 2761 R.getLookupNameInfo(), 2762 NeedsADL, R.isOverloadedResult(), 2763 R.begin(), R.end()); 2764 2765 return ULE; 2766 } 2767 2768 /// \brief Complete semantic analysis for a reference to the given declaration. 2769 ExprResult Sema::BuildDeclarationNameExpr( 2770 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2771 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2772 bool AcceptInvalidDecl) { 2773 assert(D && "Cannot refer to a NULL declaration"); 2774 assert(!isa<FunctionTemplateDecl>(D) && 2775 "Cannot refer unambiguously to a function template"); 2776 2777 SourceLocation Loc = NameInfo.getLoc(); 2778 if (CheckDeclInExpr(*this, Loc, D)) 2779 return ExprError(); 2780 2781 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2782 // Specifically diagnose references to class templates that are missing 2783 // a template argument list. 2784 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2785 << Template << SS.getRange(); 2786 Diag(Template->getLocation(), diag::note_template_decl_here); 2787 return ExprError(); 2788 } 2789 2790 // Make sure that we're referring to a value. 2791 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2792 if (!VD) { 2793 Diag(Loc, diag::err_ref_non_value) 2794 << D << SS.getRange(); 2795 Diag(D->getLocation(), diag::note_declared_at); 2796 return ExprError(); 2797 } 2798 2799 // Check whether this declaration can be used. Note that we suppress 2800 // this check when we're going to perform argument-dependent lookup 2801 // on this function name, because this might not be the function 2802 // that overload resolution actually selects. 2803 if (DiagnoseUseOfDecl(VD, Loc)) 2804 return ExprError(); 2805 2806 // Only create DeclRefExpr's for valid Decl's. 2807 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2808 return ExprError(); 2809 2810 // Handle members of anonymous structs and unions. If we got here, 2811 // and the reference is to a class member indirect field, then this 2812 // must be the subject of a pointer-to-member expression. 2813 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2814 if (!indirectField->isCXXClassMember()) 2815 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2816 indirectField); 2817 2818 { 2819 QualType type = VD->getType(); 2820 ExprValueKind valueKind = VK_RValue; 2821 2822 switch (D->getKind()) { 2823 // Ignore all the non-ValueDecl kinds. 2824 #define ABSTRACT_DECL(kind) 2825 #define VALUE(type, base) 2826 #define DECL(type, base) \ 2827 case Decl::type: 2828 #include "clang/AST/DeclNodes.inc" 2829 llvm_unreachable("invalid value decl kind"); 2830 2831 // These shouldn't make it here. 2832 case Decl::ObjCAtDefsField: 2833 case Decl::ObjCIvar: 2834 llvm_unreachable("forming non-member reference to ivar?"); 2835 2836 // Enum constants are always r-values and never references. 2837 // Unresolved using declarations are dependent. 2838 case Decl::EnumConstant: 2839 case Decl::UnresolvedUsingValue: 2840 valueKind = VK_RValue; 2841 break; 2842 2843 // Fields and indirect fields that got here must be for 2844 // pointer-to-member expressions; we just call them l-values for 2845 // internal consistency, because this subexpression doesn't really 2846 // exist in the high-level semantics. 2847 case Decl::Field: 2848 case Decl::IndirectField: 2849 assert(getLangOpts().CPlusPlus && 2850 "building reference to field in C?"); 2851 2852 // These can't have reference type in well-formed programs, but 2853 // for internal consistency we do this anyway. 2854 type = type.getNonReferenceType(); 2855 valueKind = VK_LValue; 2856 break; 2857 2858 // Non-type template parameters are either l-values or r-values 2859 // depending on the type. 2860 case Decl::NonTypeTemplateParm: { 2861 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2862 type = reftype->getPointeeType(); 2863 valueKind = VK_LValue; // even if the parameter is an r-value reference 2864 break; 2865 } 2866 2867 // For non-references, we need to strip qualifiers just in case 2868 // the template parameter was declared as 'const int' or whatever. 2869 valueKind = VK_RValue; 2870 type = type.getUnqualifiedType(); 2871 break; 2872 } 2873 2874 case Decl::Var: 2875 case Decl::VarTemplateSpecialization: 2876 case Decl::VarTemplatePartialSpecialization: 2877 // In C, "extern void blah;" is valid and is an r-value. 2878 if (!getLangOpts().CPlusPlus && 2879 !type.hasQualifiers() && 2880 type->isVoidType()) { 2881 valueKind = VK_RValue; 2882 break; 2883 } 2884 // fallthrough 2885 2886 case Decl::ImplicitParam: 2887 case Decl::ParmVar: { 2888 // These are always l-values. 2889 valueKind = VK_LValue; 2890 type = type.getNonReferenceType(); 2891 2892 // FIXME: Does the addition of const really only apply in 2893 // potentially-evaluated contexts? Since the variable isn't actually 2894 // captured in an unevaluated context, it seems that the answer is no. 2895 if (!isUnevaluatedContext()) { 2896 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2897 if (!CapturedType.isNull()) 2898 type = CapturedType; 2899 } 2900 2901 break; 2902 } 2903 2904 case Decl::Function: { 2905 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2906 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2907 type = Context.BuiltinFnTy; 2908 valueKind = VK_RValue; 2909 break; 2910 } 2911 } 2912 2913 const FunctionType *fty = type->castAs<FunctionType>(); 2914 2915 // If we're referring to a function with an __unknown_anytype 2916 // result type, make the entire expression __unknown_anytype. 2917 if (fty->getReturnType() == Context.UnknownAnyTy) { 2918 type = Context.UnknownAnyTy; 2919 valueKind = VK_RValue; 2920 break; 2921 } 2922 2923 // Functions are l-values in C++. 2924 if (getLangOpts().CPlusPlus) { 2925 valueKind = VK_LValue; 2926 break; 2927 } 2928 2929 // C99 DR 316 says that, if a function type comes from a 2930 // function definition (without a prototype), that type is only 2931 // used for checking compatibility. Therefore, when referencing 2932 // the function, we pretend that we don't have the full function 2933 // type. 2934 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2935 isa<FunctionProtoType>(fty)) 2936 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2937 fty->getExtInfo()); 2938 2939 // Functions are r-values in C. 2940 valueKind = VK_RValue; 2941 break; 2942 } 2943 2944 case Decl::MSProperty: 2945 valueKind = VK_LValue; 2946 break; 2947 2948 case Decl::CXXMethod: 2949 // If we're referring to a method with an __unknown_anytype 2950 // result type, make the entire expression __unknown_anytype. 2951 // This should only be possible with a type written directly. 2952 if (const FunctionProtoType *proto 2953 = dyn_cast<FunctionProtoType>(VD->getType())) 2954 if (proto->getReturnType() == Context.UnknownAnyTy) { 2955 type = Context.UnknownAnyTy; 2956 valueKind = VK_RValue; 2957 break; 2958 } 2959 2960 // C++ methods are l-values if static, r-values if non-static. 2961 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2962 valueKind = VK_LValue; 2963 break; 2964 } 2965 // fallthrough 2966 2967 case Decl::CXXConversion: 2968 case Decl::CXXDestructor: 2969 case Decl::CXXConstructor: 2970 valueKind = VK_RValue; 2971 break; 2972 } 2973 2974 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2975 TemplateArgs); 2976 } 2977 } 2978 2979 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2980 SmallString<32> &Target) { 2981 Target.resize(CharByteWidth * (Source.size() + 1)); 2982 char *ResultPtr = &Target[0]; 2983 const UTF8 *ErrorPtr; 2984 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2985 (void)success; 2986 assert(success); 2987 Target.resize(ResultPtr - &Target[0]); 2988 } 2989 2990 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2991 PredefinedExpr::IdentType IT) { 2992 // Pick the current block, lambda, captured statement or function. 2993 Decl *currentDecl = nullptr; 2994 if (const BlockScopeInfo *BSI = getCurBlock()) 2995 currentDecl = BSI->TheDecl; 2996 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2997 currentDecl = LSI->CallOperator; 2998 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2999 currentDecl = CSI->TheCapturedDecl; 3000 else 3001 currentDecl = getCurFunctionOrMethodDecl(); 3002 3003 if (!currentDecl) { 3004 Diag(Loc, diag::ext_predef_outside_function); 3005 currentDecl = Context.getTranslationUnitDecl(); 3006 } 3007 3008 QualType ResTy; 3009 StringLiteral *SL = nullptr; 3010 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3011 ResTy = Context.DependentTy; 3012 else { 3013 // Pre-defined identifiers are of type char[x], where x is the length of 3014 // the string. 3015 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3016 unsigned Length = Str.length(); 3017 3018 llvm::APInt LengthI(32, Length + 1); 3019 if (IT == PredefinedExpr::LFunction) { 3020 ResTy = Context.WideCharTy.withConst(); 3021 SmallString<32> RawChars; 3022 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3023 Str, RawChars); 3024 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3025 /*IndexTypeQuals*/ 0); 3026 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3027 /*Pascal*/ false, ResTy, Loc); 3028 } else { 3029 ResTy = Context.CharTy.withConst(); 3030 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3031 /*IndexTypeQuals*/ 0); 3032 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3033 /*Pascal*/ false, ResTy, Loc); 3034 } 3035 } 3036 3037 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3038 } 3039 3040 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3041 PredefinedExpr::IdentType IT; 3042 3043 switch (Kind) { 3044 default: llvm_unreachable("Unknown simple primary expr!"); 3045 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3046 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3047 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3048 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3049 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3050 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3051 } 3052 3053 return BuildPredefinedExpr(Loc, IT); 3054 } 3055 3056 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3057 SmallString<16> CharBuffer; 3058 bool Invalid = false; 3059 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3060 if (Invalid) 3061 return ExprError(); 3062 3063 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3064 PP, Tok.getKind()); 3065 if (Literal.hadError()) 3066 return ExprError(); 3067 3068 QualType Ty; 3069 if (Literal.isWide()) 3070 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3071 else if (Literal.isUTF16()) 3072 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3073 else if (Literal.isUTF32()) 3074 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3075 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3076 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3077 else 3078 Ty = Context.CharTy; // 'x' -> char in C++ 3079 3080 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3081 if (Literal.isWide()) 3082 Kind = CharacterLiteral::Wide; 3083 else if (Literal.isUTF16()) 3084 Kind = CharacterLiteral::UTF16; 3085 else if (Literal.isUTF32()) 3086 Kind = CharacterLiteral::UTF32; 3087 3088 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3089 Tok.getLocation()); 3090 3091 if (Literal.getUDSuffix().empty()) 3092 return Lit; 3093 3094 // We're building a user-defined literal. 3095 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3096 SourceLocation UDSuffixLoc = 3097 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3098 3099 // Make sure we're allowed user-defined literals here. 3100 if (!UDLScope) 3101 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3102 3103 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3104 // operator "" X (ch) 3105 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3106 Lit, Tok.getLocation()); 3107 } 3108 3109 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3110 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3111 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3112 Context.IntTy, Loc); 3113 } 3114 3115 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3116 QualType Ty, SourceLocation Loc) { 3117 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3118 3119 using llvm::APFloat; 3120 APFloat Val(Format); 3121 3122 APFloat::opStatus result = Literal.GetFloatValue(Val); 3123 3124 // Overflow is always an error, but underflow is only an error if 3125 // we underflowed to zero (APFloat reports denormals as underflow). 3126 if ((result & APFloat::opOverflow) || 3127 ((result & APFloat::opUnderflow) && Val.isZero())) { 3128 unsigned diagnostic; 3129 SmallString<20> buffer; 3130 if (result & APFloat::opOverflow) { 3131 diagnostic = diag::warn_float_overflow; 3132 APFloat::getLargest(Format).toString(buffer); 3133 } else { 3134 diagnostic = diag::warn_float_underflow; 3135 APFloat::getSmallest(Format).toString(buffer); 3136 } 3137 3138 S.Diag(Loc, diagnostic) 3139 << Ty 3140 << StringRef(buffer.data(), buffer.size()); 3141 } 3142 3143 bool isExact = (result == APFloat::opOK); 3144 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3145 } 3146 3147 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3148 assert(E && "Invalid expression"); 3149 3150 if (E->isValueDependent()) 3151 return false; 3152 3153 QualType QT = E->getType(); 3154 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3155 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3156 return true; 3157 } 3158 3159 llvm::APSInt ValueAPS; 3160 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3161 3162 if (R.isInvalid()) 3163 return true; 3164 3165 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3166 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3167 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3168 << ValueAPS.toString(10) << ValueIsPositive; 3169 return true; 3170 } 3171 3172 return false; 3173 } 3174 3175 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3176 // Fast path for a single digit (which is quite common). A single digit 3177 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3178 if (Tok.getLength() == 1) { 3179 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3180 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3181 } 3182 3183 SmallString<128> SpellingBuffer; 3184 // NumericLiteralParser wants to overread by one character. Add padding to 3185 // the buffer in case the token is copied to the buffer. If getSpelling() 3186 // returns a StringRef to the memory buffer, it should have a null char at 3187 // the EOF, so it is also safe. 3188 SpellingBuffer.resize(Tok.getLength() + 1); 3189 3190 // Get the spelling of the token, which eliminates trigraphs, etc. 3191 bool Invalid = false; 3192 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3193 if (Invalid) 3194 return ExprError(); 3195 3196 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3197 if (Literal.hadError) 3198 return ExprError(); 3199 3200 if (Literal.hasUDSuffix()) { 3201 // We're building a user-defined literal. 3202 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3203 SourceLocation UDSuffixLoc = 3204 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3205 3206 // Make sure we're allowed user-defined literals here. 3207 if (!UDLScope) 3208 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3209 3210 QualType CookedTy; 3211 if (Literal.isFloatingLiteral()) { 3212 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3213 // long double, the literal is treated as a call of the form 3214 // operator "" X (f L) 3215 CookedTy = Context.LongDoubleTy; 3216 } else { 3217 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3218 // unsigned long long, the literal is treated as a call of the form 3219 // operator "" X (n ULL) 3220 CookedTy = Context.UnsignedLongLongTy; 3221 } 3222 3223 DeclarationName OpName = 3224 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3225 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3226 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3227 3228 SourceLocation TokLoc = Tok.getLocation(); 3229 3230 // Perform literal operator lookup to determine if we're building a raw 3231 // literal or a cooked one. 3232 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3233 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3234 /*AllowRaw*/true, /*AllowTemplate*/true, 3235 /*AllowStringTemplate*/false)) { 3236 case LOLR_Error: 3237 return ExprError(); 3238 3239 case LOLR_Cooked: { 3240 Expr *Lit; 3241 if (Literal.isFloatingLiteral()) { 3242 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3243 } else { 3244 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3245 if (Literal.GetIntegerValue(ResultVal)) 3246 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3247 << /* Unsigned */ 1; 3248 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3249 Tok.getLocation()); 3250 } 3251 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3252 } 3253 3254 case LOLR_Raw: { 3255 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3256 // literal is treated as a call of the form 3257 // operator "" X ("n") 3258 unsigned Length = Literal.getUDSuffixOffset(); 3259 QualType StrTy = Context.getConstantArrayType( 3260 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3261 ArrayType::Normal, 0); 3262 Expr *Lit = StringLiteral::Create( 3263 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3264 /*Pascal*/false, StrTy, &TokLoc, 1); 3265 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3266 } 3267 3268 case LOLR_Template: { 3269 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3270 // template), L is treated as a call fo the form 3271 // operator "" X <'c1', 'c2', ... 'ck'>() 3272 // where n is the source character sequence c1 c2 ... ck. 3273 TemplateArgumentListInfo ExplicitArgs; 3274 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3275 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3276 llvm::APSInt Value(CharBits, CharIsUnsigned); 3277 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3278 Value = TokSpelling[I]; 3279 TemplateArgument Arg(Context, Value, Context.CharTy); 3280 TemplateArgumentLocInfo ArgInfo; 3281 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3282 } 3283 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3284 &ExplicitArgs); 3285 } 3286 case LOLR_StringTemplate: 3287 llvm_unreachable("unexpected literal operator lookup result"); 3288 } 3289 } 3290 3291 Expr *Res; 3292 3293 if (Literal.isFloatingLiteral()) { 3294 QualType Ty; 3295 if (Literal.isFloat) 3296 Ty = Context.FloatTy; 3297 else if (!Literal.isLong) 3298 Ty = Context.DoubleTy; 3299 else 3300 Ty = Context.LongDoubleTy; 3301 3302 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3303 3304 if (Ty == Context.DoubleTy) { 3305 if (getLangOpts().SinglePrecisionConstants) { 3306 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3307 } else if (getLangOpts().OpenCL && 3308 !((getLangOpts().OpenCLVersion >= 120) || 3309 getOpenCLOptions().cl_khr_fp64)) { 3310 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3311 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3312 } 3313 } 3314 } else if (!Literal.isIntegerLiteral()) { 3315 return ExprError(); 3316 } else { 3317 QualType Ty; 3318 3319 // 'long long' is a C99 or C++11 feature. 3320 if (!getLangOpts().C99 && Literal.isLongLong) { 3321 if (getLangOpts().CPlusPlus) 3322 Diag(Tok.getLocation(), 3323 getLangOpts().CPlusPlus11 ? 3324 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3325 else 3326 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3327 } 3328 3329 // Get the value in the widest-possible width. 3330 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3331 llvm::APInt ResultVal(MaxWidth, 0); 3332 3333 if (Literal.GetIntegerValue(ResultVal)) { 3334 // If this value didn't fit into uintmax_t, error and force to ull. 3335 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3336 << /* Unsigned */ 1; 3337 Ty = Context.UnsignedLongLongTy; 3338 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3339 "long long is not intmax_t?"); 3340 } else { 3341 // If this value fits into a ULL, try to figure out what else it fits into 3342 // according to the rules of C99 6.4.4.1p5. 3343 3344 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3345 // be an unsigned int. 3346 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3347 3348 // Check from smallest to largest, picking the smallest type we can. 3349 unsigned Width = 0; 3350 3351 // Microsoft specific integer suffixes are explicitly sized. 3352 if (Literal.MicrosoftInteger) { 3353 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3354 Width = 8; 3355 Ty = Context.CharTy; 3356 } else { 3357 Width = Literal.MicrosoftInteger; 3358 Ty = Context.getIntTypeForBitwidth(Width, 3359 /*Signed=*/!Literal.isUnsigned); 3360 } 3361 } 3362 3363 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3364 // Are int/unsigned possibilities? 3365 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3366 3367 // Does it fit in a unsigned int? 3368 if (ResultVal.isIntN(IntSize)) { 3369 // Does it fit in a signed int? 3370 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3371 Ty = Context.IntTy; 3372 else if (AllowUnsigned) 3373 Ty = Context.UnsignedIntTy; 3374 Width = IntSize; 3375 } 3376 } 3377 3378 // Are long/unsigned long possibilities? 3379 if (Ty.isNull() && !Literal.isLongLong) { 3380 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3381 3382 // Does it fit in a unsigned long? 3383 if (ResultVal.isIntN(LongSize)) { 3384 // Does it fit in a signed long? 3385 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3386 Ty = Context.LongTy; 3387 else if (AllowUnsigned) 3388 Ty = Context.UnsignedLongTy; 3389 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3390 // is compatible. 3391 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3392 const unsigned LongLongSize = 3393 Context.getTargetInfo().getLongLongWidth(); 3394 Diag(Tok.getLocation(), 3395 getLangOpts().CPlusPlus 3396 ? Literal.isLong 3397 ? diag::warn_old_implicitly_unsigned_long_cxx 3398 : /*C++98 UB*/ diag:: 3399 ext_old_implicitly_unsigned_long_cxx 3400 : diag::warn_old_implicitly_unsigned_long) 3401 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3402 : /*will be ill-formed*/ 1); 3403 Ty = Context.UnsignedLongTy; 3404 } 3405 Width = LongSize; 3406 } 3407 } 3408 3409 // Check long long if needed. 3410 if (Ty.isNull()) { 3411 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3412 3413 // Does it fit in a unsigned long long? 3414 if (ResultVal.isIntN(LongLongSize)) { 3415 // Does it fit in a signed long long? 3416 // To be compatible with MSVC, hex integer literals ending with the 3417 // LL or i64 suffix are always signed in Microsoft mode. 3418 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3419 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3420 Ty = Context.LongLongTy; 3421 else if (AllowUnsigned) 3422 Ty = Context.UnsignedLongLongTy; 3423 Width = LongLongSize; 3424 } 3425 } 3426 3427 // If we still couldn't decide a type, we probably have something that 3428 // does not fit in a signed long long, but has no U suffix. 3429 if (Ty.isNull()) { 3430 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3431 Ty = Context.UnsignedLongLongTy; 3432 Width = Context.getTargetInfo().getLongLongWidth(); 3433 } 3434 3435 if (ResultVal.getBitWidth() != Width) 3436 ResultVal = ResultVal.trunc(Width); 3437 } 3438 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3439 } 3440 3441 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3442 if (Literal.isImaginary) 3443 Res = new (Context) ImaginaryLiteral(Res, 3444 Context.getComplexType(Res->getType())); 3445 3446 return Res; 3447 } 3448 3449 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3450 assert(E && "ActOnParenExpr() missing expr"); 3451 return new (Context) ParenExpr(L, R, E); 3452 } 3453 3454 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3455 SourceLocation Loc, 3456 SourceRange ArgRange) { 3457 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3458 // scalar or vector data type argument..." 3459 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3460 // type (C99 6.2.5p18) or void. 3461 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3462 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3463 << T << ArgRange; 3464 return true; 3465 } 3466 3467 assert((T->isVoidType() || !T->isIncompleteType()) && 3468 "Scalar types should always be complete"); 3469 return false; 3470 } 3471 3472 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3473 SourceLocation Loc, 3474 SourceRange ArgRange, 3475 UnaryExprOrTypeTrait TraitKind) { 3476 // Invalid types must be hard errors for SFINAE in C++. 3477 if (S.LangOpts.CPlusPlus) 3478 return true; 3479 3480 // C99 6.5.3.4p1: 3481 if (T->isFunctionType() && 3482 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3483 // sizeof(function)/alignof(function) is allowed as an extension. 3484 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3485 << TraitKind << ArgRange; 3486 return false; 3487 } 3488 3489 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3490 // this is an error (OpenCL v1.1 s6.3.k) 3491 if (T->isVoidType()) { 3492 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3493 : diag::ext_sizeof_alignof_void_type; 3494 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3495 return false; 3496 } 3497 3498 return true; 3499 } 3500 3501 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3502 SourceLocation Loc, 3503 SourceRange ArgRange, 3504 UnaryExprOrTypeTrait TraitKind) { 3505 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3506 // runtime doesn't allow it. 3507 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3508 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3509 << T << (TraitKind == UETT_SizeOf) 3510 << ArgRange; 3511 return true; 3512 } 3513 3514 return false; 3515 } 3516 3517 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3518 /// pointer type is equal to T) and emit a warning if it is. 3519 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3520 Expr *E) { 3521 // Don't warn if the operation changed the type. 3522 if (T != E->getType()) 3523 return; 3524 3525 // Now look for array decays. 3526 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3527 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3528 return; 3529 3530 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3531 << ICE->getType() 3532 << ICE->getSubExpr()->getType(); 3533 } 3534 3535 /// \brief Check the constraints on expression operands to unary type expression 3536 /// and type traits. 3537 /// 3538 /// Completes any types necessary and validates the constraints on the operand 3539 /// expression. The logic mostly mirrors the type-based overload, but may modify 3540 /// the expression as it completes the type for that expression through template 3541 /// instantiation, etc. 3542 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3543 UnaryExprOrTypeTrait ExprKind) { 3544 QualType ExprTy = E->getType(); 3545 assert(!ExprTy->isReferenceType()); 3546 3547 if (ExprKind == UETT_VecStep) 3548 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3549 E->getSourceRange()); 3550 3551 // Whitelist some types as extensions 3552 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3553 E->getSourceRange(), ExprKind)) 3554 return false; 3555 3556 // 'alignof' applied to an expression only requires the base element type of 3557 // the expression to be complete. 'sizeof' requires the expression's type to 3558 // be complete (and will attempt to complete it if it's an array of unknown 3559 // bound). 3560 if (ExprKind == UETT_AlignOf) { 3561 if (RequireCompleteType(E->getExprLoc(), 3562 Context.getBaseElementType(E->getType()), 3563 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3564 E->getSourceRange())) 3565 return true; 3566 } else { 3567 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3568 ExprKind, E->getSourceRange())) 3569 return true; 3570 } 3571 3572 // Completing the expression's type may have changed it. 3573 ExprTy = E->getType(); 3574 assert(!ExprTy->isReferenceType()); 3575 3576 if (ExprTy->isFunctionType()) { 3577 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3578 << ExprKind << E->getSourceRange(); 3579 return true; 3580 } 3581 3582 // The operand for sizeof and alignof is in an unevaluated expression context, 3583 // so side effects could result in unintended consequences. 3584 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3585 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3586 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3587 3588 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3589 E->getSourceRange(), ExprKind)) 3590 return true; 3591 3592 if (ExprKind == UETT_SizeOf) { 3593 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3594 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3595 QualType OType = PVD->getOriginalType(); 3596 QualType Type = PVD->getType(); 3597 if (Type->isPointerType() && OType->isArrayType()) { 3598 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3599 << Type << OType; 3600 Diag(PVD->getLocation(), diag::note_declared_at); 3601 } 3602 } 3603 } 3604 3605 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3606 // decays into a pointer and returns an unintended result. This is most 3607 // likely a typo for "sizeof(array) op x". 3608 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3609 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3610 BO->getLHS()); 3611 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3612 BO->getRHS()); 3613 } 3614 } 3615 3616 return false; 3617 } 3618 3619 /// \brief Check the constraints on operands to unary expression and type 3620 /// traits. 3621 /// 3622 /// This will complete any types necessary, and validate the various constraints 3623 /// on those operands. 3624 /// 3625 /// The UsualUnaryConversions() function is *not* called by this routine. 3626 /// C99 6.3.2.1p[2-4] all state: 3627 /// Except when it is the operand of the sizeof operator ... 3628 /// 3629 /// C++ [expr.sizeof]p4 3630 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3631 /// standard conversions are not applied to the operand of sizeof. 3632 /// 3633 /// This policy is followed for all of the unary trait expressions. 3634 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3635 SourceLocation OpLoc, 3636 SourceRange ExprRange, 3637 UnaryExprOrTypeTrait ExprKind) { 3638 if (ExprType->isDependentType()) 3639 return false; 3640 3641 // C++ [expr.sizeof]p2: 3642 // When applied to a reference or a reference type, the result 3643 // is the size of the referenced type. 3644 // C++11 [expr.alignof]p3: 3645 // When alignof is applied to a reference type, the result 3646 // shall be the alignment of the referenced type. 3647 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3648 ExprType = Ref->getPointeeType(); 3649 3650 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3651 // When alignof or _Alignof is applied to an array type, the result 3652 // is the alignment of the element type. 3653 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3654 ExprType = Context.getBaseElementType(ExprType); 3655 3656 if (ExprKind == UETT_VecStep) 3657 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3658 3659 // Whitelist some types as extensions 3660 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3661 ExprKind)) 3662 return false; 3663 3664 if (RequireCompleteType(OpLoc, ExprType, 3665 diag::err_sizeof_alignof_incomplete_type, 3666 ExprKind, ExprRange)) 3667 return true; 3668 3669 if (ExprType->isFunctionType()) { 3670 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3671 << ExprKind << ExprRange; 3672 return true; 3673 } 3674 3675 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3676 ExprKind)) 3677 return true; 3678 3679 return false; 3680 } 3681 3682 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3683 E = E->IgnoreParens(); 3684 3685 // Cannot know anything else if the expression is dependent. 3686 if (E->isTypeDependent()) 3687 return false; 3688 3689 if (E->getObjectKind() == OK_BitField) { 3690 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3691 << 1 << E->getSourceRange(); 3692 return true; 3693 } 3694 3695 ValueDecl *D = nullptr; 3696 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3697 D = DRE->getDecl(); 3698 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3699 D = ME->getMemberDecl(); 3700 } 3701 3702 // If it's a field, require the containing struct to have a 3703 // complete definition so that we can compute the layout. 3704 // 3705 // This can happen in C++11 onwards, either by naming the member 3706 // in a way that is not transformed into a member access expression 3707 // (in an unevaluated operand, for instance), or by naming the member 3708 // in a trailing-return-type. 3709 // 3710 // For the record, since __alignof__ on expressions is a GCC 3711 // extension, GCC seems to permit this but always gives the 3712 // nonsensical answer 0. 3713 // 3714 // We don't really need the layout here --- we could instead just 3715 // directly check for all the appropriate alignment-lowing 3716 // attributes --- but that would require duplicating a lot of 3717 // logic that just isn't worth duplicating for such a marginal 3718 // use-case. 3719 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3720 // Fast path this check, since we at least know the record has a 3721 // definition if we can find a member of it. 3722 if (!FD->getParent()->isCompleteDefinition()) { 3723 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3724 << E->getSourceRange(); 3725 return true; 3726 } 3727 3728 // Otherwise, if it's a field, and the field doesn't have 3729 // reference type, then it must have a complete type (or be a 3730 // flexible array member, which we explicitly want to 3731 // white-list anyway), which makes the following checks trivial. 3732 if (!FD->getType()->isReferenceType()) 3733 return false; 3734 } 3735 3736 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3737 } 3738 3739 bool Sema::CheckVecStepExpr(Expr *E) { 3740 E = E->IgnoreParens(); 3741 3742 // Cannot know anything else if the expression is dependent. 3743 if (E->isTypeDependent()) 3744 return false; 3745 3746 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3747 } 3748 3749 /// \brief Build a sizeof or alignof expression given a type operand. 3750 ExprResult 3751 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3752 SourceLocation OpLoc, 3753 UnaryExprOrTypeTrait ExprKind, 3754 SourceRange R) { 3755 if (!TInfo) 3756 return ExprError(); 3757 3758 QualType T = TInfo->getType(); 3759 3760 if (!T->isDependentType() && 3761 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3762 return ExprError(); 3763 3764 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3765 return new (Context) UnaryExprOrTypeTraitExpr( 3766 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3767 } 3768 3769 /// \brief Build a sizeof or alignof expression given an expression 3770 /// operand. 3771 ExprResult 3772 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3773 UnaryExprOrTypeTrait ExprKind) { 3774 ExprResult PE = CheckPlaceholderExpr(E); 3775 if (PE.isInvalid()) 3776 return ExprError(); 3777 3778 E = PE.get(); 3779 3780 // Verify that the operand is valid. 3781 bool isInvalid = false; 3782 if (E->isTypeDependent()) { 3783 // Delay type-checking for type-dependent expressions. 3784 } else if (ExprKind == UETT_AlignOf) { 3785 isInvalid = CheckAlignOfExpr(*this, E); 3786 } else if (ExprKind == UETT_VecStep) { 3787 isInvalid = CheckVecStepExpr(E); 3788 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3789 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3790 isInvalid = true; 3791 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3792 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3793 isInvalid = true; 3794 } else { 3795 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3796 } 3797 3798 if (isInvalid) 3799 return ExprError(); 3800 3801 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3802 PE = TransformToPotentiallyEvaluated(E); 3803 if (PE.isInvalid()) return ExprError(); 3804 E = PE.get(); 3805 } 3806 3807 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3808 return new (Context) UnaryExprOrTypeTraitExpr( 3809 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3810 } 3811 3812 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3813 /// expr and the same for @c alignof and @c __alignof 3814 /// Note that the ArgRange is invalid if isType is false. 3815 ExprResult 3816 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3817 UnaryExprOrTypeTrait ExprKind, bool IsType, 3818 void *TyOrEx, SourceRange ArgRange) { 3819 // If error parsing type, ignore. 3820 if (!TyOrEx) return ExprError(); 3821 3822 if (IsType) { 3823 TypeSourceInfo *TInfo; 3824 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3825 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3826 } 3827 3828 Expr *ArgEx = (Expr *)TyOrEx; 3829 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3830 return Result; 3831 } 3832 3833 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3834 bool IsReal) { 3835 if (V.get()->isTypeDependent()) 3836 return S.Context.DependentTy; 3837 3838 // _Real and _Imag are only l-values for normal l-values. 3839 if (V.get()->getObjectKind() != OK_Ordinary) { 3840 V = S.DefaultLvalueConversion(V.get()); 3841 if (V.isInvalid()) 3842 return QualType(); 3843 } 3844 3845 // These operators return the element type of a complex type. 3846 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3847 return CT->getElementType(); 3848 3849 // Otherwise they pass through real integer and floating point types here. 3850 if (V.get()->getType()->isArithmeticType()) 3851 return V.get()->getType(); 3852 3853 // Test for placeholders. 3854 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3855 if (PR.isInvalid()) return QualType(); 3856 if (PR.get() != V.get()) { 3857 V = PR; 3858 return CheckRealImagOperand(S, V, Loc, IsReal); 3859 } 3860 3861 // Reject anything else. 3862 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3863 << (IsReal ? "__real" : "__imag"); 3864 return QualType(); 3865 } 3866 3867 3868 3869 ExprResult 3870 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3871 tok::TokenKind Kind, Expr *Input) { 3872 UnaryOperatorKind Opc; 3873 switch (Kind) { 3874 default: llvm_unreachable("Unknown unary op!"); 3875 case tok::plusplus: Opc = UO_PostInc; break; 3876 case tok::minusminus: Opc = UO_PostDec; break; 3877 } 3878 3879 // Since this might is a postfix expression, get rid of ParenListExprs. 3880 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3881 if (Result.isInvalid()) return ExprError(); 3882 Input = Result.get(); 3883 3884 return BuildUnaryOp(S, OpLoc, Opc, Input); 3885 } 3886 3887 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3888 /// 3889 /// \return true on error 3890 static bool checkArithmeticOnObjCPointer(Sema &S, 3891 SourceLocation opLoc, 3892 Expr *op) { 3893 assert(op->getType()->isObjCObjectPointerType()); 3894 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3895 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3896 return false; 3897 3898 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3899 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3900 << op->getSourceRange(); 3901 return true; 3902 } 3903 3904 ExprResult 3905 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3906 Expr *idx, SourceLocation rbLoc) { 3907 if (base && !base->getType().isNull() && 3908 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 3909 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 3910 /*Length=*/nullptr, rbLoc); 3911 3912 // Since this might be a postfix expression, get rid of ParenListExprs. 3913 if (isa<ParenListExpr>(base)) { 3914 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3915 if (result.isInvalid()) return ExprError(); 3916 base = result.get(); 3917 } 3918 3919 // Handle any non-overload placeholder types in the base and index 3920 // expressions. We can't handle overloads here because the other 3921 // operand might be an overloadable type, in which case the overload 3922 // resolution for the operator overload should get the first crack 3923 // at the overload. 3924 if (base->getType()->isNonOverloadPlaceholderType()) { 3925 ExprResult result = CheckPlaceholderExpr(base); 3926 if (result.isInvalid()) return ExprError(); 3927 base = result.get(); 3928 } 3929 if (idx->getType()->isNonOverloadPlaceholderType()) { 3930 ExprResult result = CheckPlaceholderExpr(idx); 3931 if (result.isInvalid()) return ExprError(); 3932 idx = result.get(); 3933 } 3934 3935 // Build an unanalyzed expression if either operand is type-dependent. 3936 if (getLangOpts().CPlusPlus && 3937 (base->isTypeDependent() || idx->isTypeDependent())) { 3938 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3939 VK_LValue, OK_Ordinary, rbLoc); 3940 } 3941 3942 // Use C++ overloaded-operator rules if either operand has record 3943 // type. The spec says to do this if either type is *overloadable*, 3944 // but enum types can't declare subscript operators or conversion 3945 // operators, so there's nothing interesting for overload resolution 3946 // to do if there aren't any record types involved. 3947 // 3948 // ObjC pointers have their own subscripting logic that is not tied 3949 // to overload resolution and so should not take this path. 3950 if (getLangOpts().CPlusPlus && 3951 (base->getType()->isRecordType() || 3952 (!base->getType()->isObjCObjectPointerType() && 3953 idx->getType()->isRecordType()))) { 3954 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3955 } 3956 3957 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3958 } 3959 3960 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 3961 Expr *LowerBound, 3962 SourceLocation ColonLoc, Expr *Length, 3963 SourceLocation RBLoc) { 3964 if (Base->getType()->isPlaceholderType() && 3965 !Base->getType()->isSpecificPlaceholderType( 3966 BuiltinType::OMPArraySection)) { 3967 ExprResult Result = CheckPlaceholderExpr(Base); 3968 if (Result.isInvalid()) 3969 return ExprError(); 3970 Base = Result.get(); 3971 } 3972 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 3973 ExprResult Result = CheckPlaceholderExpr(LowerBound); 3974 if (Result.isInvalid()) 3975 return ExprError(); 3976 LowerBound = Result.get(); 3977 } 3978 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 3979 ExprResult Result = CheckPlaceholderExpr(Length); 3980 if (Result.isInvalid()) 3981 return ExprError(); 3982 Length = Result.get(); 3983 } 3984 3985 // Build an unanalyzed expression if either operand is type-dependent. 3986 if (Base->isTypeDependent() || 3987 (LowerBound && 3988 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 3989 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 3990 return new (Context) 3991 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 3992 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 3993 } 3994 3995 // Perform default conversions. 3996 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 3997 QualType ResultTy; 3998 if (OriginalTy->isAnyPointerType()) { 3999 ResultTy = OriginalTy->getPointeeType(); 4000 } else if (OriginalTy->isArrayType()) { 4001 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4002 } else { 4003 return ExprError( 4004 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4005 << Base->getSourceRange()); 4006 } 4007 // C99 6.5.2.1p1 4008 if (LowerBound) { 4009 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4010 LowerBound); 4011 if (Res.isInvalid()) 4012 return ExprError(Diag(LowerBound->getExprLoc(), 4013 diag::err_omp_typecheck_section_not_integer) 4014 << 0 << LowerBound->getSourceRange()); 4015 LowerBound = Res.get(); 4016 4017 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4018 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4019 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4020 << 0 << LowerBound->getSourceRange(); 4021 } 4022 if (Length) { 4023 auto Res = 4024 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4025 if (Res.isInvalid()) 4026 return ExprError(Diag(Length->getExprLoc(), 4027 diag::err_omp_typecheck_section_not_integer) 4028 << 1 << Length->getSourceRange()); 4029 Length = Res.get(); 4030 4031 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4032 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4033 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4034 << 1 << Length->getSourceRange(); 4035 } 4036 4037 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4038 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4039 // type. Note that functions are not objects, and that (in C99 parlance) 4040 // incomplete types are not object types. 4041 if (ResultTy->isFunctionType()) { 4042 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4043 << ResultTy << Base->getSourceRange(); 4044 return ExprError(); 4045 } 4046 4047 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4048 diag::err_omp_section_incomplete_type, Base)) 4049 return ExprError(); 4050 4051 if (LowerBound) { 4052 llvm::APSInt LowerBoundValue; 4053 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4054 // OpenMP 4.0, [2.4 Array Sections] 4055 // The lower-bound and length must evaluate to non-negative integers. 4056 if (LowerBoundValue.isNegative()) { 4057 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4058 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4059 << LowerBound->getSourceRange(); 4060 return ExprError(); 4061 } 4062 } 4063 } 4064 4065 if (Length) { 4066 llvm::APSInt LengthValue; 4067 if (Length->EvaluateAsInt(LengthValue, Context)) { 4068 // OpenMP 4.0, [2.4 Array Sections] 4069 // The lower-bound and length must evaluate to non-negative integers. 4070 if (LengthValue.isNegative()) { 4071 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4072 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4073 << Length->getSourceRange(); 4074 return ExprError(); 4075 } 4076 } 4077 } else if (ColonLoc.isValid() && 4078 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4079 !OriginalTy->isVariableArrayType()))) { 4080 // OpenMP 4.0, [2.4 Array Sections] 4081 // When the size of the array dimension is not known, the length must be 4082 // specified explicitly. 4083 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4084 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4085 return ExprError(); 4086 } 4087 4088 return new (Context) 4089 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4090 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4091 } 4092 4093 ExprResult 4094 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4095 Expr *Idx, SourceLocation RLoc) { 4096 Expr *LHSExp = Base; 4097 Expr *RHSExp = Idx; 4098 4099 // Perform default conversions. 4100 if (!LHSExp->getType()->getAs<VectorType>()) { 4101 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4102 if (Result.isInvalid()) 4103 return ExprError(); 4104 LHSExp = Result.get(); 4105 } 4106 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4107 if (Result.isInvalid()) 4108 return ExprError(); 4109 RHSExp = Result.get(); 4110 4111 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4112 ExprValueKind VK = VK_LValue; 4113 ExprObjectKind OK = OK_Ordinary; 4114 4115 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4116 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4117 // in the subscript position. As a result, we need to derive the array base 4118 // and index from the expression types. 4119 Expr *BaseExpr, *IndexExpr; 4120 QualType ResultType; 4121 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4122 BaseExpr = LHSExp; 4123 IndexExpr = RHSExp; 4124 ResultType = Context.DependentTy; 4125 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4126 BaseExpr = LHSExp; 4127 IndexExpr = RHSExp; 4128 ResultType = PTy->getPointeeType(); 4129 } else if (const ObjCObjectPointerType *PTy = 4130 LHSTy->getAs<ObjCObjectPointerType>()) { 4131 BaseExpr = LHSExp; 4132 IndexExpr = RHSExp; 4133 4134 // Use custom logic if this should be the pseudo-object subscript 4135 // expression. 4136 if (!LangOpts.isSubscriptPointerArithmetic()) 4137 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4138 nullptr); 4139 4140 ResultType = PTy->getPointeeType(); 4141 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4142 // Handle the uncommon case of "123[Ptr]". 4143 BaseExpr = RHSExp; 4144 IndexExpr = LHSExp; 4145 ResultType = PTy->getPointeeType(); 4146 } else if (const ObjCObjectPointerType *PTy = 4147 RHSTy->getAs<ObjCObjectPointerType>()) { 4148 // Handle the uncommon case of "123[Ptr]". 4149 BaseExpr = RHSExp; 4150 IndexExpr = LHSExp; 4151 ResultType = PTy->getPointeeType(); 4152 if (!LangOpts.isSubscriptPointerArithmetic()) { 4153 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4154 << ResultType << BaseExpr->getSourceRange(); 4155 return ExprError(); 4156 } 4157 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4158 BaseExpr = LHSExp; // vectors: V[123] 4159 IndexExpr = RHSExp; 4160 VK = LHSExp->getValueKind(); 4161 if (VK != VK_RValue) 4162 OK = OK_VectorComponent; 4163 4164 // FIXME: need to deal with const... 4165 ResultType = VTy->getElementType(); 4166 } else if (LHSTy->isArrayType()) { 4167 // If we see an array that wasn't promoted by 4168 // DefaultFunctionArrayLvalueConversion, it must be an array that 4169 // wasn't promoted because of the C90 rule that doesn't 4170 // allow promoting non-lvalue arrays. Warn, then 4171 // force the promotion here. 4172 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4173 LHSExp->getSourceRange(); 4174 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4175 CK_ArrayToPointerDecay).get(); 4176 LHSTy = LHSExp->getType(); 4177 4178 BaseExpr = LHSExp; 4179 IndexExpr = RHSExp; 4180 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4181 } else if (RHSTy->isArrayType()) { 4182 // Same as previous, except for 123[f().a] case 4183 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4184 RHSExp->getSourceRange(); 4185 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4186 CK_ArrayToPointerDecay).get(); 4187 RHSTy = RHSExp->getType(); 4188 4189 BaseExpr = RHSExp; 4190 IndexExpr = LHSExp; 4191 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4192 } else { 4193 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4194 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4195 } 4196 // C99 6.5.2.1p1 4197 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4198 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4199 << IndexExpr->getSourceRange()); 4200 4201 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4202 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4203 && !IndexExpr->isTypeDependent()) 4204 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4205 4206 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4207 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4208 // type. Note that Functions are not objects, and that (in C99 parlance) 4209 // incomplete types are not object types. 4210 if (ResultType->isFunctionType()) { 4211 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4212 << ResultType << BaseExpr->getSourceRange(); 4213 return ExprError(); 4214 } 4215 4216 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4217 // GNU extension: subscripting on pointer to void 4218 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4219 << BaseExpr->getSourceRange(); 4220 4221 // C forbids expressions of unqualified void type from being l-values. 4222 // See IsCForbiddenLValueType. 4223 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4224 } else if (!ResultType->isDependentType() && 4225 RequireCompleteType(LLoc, ResultType, 4226 diag::err_subscript_incomplete_type, BaseExpr)) 4227 return ExprError(); 4228 4229 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4230 !ResultType.isCForbiddenLValueType()); 4231 4232 return new (Context) 4233 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4234 } 4235 4236 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4237 FunctionDecl *FD, 4238 ParmVarDecl *Param) { 4239 if (Param->hasUnparsedDefaultArg()) { 4240 Diag(CallLoc, 4241 diag::err_use_of_default_argument_to_function_declared_later) << 4242 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4243 Diag(UnparsedDefaultArgLocs[Param], 4244 diag::note_default_argument_declared_here); 4245 return ExprError(); 4246 } 4247 4248 if (Param->hasUninstantiatedDefaultArg()) { 4249 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4250 4251 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4252 Param); 4253 4254 // Instantiate the expression. 4255 MultiLevelTemplateArgumentList MutiLevelArgList 4256 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4257 4258 InstantiatingTemplate Inst(*this, CallLoc, Param, 4259 MutiLevelArgList.getInnermost()); 4260 if (Inst.isInvalid()) 4261 return ExprError(); 4262 4263 ExprResult Result; 4264 { 4265 // C++ [dcl.fct.default]p5: 4266 // The names in the [default argument] expression are bound, and 4267 // the semantic constraints are checked, at the point where the 4268 // default argument expression appears. 4269 ContextRAII SavedContext(*this, FD); 4270 LocalInstantiationScope Local(*this); 4271 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4272 } 4273 if (Result.isInvalid()) 4274 return ExprError(); 4275 4276 // Check the expression as an initializer for the parameter. 4277 InitializedEntity Entity 4278 = InitializedEntity::InitializeParameter(Context, Param); 4279 InitializationKind Kind 4280 = InitializationKind::CreateCopy(Param->getLocation(), 4281 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4282 Expr *ResultE = Result.getAs<Expr>(); 4283 4284 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4285 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4286 if (Result.isInvalid()) 4287 return ExprError(); 4288 4289 Expr *Arg = Result.getAs<Expr>(); 4290 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4291 // Build the default argument expression. 4292 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4293 } 4294 4295 // If the default expression creates temporaries, we need to 4296 // push them to the current stack of expression temporaries so they'll 4297 // be properly destroyed. 4298 // FIXME: We should really be rebuilding the default argument with new 4299 // bound temporaries; see the comment in PR5810. 4300 // We don't need to do that with block decls, though, because 4301 // blocks in default argument expression can never capture anything. 4302 if (isa<ExprWithCleanups>(Param->getInit())) { 4303 // Set the "needs cleanups" bit regardless of whether there are 4304 // any explicit objects. 4305 ExprNeedsCleanups = true; 4306 4307 // Append all the objects to the cleanup list. Right now, this 4308 // should always be a no-op, because blocks in default argument 4309 // expressions should never be able to capture anything. 4310 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4311 "default argument expression has capturing blocks?"); 4312 } 4313 4314 // We already type-checked the argument, so we know it works. 4315 // Just mark all of the declarations in this potentially-evaluated expression 4316 // as being "referenced". 4317 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4318 /*SkipLocalVariables=*/true); 4319 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4320 } 4321 4322 4323 Sema::VariadicCallType 4324 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4325 Expr *Fn) { 4326 if (Proto && Proto->isVariadic()) { 4327 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4328 return VariadicConstructor; 4329 else if (Fn && Fn->getType()->isBlockPointerType()) 4330 return VariadicBlock; 4331 else if (FDecl) { 4332 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4333 if (Method->isInstance()) 4334 return VariadicMethod; 4335 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4336 return VariadicMethod; 4337 return VariadicFunction; 4338 } 4339 return VariadicDoesNotApply; 4340 } 4341 4342 namespace { 4343 class FunctionCallCCC : public FunctionCallFilterCCC { 4344 public: 4345 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4346 unsigned NumArgs, MemberExpr *ME) 4347 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4348 FunctionName(FuncName) {} 4349 4350 bool ValidateCandidate(const TypoCorrection &candidate) override { 4351 if (!candidate.getCorrectionSpecifier() || 4352 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4353 return false; 4354 } 4355 4356 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4357 } 4358 4359 private: 4360 const IdentifierInfo *const FunctionName; 4361 }; 4362 } 4363 4364 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4365 FunctionDecl *FDecl, 4366 ArrayRef<Expr *> Args) { 4367 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4368 DeclarationName FuncName = FDecl->getDeclName(); 4369 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4370 4371 if (TypoCorrection Corrected = S.CorrectTypo( 4372 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4373 S.getScopeForContext(S.CurContext), nullptr, 4374 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4375 Args.size(), ME), 4376 Sema::CTK_ErrorRecovery)) { 4377 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4378 if (Corrected.isOverloaded()) { 4379 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4380 OverloadCandidateSet::iterator Best; 4381 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4382 CDEnd = Corrected.end(); 4383 CD != CDEnd; ++CD) { 4384 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4385 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4386 OCS); 4387 } 4388 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4389 case OR_Success: 4390 ND = Best->Function; 4391 Corrected.setCorrectionDecl(ND); 4392 break; 4393 default: 4394 break; 4395 } 4396 } 4397 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4398 return Corrected; 4399 } 4400 } 4401 } 4402 return TypoCorrection(); 4403 } 4404 4405 /// ConvertArgumentsForCall - Converts the arguments specified in 4406 /// Args/NumArgs to the parameter types of the function FDecl with 4407 /// function prototype Proto. Call is the call expression itself, and 4408 /// Fn is the function expression. For a C++ member function, this 4409 /// routine does not attempt to convert the object argument. Returns 4410 /// true if the call is ill-formed. 4411 bool 4412 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4413 FunctionDecl *FDecl, 4414 const FunctionProtoType *Proto, 4415 ArrayRef<Expr *> Args, 4416 SourceLocation RParenLoc, 4417 bool IsExecConfig) { 4418 // Bail out early if calling a builtin with custom typechecking. 4419 if (FDecl) 4420 if (unsigned ID = FDecl->getBuiltinID()) 4421 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4422 return false; 4423 4424 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4425 // assignment, to the types of the corresponding parameter, ... 4426 unsigned NumParams = Proto->getNumParams(); 4427 bool Invalid = false; 4428 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4429 unsigned FnKind = Fn->getType()->isBlockPointerType() 4430 ? 1 /* block */ 4431 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4432 : 0 /* function */); 4433 4434 // If too few arguments are available (and we don't have default 4435 // arguments for the remaining parameters), don't make the call. 4436 if (Args.size() < NumParams) { 4437 if (Args.size() < MinArgs) { 4438 TypoCorrection TC; 4439 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4440 unsigned diag_id = 4441 MinArgs == NumParams && !Proto->isVariadic() 4442 ? diag::err_typecheck_call_too_few_args_suggest 4443 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4444 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4445 << static_cast<unsigned>(Args.size()) 4446 << TC.getCorrectionRange()); 4447 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4448 Diag(RParenLoc, 4449 MinArgs == NumParams && !Proto->isVariadic() 4450 ? diag::err_typecheck_call_too_few_args_one 4451 : diag::err_typecheck_call_too_few_args_at_least_one) 4452 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4453 else 4454 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4455 ? diag::err_typecheck_call_too_few_args 4456 : diag::err_typecheck_call_too_few_args_at_least) 4457 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4458 << Fn->getSourceRange(); 4459 4460 // Emit the location of the prototype. 4461 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4462 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4463 << FDecl; 4464 4465 return true; 4466 } 4467 Call->setNumArgs(Context, NumParams); 4468 } 4469 4470 // If too many are passed and not variadic, error on the extras and drop 4471 // them. 4472 if (Args.size() > NumParams) { 4473 if (!Proto->isVariadic()) { 4474 TypoCorrection TC; 4475 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4476 unsigned diag_id = 4477 MinArgs == NumParams && !Proto->isVariadic() 4478 ? diag::err_typecheck_call_too_many_args_suggest 4479 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4480 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4481 << static_cast<unsigned>(Args.size()) 4482 << TC.getCorrectionRange()); 4483 } else if (NumParams == 1 && FDecl && 4484 FDecl->getParamDecl(0)->getDeclName()) 4485 Diag(Args[NumParams]->getLocStart(), 4486 MinArgs == NumParams 4487 ? diag::err_typecheck_call_too_many_args_one 4488 : diag::err_typecheck_call_too_many_args_at_most_one) 4489 << FnKind << FDecl->getParamDecl(0) 4490 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4491 << SourceRange(Args[NumParams]->getLocStart(), 4492 Args.back()->getLocEnd()); 4493 else 4494 Diag(Args[NumParams]->getLocStart(), 4495 MinArgs == NumParams 4496 ? diag::err_typecheck_call_too_many_args 4497 : diag::err_typecheck_call_too_many_args_at_most) 4498 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4499 << Fn->getSourceRange() 4500 << SourceRange(Args[NumParams]->getLocStart(), 4501 Args.back()->getLocEnd()); 4502 4503 // Emit the location of the prototype. 4504 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4505 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4506 << FDecl; 4507 4508 // This deletes the extra arguments. 4509 Call->setNumArgs(Context, NumParams); 4510 return true; 4511 } 4512 } 4513 SmallVector<Expr *, 8> AllArgs; 4514 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4515 4516 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4517 Proto, 0, Args, AllArgs, CallType); 4518 if (Invalid) 4519 return true; 4520 unsigned TotalNumArgs = AllArgs.size(); 4521 for (unsigned i = 0; i < TotalNumArgs; ++i) 4522 Call->setArg(i, AllArgs[i]); 4523 4524 return false; 4525 } 4526 4527 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4528 const FunctionProtoType *Proto, 4529 unsigned FirstParam, ArrayRef<Expr *> Args, 4530 SmallVectorImpl<Expr *> &AllArgs, 4531 VariadicCallType CallType, bool AllowExplicit, 4532 bool IsListInitialization) { 4533 unsigned NumParams = Proto->getNumParams(); 4534 bool Invalid = false; 4535 unsigned ArgIx = 0; 4536 // Continue to check argument types (even if we have too few/many args). 4537 for (unsigned i = FirstParam; i < NumParams; i++) { 4538 QualType ProtoArgType = Proto->getParamType(i); 4539 4540 Expr *Arg; 4541 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4542 if (ArgIx < Args.size()) { 4543 Arg = Args[ArgIx++]; 4544 4545 if (RequireCompleteType(Arg->getLocStart(), 4546 ProtoArgType, 4547 diag::err_call_incomplete_argument, Arg)) 4548 return true; 4549 4550 // Strip the unbridged-cast placeholder expression off, if applicable. 4551 bool CFAudited = false; 4552 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4553 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4554 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4555 Arg = stripARCUnbridgedCast(Arg); 4556 else if (getLangOpts().ObjCAutoRefCount && 4557 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4558 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4559 CFAudited = true; 4560 4561 InitializedEntity Entity = 4562 Param ? InitializedEntity::InitializeParameter(Context, Param, 4563 ProtoArgType) 4564 : InitializedEntity::InitializeParameter( 4565 Context, ProtoArgType, Proto->isParamConsumed(i)); 4566 4567 // Remember that parameter belongs to a CF audited API. 4568 if (CFAudited) 4569 Entity.setParameterCFAudited(); 4570 4571 ExprResult ArgE = PerformCopyInitialization( 4572 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4573 if (ArgE.isInvalid()) 4574 return true; 4575 4576 Arg = ArgE.getAs<Expr>(); 4577 } else { 4578 assert(Param && "can't use default arguments without a known callee"); 4579 4580 ExprResult ArgExpr = 4581 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4582 if (ArgExpr.isInvalid()) 4583 return true; 4584 4585 Arg = ArgExpr.getAs<Expr>(); 4586 } 4587 4588 // Check for array bounds violations for each argument to the call. This 4589 // check only triggers warnings when the argument isn't a more complex Expr 4590 // with its own checking, such as a BinaryOperator. 4591 CheckArrayAccess(Arg); 4592 4593 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4594 CheckStaticArrayArgument(CallLoc, Param, Arg); 4595 4596 AllArgs.push_back(Arg); 4597 } 4598 4599 // If this is a variadic call, handle args passed through "...". 4600 if (CallType != VariadicDoesNotApply) { 4601 // Assume that extern "C" functions with variadic arguments that 4602 // return __unknown_anytype aren't *really* variadic. 4603 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4604 FDecl->isExternC()) { 4605 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4606 QualType paramType; // ignored 4607 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4608 Invalid |= arg.isInvalid(); 4609 AllArgs.push_back(arg.get()); 4610 } 4611 4612 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4613 } else { 4614 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4615 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4616 FDecl); 4617 Invalid |= Arg.isInvalid(); 4618 AllArgs.push_back(Arg.get()); 4619 } 4620 } 4621 4622 // Check for array bounds violations. 4623 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4624 CheckArrayAccess(Args[i]); 4625 } 4626 return Invalid; 4627 } 4628 4629 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4630 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4631 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4632 TL = DTL.getOriginalLoc(); 4633 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4634 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4635 << ATL.getLocalSourceRange(); 4636 } 4637 4638 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4639 /// array parameter, check that it is non-null, and that if it is formed by 4640 /// array-to-pointer decay, the underlying array is sufficiently large. 4641 /// 4642 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4643 /// array type derivation, then for each call to the function, the value of the 4644 /// corresponding actual argument shall provide access to the first element of 4645 /// an array with at least as many elements as specified by the size expression. 4646 void 4647 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4648 ParmVarDecl *Param, 4649 const Expr *ArgExpr) { 4650 // Static array parameters are not supported in C++. 4651 if (!Param || getLangOpts().CPlusPlus) 4652 return; 4653 4654 QualType OrigTy = Param->getOriginalType(); 4655 4656 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4657 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4658 return; 4659 4660 if (ArgExpr->isNullPointerConstant(Context, 4661 Expr::NPC_NeverValueDependent)) { 4662 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4663 DiagnoseCalleeStaticArrayParam(*this, Param); 4664 return; 4665 } 4666 4667 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4668 if (!CAT) 4669 return; 4670 4671 const ConstantArrayType *ArgCAT = 4672 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4673 if (!ArgCAT) 4674 return; 4675 4676 if (ArgCAT->getSize().ult(CAT->getSize())) { 4677 Diag(CallLoc, diag::warn_static_array_too_small) 4678 << ArgExpr->getSourceRange() 4679 << (unsigned) ArgCAT->getSize().getZExtValue() 4680 << (unsigned) CAT->getSize().getZExtValue(); 4681 DiagnoseCalleeStaticArrayParam(*this, Param); 4682 } 4683 } 4684 4685 /// Given a function expression of unknown-any type, try to rebuild it 4686 /// to have a function type. 4687 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4688 4689 /// Is the given type a placeholder that we need to lower out 4690 /// immediately during argument processing? 4691 static bool isPlaceholderToRemoveAsArg(QualType type) { 4692 // Placeholders are never sugared. 4693 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4694 if (!placeholder) return false; 4695 4696 switch (placeholder->getKind()) { 4697 // Ignore all the non-placeholder types. 4698 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4699 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4700 #include "clang/AST/BuiltinTypes.def" 4701 return false; 4702 4703 // We cannot lower out overload sets; they might validly be resolved 4704 // by the call machinery. 4705 case BuiltinType::Overload: 4706 return false; 4707 4708 // Unbridged casts in ARC can be handled in some call positions and 4709 // should be left in place. 4710 case BuiltinType::ARCUnbridgedCast: 4711 return false; 4712 4713 // Pseudo-objects should be converted as soon as possible. 4714 case BuiltinType::PseudoObject: 4715 return true; 4716 4717 // The debugger mode could theoretically but currently does not try 4718 // to resolve unknown-typed arguments based on known parameter types. 4719 case BuiltinType::UnknownAny: 4720 return true; 4721 4722 // These are always invalid as call arguments and should be reported. 4723 case BuiltinType::BoundMember: 4724 case BuiltinType::BuiltinFn: 4725 case BuiltinType::OMPArraySection: 4726 return true; 4727 4728 } 4729 llvm_unreachable("bad builtin type kind"); 4730 } 4731 4732 /// Check an argument list for placeholders that we won't try to 4733 /// handle later. 4734 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4735 // Apply this processing to all the arguments at once instead of 4736 // dying at the first failure. 4737 bool hasInvalid = false; 4738 for (size_t i = 0, e = args.size(); i != e; i++) { 4739 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4740 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4741 if (result.isInvalid()) hasInvalid = true; 4742 else args[i] = result.get(); 4743 } else if (hasInvalid) { 4744 (void)S.CorrectDelayedTyposInExpr(args[i]); 4745 } 4746 } 4747 return hasInvalid; 4748 } 4749 4750 /// If a builtin function has a pointer argument with no explicit address 4751 /// space, than it should be able to accept a pointer to any address 4752 /// space as input. In order to do this, we need to replace the 4753 /// standard builtin declaration with one that uses the same address space 4754 /// as the call. 4755 /// 4756 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4757 /// it does not contain any pointer arguments without 4758 /// an address space qualifer. Otherwise the rewritten 4759 /// FunctionDecl is returned. 4760 /// TODO: Handle pointer return types. 4761 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4762 const FunctionDecl *FDecl, 4763 MultiExprArg ArgExprs) { 4764 4765 QualType DeclType = FDecl->getType(); 4766 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4767 4768 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4769 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4770 return nullptr; 4771 4772 bool NeedsNewDecl = false; 4773 unsigned i = 0; 4774 SmallVector<QualType, 8> OverloadParams; 4775 4776 for (QualType ParamType : FT->param_types()) { 4777 4778 // Convert array arguments to pointer to simplify type lookup. 4779 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4780 QualType ArgType = Arg->getType(); 4781 if (!ParamType->isPointerType() || 4782 ParamType.getQualifiers().hasAddressSpace() || 4783 !ArgType->isPointerType() || 4784 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4785 OverloadParams.push_back(ParamType); 4786 continue; 4787 } 4788 4789 NeedsNewDecl = true; 4790 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 4791 4792 QualType PointeeType = ParamType->getPointeeType(); 4793 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 4794 OverloadParams.push_back(Context.getPointerType(PointeeType)); 4795 } 4796 4797 if (!NeedsNewDecl) 4798 return nullptr; 4799 4800 FunctionProtoType::ExtProtoInfo EPI; 4801 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 4802 OverloadParams, EPI); 4803 DeclContext *Parent = Context.getTranslationUnitDecl(); 4804 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 4805 FDecl->getLocation(), 4806 FDecl->getLocation(), 4807 FDecl->getIdentifier(), 4808 OverloadTy, 4809 /*TInfo=*/nullptr, 4810 SC_Extern, false, 4811 /*hasPrototype=*/true); 4812 SmallVector<ParmVarDecl*, 16> Params; 4813 FT = cast<FunctionProtoType>(OverloadTy); 4814 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 4815 QualType ParamType = FT->getParamType(i); 4816 ParmVarDecl *Parm = 4817 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 4818 SourceLocation(), nullptr, ParamType, 4819 /*TInfo=*/nullptr, SC_None, nullptr); 4820 Parm->setScopeInfo(0, i); 4821 Params.push_back(Parm); 4822 } 4823 OverloadDecl->setParams(Params); 4824 return OverloadDecl; 4825 } 4826 4827 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4828 /// This provides the location of the left/right parens and a list of comma 4829 /// locations. 4830 ExprResult 4831 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4832 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4833 Expr *ExecConfig, bool IsExecConfig) { 4834 // Since this might be a postfix expression, get rid of ParenListExprs. 4835 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4836 if (Result.isInvalid()) return ExprError(); 4837 Fn = Result.get(); 4838 4839 if (checkArgsForPlaceholders(*this, ArgExprs)) 4840 return ExprError(); 4841 4842 if (getLangOpts().CPlusPlus) { 4843 // If this is a pseudo-destructor expression, build the call immediately. 4844 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4845 if (!ArgExprs.empty()) { 4846 // Pseudo-destructor calls should not have any arguments. 4847 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4848 << FixItHint::CreateRemoval( 4849 SourceRange(ArgExprs.front()->getLocStart(), 4850 ArgExprs.back()->getLocEnd())); 4851 } 4852 4853 return new (Context) 4854 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4855 } 4856 if (Fn->getType() == Context.PseudoObjectTy) { 4857 ExprResult result = CheckPlaceholderExpr(Fn); 4858 if (result.isInvalid()) return ExprError(); 4859 Fn = result.get(); 4860 } 4861 4862 // Determine whether this is a dependent call inside a C++ template, 4863 // in which case we won't do any semantic analysis now. 4864 // FIXME: Will need to cache the results of name lookup (including ADL) in 4865 // Fn. 4866 bool Dependent = false; 4867 if (Fn->isTypeDependent()) 4868 Dependent = true; 4869 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4870 Dependent = true; 4871 4872 if (Dependent) { 4873 if (ExecConfig) { 4874 return new (Context) CUDAKernelCallExpr( 4875 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4876 Context.DependentTy, VK_RValue, RParenLoc); 4877 } else { 4878 return new (Context) CallExpr( 4879 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4880 } 4881 } 4882 4883 // Determine whether this is a call to an object (C++ [over.call.object]). 4884 if (Fn->getType()->isRecordType()) 4885 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4886 RParenLoc); 4887 4888 if (Fn->getType() == Context.UnknownAnyTy) { 4889 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4890 if (result.isInvalid()) return ExprError(); 4891 Fn = result.get(); 4892 } 4893 4894 if (Fn->getType() == Context.BoundMemberTy) { 4895 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4896 } 4897 } 4898 4899 // Check for overloaded calls. This can happen even in C due to extensions. 4900 if (Fn->getType() == Context.OverloadTy) { 4901 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4902 4903 // We aren't supposed to apply this logic for if there's an '&' involved. 4904 if (!find.HasFormOfMemberPointer) { 4905 OverloadExpr *ovl = find.Expression; 4906 if (isa<UnresolvedLookupExpr>(ovl)) { 4907 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4908 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4909 RParenLoc, ExecConfig); 4910 } else { 4911 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4912 RParenLoc); 4913 } 4914 } 4915 } 4916 4917 // If we're directly calling a function, get the appropriate declaration. 4918 if (Fn->getType() == Context.UnknownAnyTy) { 4919 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4920 if (result.isInvalid()) return ExprError(); 4921 Fn = result.get(); 4922 } 4923 4924 Expr *NakedFn = Fn->IgnoreParens(); 4925 4926 NamedDecl *NDecl = nullptr; 4927 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4928 if (UnOp->getOpcode() == UO_AddrOf) 4929 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4930 4931 if (isa<DeclRefExpr>(NakedFn)) { 4932 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4933 4934 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 4935 if (FDecl && FDecl->getBuiltinID()) { 4936 // Rewrite the function decl for this builtin by replacing paramaters 4937 // with no explicit address space with the address space of the arguments 4938 // in ArgExprs. 4939 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 4940 NDecl = FDecl; 4941 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 4942 SourceLocation(), FDecl, false, 4943 SourceLocation(), FDecl->getType(), 4944 Fn->getValueKind(), FDecl); 4945 } 4946 } 4947 } else if (isa<MemberExpr>(NakedFn)) 4948 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4949 4950 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4951 if (FD->hasAttr<EnableIfAttr>()) { 4952 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4953 Diag(Fn->getLocStart(), 4954 isa<CXXMethodDecl>(FD) ? 4955 diag::err_ovl_no_viable_member_function_in_call : 4956 diag::err_ovl_no_viable_function_in_call) 4957 << FD << FD->getSourceRange(); 4958 Diag(FD->getLocation(), 4959 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4960 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4961 } 4962 } 4963 } 4964 4965 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4966 ExecConfig, IsExecConfig); 4967 } 4968 4969 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4970 /// 4971 /// __builtin_astype( value, dst type ) 4972 /// 4973 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4974 SourceLocation BuiltinLoc, 4975 SourceLocation RParenLoc) { 4976 ExprValueKind VK = VK_RValue; 4977 ExprObjectKind OK = OK_Ordinary; 4978 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4979 QualType SrcTy = E->getType(); 4980 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4981 return ExprError(Diag(BuiltinLoc, 4982 diag::err_invalid_astype_of_different_size) 4983 << DstTy 4984 << SrcTy 4985 << E->getSourceRange()); 4986 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4987 } 4988 4989 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4990 /// provided arguments. 4991 /// 4992 /// __builtin_convertvector( value, dst type ) 4993 /// 4994 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4995 SourceLocation BuiltinLoc, 4996 SourceLocation RParenLoc) { 4997 TypeSourceInfo *TInfo; 4998 GetTypeFromParser(ParsedDestTy, &TInfo); 4999 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5000 } 5001 5002 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5003 /// i.e. an expression not of \p OverloadTy. The expression should 5004 /// unary-convert to an expression of function-pointer or 5005 /// block-pointer type. 5006 /// 5007 /// \param NDecl the declaration being called, if available 5008 ExprResult 5009 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5010 SourceLocation LParenLoc, 5011 ArrayRef<Expr *> Args, 5012 SourceLocation RParenLoc, 5013 Expr *Config, bool IsExecConfig) { 5014 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5015 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5016 5017 // Promote the function operand. 5018 // We special-case function promotion here because we only allow promoting 5019 // builtin functions to function pointers in the callee of a call. 5020 ExprResult Result; 5021 if (BuiltinID && 5022 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5023 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5024 CK_BuiltinFnToFnPtr).get(); 5025 } else { 5026 Result = CallExprUnaryConversions(Fn); 5027 } 5028 if (Result.isInvalid()) 5029 return ExprError(); 5030 Fn = Result.get(); 5031 5032 // Make the call expr early, before semantic checks. This guarantees cleanup 5033 // of arguments and function on error. 5034 CallExpr *TheCall; 5035 if (Config) 5036 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5037 cast<CallExpr>(Config), Args, 5038 Context.BoolTy, VK_RValue, 5039 RParenLoc); 5040 else 5041 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5042 VK_RValue, RParenLoc); 5043 5044 if (!getLangOpts().CPlusPlus) { 5045 // C cannot always handle TypoExpr nodes in builtin calls and direct 5046 // function calls as their argument checking don't necessarily handle 5047 // dependent types properly, so make sure any TypoExprs have been 5048 // dealt with. 5049 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5050 if (!Result.isUsable()) return ExprError(); 5051 TheCall = dyn_cast<CallExpr>(Result.get()); 5052 if (!TheCall) return Result; 5053 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5054 } 5055 5056 // Bail out early if calling a builtin with custom typechecking. 5057 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5058 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5059 5060 retry: 5061 const FunctionType *FuncT; 5062 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5063 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5064 // have type pointer to function". 5065 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5066 if (!FuncT) 5067 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5068 << Fn->getType() << Fn->getSourceRange()); 5069 } else if (const BlockPointerType *BPT = 5070 Fn->getType()->getAs<BlockPointerType>()) { 5071 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5072 } else { 5073 // Handle calls to expressions of unknown-any type. 5074 if (Fn->getType() == Context.UnknownAnyTy) { 5075 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5076 if (rewrite.isInvalid()) return ExprError(); 5077 Fn = rewrite.get(); 5078 TheCall->setCallee(Fn); 5079 goto retry; 5080 } 5081 5082 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5083 << Fn->getType() << Fn->getSourceRange()); 5084 } 5085 5086 if (getLangOpts().CUDA) { 5087 if (Config) { 5088 // CUDA: Kernel calls must be to global functions 5089 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5090 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5091 << FDecl->getName() << Fn->getSourceRange()); 5092 5093 // CUDA: Kernel function must have 'void' return type 5094 if (!FuncT->getReturnType()->isVoidType()) 5095 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5096 << Fn->getType() << Fn->getSourceRange()); 5097 } else { 5098 // CUDA: Calls to global functions must be configured 5099 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5100 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5101 << FDecl->getName() << Fn->getSourceRange()); 5102 } 5103 } 5104 5105 // Check for a valid return type 5106 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5107 FDecl)) 5108 return ExprError(); 5109 5110 // We know the result type of the call, set it. 5111 TheCall->setType(FuncT->getCallResultType(Context)); 5112 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5113 5114 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5115 if (Proto) { 5116 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5117 IsExecConfig)) 5118 return ExprError(); 5119 } else { 5120 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5121 5122 if (FDecl) { 5123 // Check if we have too few/too many template arguments, based 5124 // on our knowledge of the function definition. 5125 const FunctionDecl *Def = nullptr; 5126 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5127 Proto = Def->getType()->getAs<FunctionProtoType>(); 5128 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5129 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5130 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5131 } 5132 5133 // If the function we're calling isn't a function prototype, but we have 5134 // a function prototype from a prior declaratiom, use that prototype. 5135 if (!FDecl->hasPrototype()) 5136 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5137 } 5138 5139 // Promote the arguments (C99 6.5.2.2p6). 5140 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5141 Expr *Arg = Args[i]; 5142 5143 if (Proto && i < Proto->getNumParams()) { 5144 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5145 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5146 ExprResult ArgE = 5147 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5148 if (ArgE.isInvalid()) 5149 return true; 5150 5151 Arg = ArgE.getAs<Expr>(); 5152 5153 } else { 5154 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5155 5156 if (ArgE.isInvalid()) 5157 return true; 5158 5159 Arg = ArgE.getAs<Expr>(); 5160 } 5161 5162 if (RequireCompleteType(Arg->getLocStart(), 5163 Arg->getType(), 5164 diag::err_call_incomplete_argument, Arg)) 5165 return ExprError(); 5166 5167 TheCall->setArg(i, Arg); 5168 } 5169 } 5170 5171 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5172 if (!Method->isStatic()) 5173 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5174 << Fn->getSourceRange()); 5175 5176 // Check for sentinels 5177 if (NDecl) 5178 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5179 5180 // Do special checking on direct calls to functions. 5181 if (FDecl) { 5182 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5183 return ExprError(); 5184 5185 if (BuiltinID) 5186 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5187 } else if (NDecl) { 5188 if (CheckPointerCall(NDecl, TheCall, Proto)) 5189 return ExprError(); 5190 } else { 5191 if (CheckOtherCall(TheCall, Proto)) 5192 return ExprError(); 5193 } 5194 5195 return MaybeBindToTemporary(TheCall); 5196 } 5197 5198 ExprResult 5199 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5200 SourceLocation RParenLoc, Expr *InitExpr) { 5201 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5202 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5203 5204 TypeSourceInfo *TInfo; 5205 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5206 if (!TInfo) 5207 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5208 5209 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5210 } 5211 5212 ExprResult 5213 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5214 SourceLocation RParenLoc, Expr *LiteralExpr) { 5215 QualType literalType = TInfo->getType(); 5216 5217 if (literalType->isArrayType()) { 5218 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5219 diag::err_illegal_decl_array_incomplete_type, 5220 SourceRange(LParenLoc, 5221 LiteralExpr->getSourceRange().getEnd()))) 5222 return ExprError(); 5223 if (literalType->isVariableArrayType()) 5224 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5225 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5226 } else if (!literalType->isDependentType() && 5227 RequireCompleteType(LParenLoc, literalType, 5228 diag::err_typecheck_decl_incomplete_type, 5229 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5230 return ExprError(); 5231 5232 InitializedEntity Entity 5233 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5234 InitializationKind Kind 5235 = InitializationKind::CreateCStyleCast(LParenLoc, 5236 SourceRange(LParenLoc, RParenLoc), 5237 /*InitList=*/true); 5238 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5239 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5240 &literalType); 5241 if (Result.isInvalid()) 5242 return ExprError(); 5243 LiteralExpr = Result.get(); 5244 5245 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5246 if (isFileScope && 5247 !LiteralExpr->isTypeDependent() && 5248 !LiteralExpr->isValueDependent() && 5249 !literalType->isDependentType()) { // 6.5.2.5p3 5250 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5251 return ExprError(); 5252 } 5253 5254 // In C, compound literals are l-values for some reason. 5255 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5256 5257 return MaybeBindToTemporary( 5258 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5259 VK, LiteralExpr, isFileScope)); 5260 } 5261 5262 ExprResult 5263 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5264 SourceLocation RBraceLoc) { 5265 // Immediately handle non-overload placeholders. Overloads can be 5266 // resolved contextually, but everything else here can't. 5267 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5268 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5269 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5270 5271 // Ignore failures; dropping the entire initializer list because 5272 // of one failure would be terrible for indexing/etc. 5273 if (result.isInvalid()) continue; 5274 5275 InitArgList[I] = result.get(); 5276 } 5277 } 5278 5279 // Semantic analysis for initializers is done by ActOnDeclarator() and 5280 // CheckInitializer() - it requires knowledge of the object being intialized. 5281 5282 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5283 RBraceLoc); 5284 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5285 return E; 5286 } 5287 5288 /// Do an explicit extend of the given block pointer if we're in ARC. 5289 void Sema::maybeExtendBlockObject(ExprResult &E) { 5290 assert(E.get()->getType()->isBlockPointerType()); 5291 assert(E.get()->isRValue()); 5292 5293 // Only do this in an r-value context. 5294 if (!getLangOpts().ObjCAutoRefCount) return; 5295 5296 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5297 CK_ARCExtendBlockObject, E.get(), 5298 /*base path*/ nullptr, VK_RValue); 5299 ExprNeedsCleanups = true; 5300 } 5301 5302 /// Prepare a conversion of the given expression to an ObjC object 5303 /// pointer type. 5304 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5305 QualType type = E.get()->getType(); 5306 if (type->isObjCObjectPointerType()) { 5307 return CK_BitCast; 5308 } else if (type->isBlockPointerType()) { 5309 maybeExtendBlockObject(E); 5310 return CK_BlockPointerToObjCPointerCast; 5311 } else { 5312 assert(type->isPointerType()); 5313 return CK_CPointerToObjCPointerCast; 5314 } 5315 } 5316 5317 /// Prepares for a scalar cast, performing all the necessary stages 5318 /// except the final cast and returning the kind required. 5319 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5320 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5321 // Also, callers should have filtered out the invalid cases with 5322 // pointers. Everything else should be possible. 5323 5324 QualType SrcTy = Src.get()->getType(); 5325 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5326 return CK_NoOp; 5327 5328 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5329 case Type::STK_MemberPointer: 5330 llvm_unreachable("member pointer type in C"); 5331 5332 case Type::STK_CPointer: 5333 case Type::STK_BlockPointer: 5334 case Type::STK_ObjCObjectPointer: 5335 switch (DestTy->getScalarTypeKind()) { 5336 case Type::STK_CPointer: { 5337 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5338 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5339 if (SrcAS != DestAS) 5340 return CK_AddressSpaceConversion; 5341 return CK_BitCast; 5342 } 5343 case Type::STK_BlockPointer: 5344 return (SrcKind == Type::STK_BlockPointer 5345 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5346 case Type::STK_ObjCObjectPointer: 5347 if (SrcKind == Type::STK_ObjCObjectPointer) 5348 return CK_BitCast; 5349 if (SrcKind == Type::STK_CPointer) 5350 return CK_CPointerToObjCPointerCast; 5351 maybeExtendBlockObject(Src); 5352 return CK_BlockPointerToObjCPointerCast; 5353 case Type::STK_Bool: 5354 return CK_PointerToBoolean; 5355 case Type::STK_Integral: 5356 return CK_PointerToIntegral; 5357 case Type::STK_Floating: 5358 case Type::STK_FloatingComplex: 5359 case Type::STK_IntegralComplex: 5360 case Type::STK_MemberPointer: 5361 llvm_unreachable("illegal cast from pointer"); 5362 } 5363 llvm_unreachable("Should have returned before this"); 5364 5365 case Type::STK_Bool: // casting from bool is like casting from an integer 5366 case Type::STK_Integral: 5367 switch (DestTy->getScalarTypeKind()) { 5368 case Type::STK_CPointer: 5369 case Type::STK_ObjCObjectPointer: 5370 case Type::STK_BlockPointer: 5371 if (Src.get()->isNullPointerConstant(Context, 5372 Expr::NPC_ValueDependentIsNull)) 5373 return CK_NullToPointer; 5374 return CK_IntegralToPointer; 5375 case Type::STK_Bool: 5376 return CK_IntegralToBoolean; 5377 case Type::STK_Integral: 5378 return CK_IntegralCast; 5379 case Type::STK_Floating: 5380 return CK_IntegralToFloating; 5381 case Type::STK_IntegralComplex: 5382 Src = ImpCastExprToType(Src.get(), 5383 DestTy->castAs<ComplexType>()->getElementType(), 5384 CK_IntegralCast); 5385 return CK_IntegralRealToComplex; 5386 case Type::STK_FloatingComplex: 5387 Src = ImpCastExprToType(Src.get(), 5388 DestTy->castAs<ComplexType>()->getElementType(), 5389 CK_IntegralToFloating); 5390 return CK_FloatingRealToComplex; 5391 case Type::STK_MemberPointer: 5392 llvm_unreachable("member pointer type in C"); 5393 } 5394 llvm_unreachable("Should have returned before this"); 5395 5396 case Type::STK_Floating: 5397 switch (DestTy->getScalarTypeKind()) { 5398 case Type::STK_Floating: 5399 return CK_FloatingCast; 5400 case Type::STK_Bool: 5401 return CK_FloatingToBoolean; 5402 case Type::STK_Integral: 5403 return CK_FloatingToIntegral; 5404 case Type::STK_FloatingComplex: 5405 Src = ImpCastExprToType(Src.get(), 5406 DestTy->castAs<ComplexType>()->getElementType(), 5407 CK_FloatingCast); 5408 return CK_FloatingRealToComplex; 5409 case Type::STK_IntegralComplex: 5410 Src = ImpCastExprToType(Src.get(), 5411 DestTy->castAs<ComplexType>()->getElementType(), 5412 CK_FloatingToIntegral); 5413 return CK_IntegralRealToComplex; 5414 case Type::STK_CPointer: 5415 case Type::STK_ObjCObjectPointer: 5416 case Type::STK_BlockPointer: 5417 llvm_unreachable("valid float->pointer cast?"); 5418 case Type::STK_MemberPointer: 5419 llvm_unreachable("member pointer type in C"); 5420 } 5421 llvm_unreachable("Should have returned before this"); 5422 5423 case Type::STK_FloatingComplex: 5424 switch (DestTy->getScalarTypeKind()) { 5425 case Type::STK_FloatingComplex: 5426 return CK_FloatingComplexCast; 5427 case Type::STK_IntegralComplex: 5428 return CK_FloatingComplexToIntegralComplex; 5429 case Type::STK_Floating: { 5430 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5431 if (Context.hasSameType(ET, DestTy)) 5432 return CK_FloatingComplexToReal; 5433 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5434 return CK_FloatingCast; 5435 } 5436 case Type::STK_Bool: 5437 return CK_FloatingComplexToBoolean; 5438 case Type::STK_Integral: 5439 Src = ImpCastExprToType(Src.get(), 5440 SrcTy->castAs<ComplexType>()->getElementType(), 5441 CK_FloatingComplexToReal); 5442 return CK_FloatingToIntegral; 5443 case Type::STK_CPointer: 5444 case Type::STK_ObjCObjectPointer: 5445 case Type::STK_BlockPointer: 5446 llvm_unreachable("valid complex float->pointer cast?"); 5447 case Type::STK_MemberPointer: 5448 llvm_unreachable("member pointer type in C"); 5449 } 5450 llvm_unreachable("Should have returned before this"); 5451 5452 case Type::STK_IntegralComplex: 5453 switch (DestTy->getScalarTypeKind()) { 5454 case Type::STK_FloatingComplex: 5455 return CK_IntegralComplexToFloatingComplex; 5456 case Type::STK_IntegralComplex: 5457 return CK_IntegralComplexCast; 5458 case Type::STK_Integral: { 5459 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5460 if (Context.hasSameType(ET, DestTy)) 5461 return CK_IntegralComplexToReal; 5462 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5463 return CK_IntegralCast; 5464 } 5465 case Type::STK_Bool: 5466 return CK_IntegralComplexToBoolean; 5467 case Type::STK_Floating: 5468 Src = ImpCastExprToType(Src.get(), 5469 SrcTy->castAs<ComplexType>()->getElementType(), 5470 CK_IntegralComplexToReal); 5471 return CK_IntegralToFloating; 5472 case Type::STK_CPointer: 5473 case Type::STK_ObjCObjectPointer: 5474 case Type::STK_BlockPointer: 5475 llvm_unreachable("valid complex int->pointer cast?"); 5476 case Type::STK_MemberPointer: 5477 llvm_unreachable("member pointer type in C"); 5478 } 5479 llvm_unreachable("Should have returned before this"); 5480 } 5481 5482 llvm_unreachable("Unhandled scalar cast"); 5483 } 5484 5485 static bool breakDownVectorType(QualType type, uint64_t &len, 5486 QualType &eltType) { 5487 // Vectors are simple. 5488 if (const VectorType *vecType = type->getAs<VectorType>()) { 5489 len = vecType->getNumElements(); 5490 eltType = vecType->getElementType(); 5491 assert(eltType->isScalarType()); 5492 return true; 5493 } 5494 5495 // We allow lax conversion to and from non-vector types, but only if 5496 // they're real types (i.e. non-complex, non-pointer scalar types). 5497 if (!type->isRealType()) return false; 5498 5499 len = 1; 5500 eltType = type; 5501 return true; 5502 } 5503 5504 /// Are the two types lax-compatible vector types? That is, given 5505 /// that one of them is a vector, do they have equal storage sizes, 5506 /// where the storage size is the number of elements times the element 5507 /// size? 5508 /// 5509 /// This will also return false if either of the types is neither a 5510 /// vector nor a real type. 5511 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5512 assert(destTy->isVectorType() || srcTy->isVectorType()); 5513 5514 // Disallow lax conversions between scalars and ExtVectors (these 5515 // conversions are allowed for other vector types because common headers 5516 // depend on them). Most scalar OP ExtVector cases are handled by the 5517 // splat path anyway, which does what we want (convert, not bitcast). 5518 // What this rules out for ExtVectors is crazy things like char4*float. 5519 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5520 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5521 5522 uint64_t srcLen, destLen; 5523 QualType srcEltTy, destEltTy; 5524 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5525 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5526 5527 // ASTContext::getTypeSize will return the size rounded up to a 5528 // power of 2, so instead of using that, we need to use the raw 5529 // element size multiplied by the element count. 5530 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5531 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5532 5533 return (srcLen * srcEltSize == destLen * destEltSize); 5534 } 5535 5536 /// Is this a legal conversion between two types, one of which is 5537 /// known to be a vector type? 5538 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5539 assert(destTy->isVectorType() || srcTy->isVectorType()); 5540 5541 if (!Context.getLangOpts().LaxVectorConversions) 5542 return false; 5543 return areLaxCompatibleVectorTypes(srcTy, destTy); 5544 } 5545 5546 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5547 CastKind &Kind) { 5548 assert(VectorTy->isVectorType() && "Not a vector type!"); 5549 5550 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5551 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5552 return Diag(R.getBegin(), 5553 Ty->isVectorType() ? 5554 diag::err_invalid_conversion_between_vectors : 5555 diag::err_invalid_conversion_between_vector_and_integer) 5556 << VectorTy << Ty << R; 5557 } else 5558 return Diag(R.getBegin(), 5559 diag::err_invalid_conversion_between_vector_and_scalar) 5560 << VectorTy << Ty << R; 5561 5562 Kind = CK_BitCast; 5563 return false; 5564 } 5565 5566 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5567 Expr *CastExpr, CastKind &Kind) { 5568 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5569 5570 QualType SrcTy = CastExpr->getType(); 5571 5572 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5573 // an ExtVectorType. 5574 // In OpenCL, casts between vectors of different types are not allowed. 5575 // (See OpenCL 6.2). 5576 if (SrcTy->isVectorType()) { 5577 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5578 || (getLangOpts().OpenCL && 5579 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5580 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5581 << DestTy << SrcTy << R; 5582 return ExprError(); 5583 } 5584 Kind = CK_BitCast; 5585 return CastExpr; 5586 } 5587 5588 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5589 // conversion will take place first from scalar to elt type, and then 5590 // splat from elt type to vector. 5591 if (SrcTy->isPointerType()) 5592 return Diag(R.getBegin(), 5593 diag::err_invalid_conversion_between_vector_and_scalar) 5594 << DestTy << SrcTy << R; 5595 5596 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5597 ExprResult CastExprRes = CastExpr; 5598 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5599 if (CastExprRes.isInvalid()) 5600 return ExprError(); 5601 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5602 5603 Kind = CK_VectorSplat; 5604 return CastExpr; 5605 } 5606 5607 ExprResult 5608 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5609 Declarator &D, ParsedType &Ty, 5610 SourceLocation RParenLoc, Expr *CastExpr) { 5611 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5612 "ActOnCastExpr(): missing type or expr"); 5613 5614 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5615 if (D.isInvalidType()) 5616 return ExprError(); 5617 5618 if (getLangOpts().CPlusPlus) { 5619 // Check that there are no default arguments (C++ only). 5620 CheckExtraCXXDefaultArguments(D); 5621 } else { 5622 // Make sure any TypoExprs have been dealt with. 5623 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5624 if (!Res.isUsable()) 5625 return ExprError(); 5626 CastExpr = Res.get(); 5627 } 5628 5629 checkUnusedDeclAttributes(D); 5630 5631 QualType castType = castTInfo->getType(); 5632 Ty = CreateParsedType(castType, castTInfo); 5633 5634 bool isVectorLiteral = false; 5635 5636 // Check for an altivec or OpenCL literal, 5637 // i.e. all the elements are integer constants. 5638 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5639 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5640 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5641 && castType->isVectorType() && (PE || PLE)) { 5642 if (PLE && PLE->getNumExprs() == 0) { 5643 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5644 return ExprError(); 5645 } 5646 if (PE || PLE->getNumExprs() == 1) { 5647 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5648 if (!E->getType()->isVectorType()) 5649 isVectorLiteral = true; 5650 } 5651 else 5652 isVectorLiteral = true; 5653 } 5654 5655 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5656 // then handle it as such. 5657 if (isVectorLiteral) 5658 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5659 5660 // If the Expr being casted is a ParenListExpr, handle it specially. 5661 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5662 // sequence of BinOp comma operators. 5663 if (isa<ParenListExpr>(CastExpr)) { 5664 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5665 if (Result.isInvalid()) return ExprError(); 5666 CastExpr = Result.get(); 5667 } 5668 5669 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5670 !getSourceManager().isInSystemMacro(LParenLoc)) 5671 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5672 5673 CheckTollFreeBridgeCast(castType, CastExpr); 5674 5675 CheckObjCBridgeRelatedCast(castType, CastExpr); 5676 5677 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5678 } 5679 5680 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5681 SourceLocation RParenLoc, Expr *E, 5682 TypeSourceInfo *TInfo) { 5683 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5684 "Expected paren or paren list expression"); 5685 5686 Expr **exprs; 5687 unsigned numExprs; 5688 Expr *subExpr; 5689 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5690 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5691 LiteralLParenLoc = PE->getLParenLoc(); 5692 LiteralRParenLoc = PE->getRParenLoc(); 5693 exprs = PE->getExprs(); 5694 numExprs = PE->getNumExprs(); 5695 } else { // isa<ParenExpr> by assertion at function entrance 5696 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5697 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5698 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5699 exprs = &subExpr; 5700 numExprs = 1; 5701 } 5702 5703 QualType Ty = TInfo->getType(); 5704 assert(Ty->isVectorType() && "Expected vector type"); 5705 5706 SmallVector<Expr *, 8> initExprs; 5707 const VectorType *VTy = Ty->getAs<VectorType>(); 5708 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5709 5710 // '(...)' form of vector initialization in AltiVec: the number of 5711 // initializers must be one or must match the size of the vector. 5712 // If a single value is specified in the initializer then it will be 5713 // replicated to all the components of the vector 5714 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5715 // The number of initializers must be one or must match the size of the 5716 // vector. If a single value is specified in the initializer then it will 5717 // be replicated to all the components of the vector 5718 if (numExprs == 1) { 5719 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5720 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5721 if (Literal.isInvalid()) 5722 return ExprError(); 5723 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5724 PrepareScalarCast(Literal, ElemTy)); 5725 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5726 } 5727 else if (numExprs < numElems) { 5728 Diag(E->getExprLoc(), 5729 diag::err_incorrect_number_of_vector_initializers); 5730 return ExprError(); 5731 } 5732 else 5733 initExprs.append(exprs, exprs + numExprs); 5734 } 5735 else { 5736 // For OpenCL, when the number of initializers is a single value, 5737 // it will be replicated to all components of the vector. 5738 if (getLangOpts().OpenCL && 5739 VTy->getVectorKind() == VectorType::GenericVector && 5740 numExprs == 1) { 5741 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5742 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5743 if (Literal.isInvalid()) 5744 return ExprError(); 5745 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5746 PrepareScalarCast(Literal, ElemTy)); 5747 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5748 } 5749 5750 initExprs.append(exprs, exprs + numExprs); 5751 } 5752 // FIXME: This means that pretty-printing the final AST will produce curly 5753 // braces instead of the original commas. 5754 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5755 initExprs, LiteralRParenLoc); 5756 initE->setType(Ty); 5757 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5758 } 5759 5760 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5761 /// the ParenListExpr into a sequence of comma binary operators. 5762 ExprResult 5763 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5764 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5765 if (!E) 5766 return OrigExpr; 5767 5768 ExprResult Result(E->getExpr(0)); 5769 5770 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5771 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5772 E->getExpr(i)); 5773 5774 if (Result.isInvalid()) return ExprError(); 5775 5776 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5777 } 5778 5779 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5780 SourceLocation R, 5781 MultiExprArg Val) { 5782 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5783 return expr; 5784 } 5785 5786 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5787 /// constant and the other is not a pointer. Returns true if a diagnostic is 5788 /// emitted. 5789 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5790 SourceLocation QuestionLoc) { 5791 Expr *NullExpr = LHSExpr; 5792 Expr *NonPointerExpr = RHSExpr; 5793 Expr::NullPointerConstantKind NullKind = 5794 NullExpr->isNullPointerConstant(Context, 5795 Expr::NPC_ValueDependentIsNotNull); 5796 5797 if (NullKind == Expr::NPCK_NotNull) { 5798 NullExpr = RHSExpr; 5799 NonPointerExpr = LHSExpr; 5800 NullKind = 5801 NullExpr->isNullPointerConstant(Context, 5802 Expr::NPC_ValueDependentIsNotNull); 5803 } 5804 5805 if (NullKind == Expr::NPCK_NotNull) 5806 return false; 5807 5808 if (NullKind == Expr::NPCK_ZeroExpression) 5809 return false; 5810 5811 if (NullKind == Expr::NPCK_ZeroLiteral) { 5812 // In this case, check to make sure that we got here from a "NULL" 5813 // string in the source code. 5814 NullExpr = NullExpr->IgnoreParenImpCasts(); 5815 SourceLocation loc = NullExpr->getExprLoc(); 5816 if (!findMacroSpelling(loc, "NULL")) 5817 return false; 5818 } 5819 5820 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5821 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5822 << NonPointerExpr->getType() << DiagType 5823 << NonPointerExpr->getSourceRange(); 5824 return true; 5825 } 5826 5827 /// \brief Return false if the condition expression is valid, true otherwise. 5828 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 5829 QualType CondTy = Cond->getType(); 5830 5831 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 5832 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 5833 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 5834 << CondTy << Cond->getSourceRange(); 5835 return true; 5836 } 5837 5838 // C99 6.5.15p2 5839 if (CondTy->isScalarType()) return false; 5840 5841 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 5842 << CondTy << Cond->getSourceRange(); 5843 return true; 5844 } 5845 5846 /// \brief Handle when one or both operands are void type. 5847 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5848 ExprResult &RHS) { 5849 Expr *LHSExpr = LHS.get(); 5850 Expr *RHSExpr = RHS.get(); 5851 5852 if (!LHSExpr->getType()->isVoidType()) 5853 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5854 << RHSExpr->getSourceRange(); 5855 if (!RHSExpr->getType()->isVoidType()) 5856 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5857 << LHSExpr->getSourceRange(); 5858 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5859 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5860 return S.Context.VoidTy; 5861 } 5862 5863 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5864 /// true otherwise. 5865 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5866 QualType PointerTy) { 5867 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5868 !NullExpr.get()->isNullPointerConstant(S.Context, 5869 Expr::NPC_ValueDependentIsNull)) 5870 return true; 5871 5872 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5873 return false; 5874 } 5875 5876 /// \brief Checks compatibility between two pointers and return the resulting 5877 /// type. 5878 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5879 ExprResult &RHS, 5880 SourceLocation Loc) { 5881 QualType LHSTy = LHS.get()->getType(); 5882 QualType RHSTy = RHS.get()->getType(); 5883 5884 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5885 // Two identical pointers types are always compatible. 5886 return LHSTy; 5887 } 5888 5889 QualType lhptee, rhptee; 5890 5891 // Get the pointee types. 5892 bool IsBlockPointer = false; 5893 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5894 lhptee = LHSBTy->getPointeeType(); 5895 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5896 IsBlockPointer = true; 5897 } else { 5898 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5899 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5900 } 5901 5902 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5903 // differently qualified versions of compatible types, the result type is 5904 // a pointer to an appropriately qualified version of the composite 5905 // type. 5906 5907 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5908 // clause doesn't make sense for our extensions. E.g. address space 2 should 5909 // be incompatible with address space 3: they may live on different devices or 5910 // anything. 5911 Qualifiers lhQual = lhptee.getQualifiers(); 5912 Qualifiers rhQual = rhptee.getQualifiers(); 5913 5914 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5915 lhQual.removeCVRQualifiers(); 5916 rhQual.removeCVRQualifiers(); 5917 5918 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5919 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5920 5921 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5922 5923 if (CompositeTy.isNull()) { 5924 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 5925 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5926 << RHS.get()->getSourceRange(); 5927 // In this situation, we assume void* type. No especially good 5928 // reason, but this is what gcc does, and we do have to pick 5929 // to get a consistent AST. 5930 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5931 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5932 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5933 return incompatTy; 5934 } 5935 5936 // The pointer types are compatible. 5937 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5938 if (IsBlockPointer) 5939 ResultTy = S.Context.getBlockPointerType(ResultTy); 5940 else 5941 ResultTy = S.Context.getPointerType(ResultTy); 5942 5943 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5944 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5945 return ResultTy; 5946 } 5947 5948 /// \brief Return the resulting type when the operands are both block pointers. 5949 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5950 ExprResult &LHS, 5951 ExprResult &RHS, 5952 SourceLocation Loc) { 5953 QualType LHSTy = LHS.get()->getType(); 5954 QualType RHSTy = RHS.get()->getType(); 5955 5956 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5957 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5958 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5959 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5960 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5961 return destType; 5962 } 5963 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5964 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5965 << RHS.get()->getSourceRange(); 5966 return QualType(); 5967 } 5968 5969 // We have 2 block pointer types. 5970 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5971 } 5972 5973 /// \brief Return the resulting type when the operands are both pointers. 5974 static QualType 5975 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5976 ExprResult &RHS, 5977 SourceLocation Loc) { 5978 // get the pointer types 5979 QualType LHSTy = LHS.get()->getType(); 5980 QualType RHSTy = RHS.get()->getType(); 5981 5982 // get the "pointed to" types 5983 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5984 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5985 5986 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5987 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5988 // Figure out necessary qualifiers (C99 6.5.15p6) 5989 QualType destPointee 5990 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5991 QualType destType = S.Context.getPointerType(destPointee); 5992 // Add qualifiers if necessary. 5993 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 5994 // Promote to void*. 5995 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5996 return destType; 5997 } 5998 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5999 QualType destPointee 6000 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6001 QualType destType = S.Context.getPointerType(destPointee); 6002 // Add qualifiers if necessary. 6003 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6004 // Promote to void*. 6005 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6006 return destType; 6007 } 6008 6009 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6010 } 6011 6012 /// \brief Return false if the first expression is not an integer and the second 6013 /// expression is not a pointer, true otherwise. 6014 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6015 Expr* PointerExpr, SourceLocation Loc, 6016 bool IsIntFirstExpr) { 6017 if (!PointerExpr->getType()->isPointerType() || 6018 !Int.get()->getType()->isIntegerType()) 6019 return false; 6020 6021 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6022 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6023 6024 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6025 << Expr1->getType() << Expr2->getType() 6026 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6027 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6028 CK_IntegralToPointer); 6029 return true; 6030 } 6031 6032 /// \brief Simple conversion between integer and floating point types. 6033 /// 6034 /// Used when handling the OpenCL conditional operator where the 6035 /// condition is a vector while the other operands are scalar. 6036 /// 6037 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6038 /// types are either integer or floating type. Between the two 6039 /// operands, the type with the higher rank is defined as the "result 6040 /// type". The other operand needs to be promoted to the same type. No 6041 /// other type promotion is allowed. We cannot use 6042 /// UsualArithmeticConversions() for this purpose, since it always 6043 /// promotes promotable types. 6044 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6045 ExprResult &RHS, 6046 SourceLocation QuestionLoc) { 6047 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6048 if (LHS.isInvalid()) 6049 return QualType(); 6050 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6051 if (RHS.isInvalid()) 6052 return QualType(); 6053 6054 // For conversion purposes, we ignore any qualifiers. 6055 // For example, "const float" and "float" are equivalent. 6056 QualType LHSType = 6057 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6058 QualType RHSType = 6059 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6060 6061 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6062 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6063 << LHSType << LHS.get()->getSourceRange(); 6064 return QualType(); 6065 } 6066 6067 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6068 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6069 << RHSType << RHS.get()->getSourceRange(); 6070 return QualType(); 6071 } 6072 6073 // If both types are identical, no conversion is needed. 6074 if (LHSType == RHSType) 6075 return LHSType; 6076 6077 // Now handle "real" floating types (i.e. float, double, long double). 6078 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6079 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6080 /*IsCompAssign = */ false); 6081 6082 // Finally, we have two differing integer types. 6083 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6084 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6085 } 6086 6087 /// \brief Convert scalar operands to a vector that matches the 6088 /// condition in length. 6089 /// 6090 /// Used when handling the OpenCL conditional operator where the 6091 /// condition is a vector while the other operands are scalar. 6092 /// 6093 /// We first compute the "result type" for the scalar operands 6094 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6095 /// into a vector of that type where the length matches the condition 6096 /// vector type. s6.11.6 requires that the element types of the result 6097 /// and the condition must have the same number of bits. 6098 static QualType 6099 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6100 QualType CondTy, SourceLocation QuestionLoc) { 6101 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6102 if (ResTy.isNull()) return QualType(); 6103 6104 const VectorType *CV = CondTy->getAs<VectorType>(); 6105 assert(CV); 6106 6107 // Determine the vector result type 6108 unsigned NumElements = CV->getNumElements(); 6109 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6110 6111 // Ensure that all types have the same number of bits 6112 if (S.Context.getTypeSize(CV->getElementType()) 6113 != S.Context.getTypeSize(ResTy)) { 6114 // Since VectorTy is created internally, it does not pretty print 6115 // with an OpenCL name. Instead, we just print a description. 6116 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6117 SmallString<64> Str; 6118 llvm::raw_svector_ostream OS(Str); 6119 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6120 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6121 << CondTy << OS.str(); 6122 return QualType(); 6123 } 6124 6125 // Convert operands to the vector result type 6126 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6127 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6128 6129 return VectorTy; 6130 } 6131 6132 /// \brief Return false if this is a valid OpenCL condition vector 6133 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6134 SourceLocation QuestionLoc) { 6135 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6136 // integral type. 6137 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6138 assert(CondTy); 6139 QualType EleTy = CondTy->getElementType(); 6140 if (EleTy->isIntegerType()) return false; 6141 6142 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6143 << Cond->getType() << Cond->getSourceRange(); 6144 return true; 6145 } 6146 6147 /// \brief Return false if the vector condition type and the vector 6148 /// result type are compatible. 6149 /// 6150 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6151 /// number of elements, and their element types have the same number 6152 /// of bits. 6153 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6154 SourceLocation QuestionLoc) { 6155 const VectorType *CV = CondTy->getAs<VectorType>(); 6156 const VectorType *RV = VecResTy->getAs<VectorType>(); 6157 assert(CV && RV); 6158 6159 if (CV->getNumElements() != RV->getNumElements()) { 6160 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6161 << CondTy << VecResTy; 6162 return true; 6163 } 6164 6165 QualType CVE = CV->getElementType(); 6166 QualType RVE = RV->getElementType(); 6167 6168 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6169 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6170 << CondTy << VecResTy; 6171 return true; 6172 } 6173 6174 return false; 6175 } 6176 6177 /// \brief Return the resulting type for the conditional operator in 6178 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6179 /// s6.3.i) when the condition is a vector type. 6180 static QualType 6181 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6182 ExprResult &LHS, ExprResult &RHS, 6183 SourceLocation QuestionLoc) { 6184 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6185 if (Cond.isInvalid()) 6186 return QualType(); 6187 QualType CondTy = Cond.get()->getType(); 6188 6189 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6190 return QualType(); 6191 6192 // If either operand is a vector then find the vector type of the 6193 // result as specified in OpenCL v1.1 s6.3.i. 6194 if (LHS.get()->getType()->isVectorType() || 6195 RHS.get()->getType()->isVectorType()) { 6196 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6197 /*isCompAssign*/false, 6198 /*AllowBothBool*/true, 6199 /*AllowBoolConversions*/false); 6200 if (VecResTy.isNull()) return QualType(); 6201 // The result type must match the condition type as specified in 6202 // OpenCL v1.1 s6.11.6. 6203 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6204 return QualType(); 6205 return VecResTy; 6206 } 6207 6208 // Both operands are scalar. 6209 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6210 } 6211 6212 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6213 /// In that case, LHS = cond. 6214 /// C99 6.5.15 6215 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6216 ExprResult &RHS, ExprValueKind &VK, 6217 ExprObjectKind &OK, 6218 SourceLocation QuestionLoc) { 6219 6220 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6221 if (!LHSResult.isUsable()) return QualType(); 6222 LHS = LHSResult; 6223 6224 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6225 if (!RHSResult.isUsable()) return QualType(); 6226 RHS = RHSResult; 6227 6228 // C++ is sufficiently different to merit its own checker. 6229 if (getLangOpts().CPlusPlus) 6230 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6231 6232 VK = VK_RValue; 6233 OK = OK_Ordinary; 6234 6235 // The OpenCL operator with a vector condition is sufficiently 6236 // different to merit its own checker. 6237 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6238 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6239 6240 // First, check the condition. 6241 Cond = UsualUnaryConversions(Cond.get()); 6242 if (Cond.isInvalid()) 6243 return QualType(); 6244 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6245 return QualType(); 6246 6247 // Now check the two expressions. 6248 if (LHS.get()->getType()->isVectorType() || 6249 RHS.get()->getType()->isVectorType()) 6250 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6251 /*AllowBothBool*/true, 6252 /*AllowBoolConversions*/false); 6253 6254 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6255 if (LHS.isInvalid() || RHS.isInvalid()) 6256 return QualType(); 6257 6258 QualType LHSTy = LHS.get()->getType(); 6259 QualType RHSTy = RHS.get()->getType(); 6260 6261 // If both operands have arithmetic type, do the usual arithmetic conversions 6262 // to find a common type: C99 6.5.15p3,5. 6263 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6264 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6265 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6266 6267 return ResTy; 6268 } 6269 6270 // If both operands are the same structure or union type, the result is that 6271 // type. 6272 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6273 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6274 if (LHSRT->getDecl() == RHSRT->getDecl()) 6275 // "If both the operands have structure or union type, the result has 6276 // that type." This implies that CV qualifiers are dropped. 6277 return LHSTy.getUnqualifiedType(); 6278 // FIXME: Type of conditional expression must be complete in C mode. 6279 } 6280 6281 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6282 // The following || allows only one side to be void (a GCC-ism). 6283 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6284 return checkConditionalVoidType(*this, LHS, RHS); 6285 } 6286 6287 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6288 // the type of the other operand." 6289 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6290 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6291 6292 // All objective-c pointer type analysis is done here. 6293 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6294 QuestionLoc); 6295 if (LHS.isInvalid() || RHS.isInvalid()) 6296 return QualType(); 6297 if (!compositeType.isNull()) 6298 return compositeType; 6299 6300 6301 // Handle block pointer types. 6302 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6303 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6304 QuestionLoc); 6305 6306 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6307 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6308 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6309 QuestionLoc); 6310 6311 // GCC compatibility: soften pointer/integer mismatch. Note that 6312 // null pointers have been filtered out by this point. 6313 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6314 /*isIntFirstExpr=*/true)) 6315 return RHSTy; 6316 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6317 /*isIntFirstExpr=*/false)) 6318 return LHSTy; 6319 6320 // Emit a better diagnostic if one of the expressions is a null pointer 6321 // constant and the other is not a pointer type. In this case, the user most 6322 // likely forgot to take the address of the other expression. 6323 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6324 return QualType(); 6325 6326 // Otherwise, the operands are not compatible. 6327 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6328 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6329 << RHS.get()->getSourceRange(); 6330 return QualType(); 6331 } 6332 6333 /// FindCompositeObjCPointerType - Helper method to find composite type of 6334 /// two objective-c pointer types of the two input expressions. 6335 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6336 SourceLocation QuestionLoc) { 6337 QualType LHSTy = LHS.get()->getType(); 6338 QualType RHSTy = RHS.get()->getType(); 6339 6340 // Handle things like Class and struct objc_class*. Here we case the result 6341 // to the pseudo-builtin, because that will be implicitly cast back to the 6342 // redefinition type if an attempt is made to access its fields. 6343 if (LHSTy->isObjCClassType() && 6344 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6345 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6346 return LHSTy; 6347 } 6348 if (RHSTy->isObjCClassType() && 6349 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6350 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6351 return RHSTy; 6352 } 6353 // And the same for struct objc_object* / id 6354 if (LHSTy->isObjCIdType() && 6355 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6356 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6357 return LHSTy; 6358 } 6359 if (RHSTy->isObjCIdType() && 6360 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6361 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6362 return RHSTy; 6363 } 6364 // And the same for struct objc_selector* / SEL 6365 if (Context.isObjCSelType(LHSTy) && 6366 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6367 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6368 return LHSTy; 6369 } 6370 if (Context.isObjCSelType(RHSTy) && 6371 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6372 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6373 return RHSTy; 6374 } 6375 // Check constraints for Objective-C object pointers types. 6376 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6377 6378 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6379 // Two identical object pointer types are always compatible. 6380 return LHSTy; 6381 } 6382 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6383 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6384 QualType compositeType = LHSTy; 6385 6386 // If both operands are interfaces and either operand can be 6387 // assigned to the other, use that type as the composite 6388 // type. This allows 6389 // xxx ? (A*) a : (B*) b 6390 // where B is a subclass of A. 6391 // 6392 // Additionally, as for assignment, if either type is 'id' 6393 // allow silent coercion. Finally, if the types are 6394 // incompatible then make sure to use 'id' as the composite 6395 // type so the result is acceptable for sending messages to. 6396 6397 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6398 // It could return the composite type. 6399 if (!(compositeType = 6400 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6401 // Nothing more to do. 6402 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6403 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6404 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6405 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6406 } else if ((LHSTy->isObjCQualifiedIdType() || 6407 RHSTy->isObjCQualifiedIdType()) && 6408 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6409 // Need to handle "id<xx>" explicitly. 6410 // GCC allows qualified id and any Objective-C type to devolve to 6411 // id. Currently localizing to here until clear this should be 6412 // part of ObjCQualifiedIdTypesAreCompatible. 6413 compositeType = Context.getObjCIdType(); 6414 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6415 compositeType = Context.getObjCIdType(); 6416 } else { 6417 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6418 << LHSTy << RHSTy 6419 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6420 QualType incompatTy = Context.getObjCIdType(); 6421 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6422 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6423 return incompatTy; 6424 } 6425 // The object pointer types are compatible. 6426 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6427 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6428 return compositeType; 6429 } 6430 // Check Objective-C object pointer types and 'void *' 6431 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6432 if (getLangOpts().ObjCAutoRefCount) { 6433 // ARC forbids the implicit conversion of object pointers to 'void *', 6434 // so these types are not compatible. 6435 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6436 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6437 LHS = RHS = true; 6438 return QualType(); 6439 } 6440 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6441 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6442 QualType destPointee 6443 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6444 QualType destType = Context.getPointerType(destPointee); 6445 // Add qualifiers if necessary. 6446 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6447 // Promote to void*. 6448 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6449 return destType; 6450 } 6451 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6452 if (getLangOpts().ObjCAutoRefCount) { 6453 // ARC forbids the implicit conversion of object pointers to 'void *', 6454 // so these types are not compatible. 6455 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6456 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6457 LHS = RHS = true; 6458 return QualType(); 6459 } 6460 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6461 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6462 QualType destPointee 6463 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6464 QualType destType = Context.getPointerType(destPointee); 6465 // Add qualifiers if necessary. 6466 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6467 // Promote to void*. 6468 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6469 return destType; 6470 } 6471 return QualType(); 6472 } 6473 6474 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6475 /// ParenRange in parentheses. 6476 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6477 const PartialDiagnostic &Note, 6478 SourceRange ParenRange) { 6479 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 6480 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6481 EndLoc.isValid()) { 6482 Self.Diag(Loc, Note) 6483 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6484 << FixItHint::CreateInsertion(EndLoc, ")"); 6485 } else { 6486 // We can't display the parentheses, so just show the bare note. 6487 Self.Diag(Loc, Note) << ParenRange; 6488 } 6489 } 6490 6491 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6492 return Opc >= BO_Mul && Opc <= BO_Shr; 6493 } 6494 6495 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6496 /// expression, either using a built-in or overloaded operator, 6497 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6498 /// expression. 6499 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6500 Expr **RHSExprs) { 6501 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6502 E = E->IgnoreImpCasts(); 6503 E = E->IgnoreConversionOperator(); 6504 E = E->IgnoreImpCasts(); 6505 6506 // Built-in binary operator. 6507 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6508 if (IsArithmeticOp(OP->getOpcode())) { 6509 *Opcode = OP->getOpcode(); 6510 *RHSExprs = OP->getRHS(); 6511 return true; 6512 } 6513 } 6514 6515 // Overloaded operator. 6516 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6517 if (Call->getNumArgs() != 2) 6518 return false; 6519 6520 // Make sure this is really a binary operator that is safe to pass into 6521 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6522 OverloadedOperatorKind OO = Call->getOperator(); 6523 if (OO < OO_Plus || OO > OO_Arrow || 6524 OO == OO_PlusPlus || OO == OO_MinusMinus) 6525 return false; 6526 6527 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6528 if (IsArithmeticOp(OpKind)) { 6529 *Opcode = OpKind; 6530 *RHSExprs = Call->getArg(1); 6531 return true; 6532 } 6533 } 6534 6535 return false; 6536 } 6537 6538 static bool IsLogicOp(BinaryOperatorKind Opc) { 6539 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 6540 } 6541 6542 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6543 /// or is a logical expression such as (x==y) which has int type, but is 6544 /// commonly interpreted as boolean. 6545 static bool ExprLooksBoolean(Expr *E) { 6546 E = E->IgnoreParenImpCasts(); 6547 6548 if (E->getType()->isBooleanType()) 6549 return true; 6550 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6551 return IsLogicOp(OP->getOpcode()); 6552 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6553 return OP->getOpcode() == UO_LNot; 6554 if (E->getType()->isPointerType()) 6555 return true; 6556 6557 return false; 6558 } 6559 6560 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6561 /// and binary operator are mixed in a way that suggests the programmer assumed 6562 /// the conditional operator has higher precedence, for example: 6563 /// "int x = a + someBinaryCondition ? 1 : 2". 6564 static void DiagnoseConditionalPrecedence(Sema &Self, 6565 SourceLocation OpLoc, 6566 Expr *Condition, 6567 Expr *LHSExpr, 6568 Expr *RHSExpr) { 6569 BinaryOperatorKind CondOpcode; 6570 Expr *CondRHS; 6571 6572 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6573 return; 6574 if (!ExprLooksBoolean(CondRHS)) 6575 return; 6576 6577 // The condition is an arithmetic binary expression, with a right- 6578 // hand side that looks boolean, so warn. 6579 6580 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6581 << Condition->getSourceRange() 6582 << BinaryOperator::getOpcodeStr(CondOpcode); 6583 6584 SuggestParentheses(Self, OpLoc, 6585 Self.PDiag(diag::note_precedence_silence) 6586 << BinaryOperator::getOpcodeStr(CondOpcode), 6587 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6588 6589 SuggestParentheses(Self, OpLoc, 6590 Self.PDiag(diag::note_precedence_conditional_first), 6591 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6592 } 6593 6594 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6595 /// in the case of a the GNU conditional expr extension. 6596 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6597 SourceLocation ColonLoc, 6598 Expr *CondExpr, Expr *LHSExpr, 6599 Expr *RHSExpr) { 6600 if (!getLangOpts().CPlusPlus) { 6601 // C cannot handle TypoExpr nodes in the condition because it 6602 // doesn't handle dependent types properly, so make sure any TypoExprs have 6603 // been dealt with before checking the operands. 6604 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6605 if (!CondResult.isUsable()) return ExprError(); 6606 CondExpr = CondResult.get(); 6607 } 6608 6609 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6610 // was the condition. 6611 OpaqueValueExpr *opaqueValue = nullptr; 6612 Expr *commonExpr = nullptr; 6613 if (!LHSExpr) { 6614 commonExpr = CondExpr; 6615 // Lower out placeholder types first. This is important so that we don't 6616 // try to capture a placeholder. This happens in few cases in C++; such 6617 // as Objective-C++'s dictionary subscripting syntax. 6618 if (commonExpr->hasPlaceholderType()) { 6619 ExprResult result = CheckPlaceholderExpr(commonExpr); 6620 if (!result.isUsable()) return ExprError(); 6621 commonExpr = result.get(); 6622 } 6623 // We usually want to apply unary conversions *before* saving, except 6624 // in the special case of a C++ l-value conditional. 6625 if (!(getLangOpts().CPlusPlus 6626 && !commonExpr->isTypeDependent() 6627 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6628 && commonExpr->isGLValue() 6629 && commonExpr->isOrdinaryOrBitFieldObject() 6630 && RHSExpr->isOrdinaryOrBitFieldObject() 6631 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6632 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6633 if (commonRes.isInvalid()) 6634 return ExprError(); 6635 commonExpr = commonRes.get(); 6636 } 6637 6638 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6639 commonExpr->getType(), 6640 commonExpr->getValueKind(), 6641 commonExpr->getObjectKind(), 6642 commonExpr); 6643 LHSExpr = CondExpr = opaqueValue; 6644 } 6645 6646 ExprValueKind VK = VK_RValue; 6647 ExprObjectKind OK = OK_Ordinary; 6648 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6649 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6650 VK, OK, QuestionLoc); 6651 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6652 RHS.isInvalid()) 6653 return ExprError(); 6654 6655 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6656 RHS.get()); 6657 6658 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6659 6660 if (!commonExpr) 6661 return new (Context) 6662 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6663 RHS.get(), result, VK, OK); 6664 6665 return new (Context) BinaryConditionalOperator( 6666 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6667 ColonLoc, result, VK, OK); 6668 } 6669 6670 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6671 // being closely modeled after the C99 spec:-). The odd characteristic of this 6672 // routine is it effectively iqnores the qualifiers on the top level pointee. 6673 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6674 // FIXME: add a couple examples in this comment. 6675 static Sema::AssignConvertType 6676 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6677 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6678 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6679 6680 // get the "pointed to" type (ignoring qualifiers at the top level) 6681 const Type *lhptee, *rhptee; 6682 Qualifiers lhq, rhq; 6683 std::tie(lhptee, lhq) = 6684 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6685 std::tie(rhptee, rhq) = 6686 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6687 6688 Sema::AssignConvertType ConvTy = Sema::Compatible; 6689 6690 // C99 6.5.16.1p1: This following citation is common to constraints 6691 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6692 // qualifiers of the type *pointed to* by the right; 6693 6694 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6695 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6696 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6697 // Ignore lifetime for further calculation. 6698 lhq.removeObjCLifetime(); 6699 rhq.removeObjCLifetime(); 6700 } 6701 6702 if (!lhq.compatiblyIncludes(rhq)) { 6703 // Treat address-space mismatches as fatal. TODO: address subspaces 6704 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6705 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6706 6707 // It's okay to add or remove GC or lifetime qualifiers when converting to 6708 // and from void*. 6709 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6710 .compatiblyIncludes( 6711 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6712 && (lhptee->isVoidType() || rhptee->isVoidType())) 6713 ; // keep old 6714 6715 // Treat lifetime mismatches as fatal. 6716 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6717 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6718 6719 // For GCC compatibility, other qualifier mismatches are treated 6720 // as still compatible in C. 6721 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6722 } 6723 6724 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6725 // incomplete type and the other is a pointer to a qualified or unqualified 6726 // version of void... 6727 if (lhptee->isVoidType()) { 6728 if (rhptee->isIncompleteOrObjectType()) 6729 return ConvTy; 6730 6731 // As an extension, we allow cast to/from void* to function pointer. 6732 assert(rhptee->isFunctionType()); 6733 return Sema::FunctionVoidPointer; 6734 } 6735 6736 if (rhptee->isVoidType()) { 6737 if (lhptee->isIncompleteOrObjectType()) 6738 return ConvTy; 6739 6740 // As an extension, we allow cast to/from void* to function pointer. 6741 assert(lhptee->isFunctionType()); 6742 return Sema::FunctionVoidPointer; 6743 } 6744 6745 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6746 // unqualified versions of compatible types, ... 6747 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6748 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6749 // Check if the pointee types are compatible ignoring the sign. 6750 // We explicitly check for char so that we catch "char" vs 6751 // "unsigned char" on systems where "char" is unsigned. 6752 if (lhptee->isCharType()) 6753 ltrans = S.Context.UnsignedCharTy; 6754 else if (lhptee->hasSignedIntegerRepresentation()) 6755 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6756 6757 if (rhptee->isCharType()) 6758 rtrans = S.Context.UnsignedCharTy; 6759 else if (rhptee->hasSignedIntegerRepresentation()) 6760 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6761 6762 if (ltrans == rtrans) { 6763 // Types are compatible ignoring the sign. Qualifier incompatibility 6764 // takes priority over sign incompatibility because the sign 6765 // warning can be disabled. 6766 if (ConvTy != Sema::Compatible) 6767 return ConvTy; 6768 6769 return Sema::IncompatiblePointerSign; 6770 } 6771 6772 // If we are a multi-level pointer, it's possible that our issue is simply 6773 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6774 // the eventual target type is the same and the pointers have the same 6775 // level of indirection, this must be the issue. 6776 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6777 do { 6778 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6779 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6780 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6781 6782 if (lhptee == rhptee) 6783 return Sema::IncompatibleNestedPointerQualifiers; 6784 } 6785 6786 // General pointer incompatibility takes priority over qualifiers. 6787 return Sema::IncompatiblePointer; 6788 } 6789 if (!S.getLangOpts().CPlusPlus && 6790 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6791 return Sema::IncompatiblePointer; 6792 return ConvTy; 6793 } 6794 6795 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6796 /// block pointer types are compatible or whether a block and normal pointer 6797 /// are compatible. It is more restrict than comparing two function pointer 6798 // types. 6799 static Sema::AssignConvertType 6800 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6801 QualType RHSType) { 6802 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6803 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6804 6805 QualType lhptee, rhptee; 6806 6807 // get the "pointed to" type (ignoring qualifiers at the top level) 6808 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6809 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6810 6811 // In C++, the types have to match exactly. 6812 if (S.getLangOpts().CPlusPlus) 6813 return Sema::IncompatibleBlockPointer; 6814 6815 Sema::AssignConvertType ConvTy = Sema::Compatible; 6816 6817 // For blocks we enforce that qualifiers are identical. 6818 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6819 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6820 6821 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6822 return Sema::IncompatibleBlockPointer; 6823 6824 return ConvTy; 6825 } 6826 6827 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6828 /// for assignment compatibility. 6829 static Sema::AssignConvertType 6830 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6831 QualType RHSType) { 6832 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6833 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6834 6835 if (LHSType->isObjCBuiltinType()) { 6836 // Class is not compatible with ObjC object pointers. 6837 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6838 !RHSType->isObjCQualifiedClassType()) 6839 return Sema::IncompatiblePointer; 6840 return Sema::Compatible; 6841 } 6842 if (RHSType->isObjCBuiltinType()) { 6843 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6844 !LHSType->isObjCQualifiedClassType()) 6845 return Sema::IncompatiblePointer; 6846 return Sema::Compatible; 6847 } 6848 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6849 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6850 6851 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6852 // make an exception for id<P> 6853 !LHSType->isObjCQualifiedIdType()) 6854 return Sema::CompatiblePointerDiscardsQualifiers; 6855 6856 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6857 return Sema::Compatible; 6858 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6859 return Sema::IncompatibleObjCQualifiedId; 6860 return Sema::IncompatiblePointer; 6861 } 6862 6863 Sema::AssignConvertType 6864 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6865 QualType LHSType, QualType RHSType) { 6866 // Fake up an opaque expression. We don't actually care about what 6867 // cast operations are required, so if CheckAssignmentConstraints 6868 // adds casts to this they'll be wasted, but fortunately that doesn't 6869 // usually happen on valid code. 6870 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6871 ExprResult RHSPtr = &RHSExpr; 6872 CastKind K = CK_Invalid; 6873 6874 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 6875 } 6876 6877 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6878 /// has code to accommodate several GCC extensions when type checking 6879 /// pointers. Here are some objectionable examples that GCC considers warnings: 6880 /// 6881 /// int a, *pint; 6882 /// short *pshort; 6883 /// struct foo *pfoo; 6884 /// 6885 /// pint = pshort; // warning: assignment from incompatible pointer type 6886 /// a = pint; // warning: assignment makes integer from pointer without a cast 6887 /// pint = a; // warning: assignment makes pointer from integer without a cast 6888 /// pint = pfoo; // warning: assignment from incompatible pointer type 6889 /// 6890 /// As a result, the code for dealing with pointers is more complex than the 6891 /// C99 spec dictates. 6892 /// 6893 /// Sets 'Kind' for any result kind except Incompatible. 6894 Sema::AssignConvertType 6895 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6896 CastKind &Kind, bool ConvertRHS) { 6897 QualType RHSType = RHS.get()->getType(); 6898 QualType OrigLHSType = LHSType; 6899 6900 // Get canonical types. We're not formatting these types, just comparing 6901 // them. 6902 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6903 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6904 6905 // Common case: no conversion required. 6906 if (LHSType == RHSType) { 6907 Kind = CK_NoOp; 6908 return Compatible; 6909 } 6910 6911 // If we have an atomic type, try a non-atomic assignment, then just add an 6912 // atomic qualification step. 6913 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6914 Sema::AssignConvertType result = 6915 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6916 if (result != Compatible) 6917 return result; 6918 if (Kind != CK_NoOp && ConvertRHS) 6919 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 6920 Kind = CK_NonAtomicToAtomic; 6921 return Compatible; 6922 } 6923 6924 // If the left-hand side is a reference type, then we are in a 6925 // (rare!) case where we've allowed the use of references in C, 6926 // e.g., as a parameter type in a built-in function. In this case, 6927 // just make sure that the type referenced is compatible with the 6928 // right-hand side type. The caller is responsible for adjusting 6929 // LHSType so that the resulting expression does not have reference 6930 // type. 6931 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6932 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6933 Kind = CK_LValueBitCast; 6934 return Compatible; 6935 } 6936 return Incompatible; 6937 } 6938 6939 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6940 // to the same ExtVector type. 6941 if (LHSType->isExtVectorType()) { 6942 if (RHSType->isExtVectorType()) 6943 return Incompatible; 6944 if (RHSType->isArithmeticType()) { 6945 // CK_VectorSplat does T -> vector T, so first cast to the 6946 // element type. 6947 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6948 if (elType != RHSType && ConvertRHS) { 6949 Kind = PrepareScalarCast(RHS, elType); 6950 RHS = ImpCastExprToType(RHS.get(), elType, Kind); 6951 } 6952 Kind = CK_VectorSplat; 6953 return Compatible; 6954 } 6955 } 6956 6957 // Conversions to or from vector type. 6958 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6959 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6960 // Allow assignments of an AltiVec vector type to an equivalent GCC 6961 // vector type and vice versa 6962 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6963 Kind = CK_BitCast; 6964 return Compatible; 6965 } 6966 6967 // If we are allowing lax vector conversions, and LHS and RHS are both 6968 // vectors, the total size only needs to be the same. This is a bitcast; 6969 // no bits are changed but the result type is different. 6970 if (isLaxVectorConversion(RHSType, LHSType)) { 6971 Kind = CK_BitCast; 6972 return IncompatibleVectors; 6973 } 6974 } 6975 return Incompatible; 6976 } 6977 6978 // Arithmetic conversions. 6979 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6980 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6981 if (ConvertRHS) 6982 Kind = PrepareScalarCast(RHS, LHSType); 6983 return Compatible; 6984 } 6985 6986 // Conversions to normal pointers. 6987 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6988 // U* -> T* 6989 if (isa<PointerType>(RHSType)) { 6990 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 6991 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 6992 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 6993 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6994 } 6995 6996 // int -> T* 6997 if (RHSType->isIntegerType()) { 6998 Kind = CK_IntegralToPointer; // FIXME: null? 6999 return IntToPointer; 7000 } 7001 7002 // C pointers are not compatible with ObjC object pointers, 7003 // with two exceptions: 7004 if (isa<ObjCObjectPointerType>(RHSType)) { 7005 // - conversions to void* 7006 if (LHSPointer->getPointeeType()->isVoidType()) { 7007 Kind = CK_BitCast; 7008 return Compatible; 7009 } 7010 7011 // - conversions from 'Class' to the redefinition type 7012 if (RHSType->isObjCClassType() && 7013 Context.hasSameType(LHSType, 7014 Context.getObjCClassRedefinitionType())) { 7015 Kind = CK_BitCast; 7016 return Compatible; 7017 } 7018 7019 Kind = CK_BitCast; 7020 return IncompatiblePointer; 7021 } 7022 7023 // U^ -> void* 7024 if (RHSType->getAs<BlockPointerType>()) { 7025 if (LHSPointer->getPointeeType()->isVoidType()) { 7026 Kind = CK_BitCast; 7027 return Compatible; 7028 } 7029 } 7030 7031 return Incompatible; 7032 } 7033 7034 // Conversions to block pointers. 7035 if (isa<BlockPointerType>(LHSType)) { 7036 // U^ -> T^ 7037 if (RHSType->isBlockPointerType()) { 7038 Kind = CK_BitCast; 7039 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7040 } 7041 7042 // int or null -> T^ 7043 if (RHSType->isIntegerType()) { 7044 Kind = CK_IntegralToPointer; // FIXME: null 7045 return IntToBlockPointer; 7046 } 7047 7048 // id -> T^ 7049 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7050 Kind = CK_AnyPointerToBlockPointerCast; 7051 return Compatible; 7052 } 7053 7054 // void* -> T^ 7055 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7056 if (RHSPT->getPointeeType()->isVoidType()) { 7057 Kind = CK_AnyPointerToBlockPointerCast; 7058 return Compatible; 7059 } 7060 7061 return Incompatible; 7062 } 7063 7064 // Conversions to Objective-C pointers. 7065 if (isa<ObjCObjectPointerType>(LHSType)) { 7066 // A* -> B* 7067 if (RHSType->isObjCObjectPointerType()) { 7068 Kind = CK_BitCast; 7069 Sema::AssignConvertType result = 7070 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7071 if (getLangOpts().ObjCAutoRefCount && 7072 result == Compatible && 7073 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7074 result = IncompatibleObjCWeakRef; 7075 return result; 7076 } 7077 7078 // int or null -> A* 7079 if (RHSType->isIntegerType()) { 7080 Kind = CK_IntegralToPointer; // FIXME: null 7081 return IntToPointer; 7082 } 7083 7084 // In general, C pointers are not compatible with ObjC object pointers, 7085 // with two exceptions: 7086 if (isa<PointerType>(RHSType)) { 7087 Kind = CK_CPointerToObjCPointerCast; 7088 7089 // - conversions from 'void*' 7090 if (RHSType->isVoidPointerType()) { 7091 return Compatible; 7092 } 7093 7094 // - conversions to 'Class' from its redefinition type 7095 if (LHSType->isObjCClassType() && 7096 Context.hasSameType(RHSType, 7097 Context.getObjCClassRedefinitionType())) { 7098 return Compatible; 7099 } 7100 7101 return IncompatiblePointer; 7102 } 7103 7104 // Only under strict condition T^ is compatible with an Objective-C pointer. 7105 if (RHSType->isBlockPointerType() && 7106 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7107 if (ConvertRHS) 7108 maybeExtendBlockObject(RHS); 7109 Kind = CK_BlockPointerToObjCPointerCast; 7110 return Compatible; 7111 } 7112 7113 return Incompatible; 7114 } 7115 7116 // Conversions from pointers that are not covered by the above. 7117 if (isa<PointerType>(RHSType)) { 7118 // T* -> _Bool 7119 if (LHSType == Context.BoolTy) { 7120 Kind = CK_PointerToBoolean; 7121 return Compatible; 7122 } 7123 7124 // T* -> int 7125 if (LHSType->isIntegerType()) { 7126 Kind = CK_PointerToIntegral; 7127 return PointerToInt; 7128 } 7129 7130 return Incompatible; 7131 } 7132 7133 // Conversions from Objective-C pointers that are not covered by the above. 7134 if (isa<ObjCObjectPointerType>(RHSType)) { 7135 // T* -> _Bool 7136 if (LHSType == Context.BoolTy) { 7137 Kind = CK_PointerToBoolean; 7138 return Compatible; 7139 } 7140 7141 // T* -> int 7142 if (LHSType->isIntegerType()) { 7143 Kind = CK_PointerToIntegral; 7144 return PointerToInt; 7145 } 7146 7147 return Incompatible; 7148 } 7149 7150 // struct A -> struct B 7151 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7152 if (Context.typesAreCompatible(LHSType, RHSType)) { 7153 Kind = CK_NoOp; 7154 return Compatible; 7155 } 7156 } 7157 7158 return Incompatible; 7159 } 7160 7161 /// \brief Constructs a transparent union from an expression that is 7162 /// used to initialize the transparent union. 7163 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7164 ExprResult &EResult, QualType UnionType, 7165 FieldDecl *Field) { 7166 // Build an initializer list that designates the appropriate member 7167 // of the transparent union. 7168 Expr *E = EResult.get(); 7169 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7170 E, SourceLocation()); 7171 Initializer->setType(UnionType); 7172 Initializer->setInitializedFieldInUnion(Field); 7173 7174 // Build a compound literal constructing a value of the transparent 7175 // union type from this initializer list. 7176 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7177 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7178 VK_RValue, Initializer, false); 7179 } 7180 7181 Sema::AssignConvertType 7182 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7183 ExprResult &RHS) { 7184 QualType RHSType = RHS.get()->getType(); 7185 7186 // If the ArgType is a Union type, we want to handle a potential 7187 // transparent_union GCC extension. 7188 const RecordType *UT = ArgType->getAsUnionType(); 7189 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7190 return Incompatible; 7191 7192 // The field to initialize within the transparent union. 7193 RecordDecl *UD = UT->getDecl(); 7194 FieldDecl *InitField = nullptr; 7195 // It's compatible if the expression matches any of the fields. 7196 for (auto *it : UD->fields()) { 7197 if (it->getType()->isPointerType()) { 7198 // If the transparent union contains a pointer type, we allow: 7199 // 1) void pointer 7200 // 2) null pointer constant 7201 if (RHSType->isPointerType()) 7202 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7203 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7204 InitField = it; 7205 break; 7206 } 7207 7208 if (RHS.get()->isNullPointerConstant(Context, 7209 Expr::NPC_ValueDependentIsNull)) { 7210 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7211 CK_NullToPointer); 7212 InitField = it; 7213 break; 7214 } 7215 } 7216 7217 CastKind Kind = CK_Invalid; 7218 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7219 == Compatible) { 7220 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7221 InitField = it; 7222 break; 7223 } 7224 } 7225 7226 if (!InitField) 7227 return Incompatible; 7228 7229 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7230 return Compatible; 7231 } 7232 7233 Sema::AssignConvertType 7234 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7235 bool Diagnose, 7236 bool DiagnoseCFAudited, 7237 bool ConvertRHS) { 7238 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7239 // we can't avoid *all* modifications at the moment, so we need some somewhere 7240 // to put the updated value. 7241 ExprResult LocalRHS = CallerRHS; 7242 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7243 7244 if (getLangOpts().CPlusPlus) { 7245 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7246 // C++ 5.17p3: If the left operand is not of class type, the 7247 // expression is implicitly converted (C++ 4) to the 7248 // cv-unqualified type of the left operand. 7249 ExprResult Res; 7250 if (Diagnose) { 7251 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7252 AA_Assigning); 7253 } else { 7254 ImplicitConversionSequence ICS = 7255 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7256 /*SuppressUserConversions=*/false, 7257 /*AllowExplicit=*/false, 7258 /*InOverloadResolution=*/false, 7259 /*CStyle=*/false, 7260 /*AllowObjCWritebackConversion=*/false); 7261 if (ICS.isFailure()) 7262 return Incompatible; 7263 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7264 ICS, AA_Assigning); 7265 } 7266 if (Res.isInvalid()) 7267 return Incompatible; 7268 Sema::AssignConvertType result = Compatible; 7269 if (getLangOpts().ObjCAutoRefCount && 7270 !CheckObjCARCUnavailableWeakConversion(LHSType, 7271 RHS.get()->getType())) 7272 result = IncompatibleObjCWeakRef; 7273 RHS = Res; 7274 return result; 7275 } 7276 7277 // FIXME: Currently, we fall through and treat C++ classes like C 7278 // structures. 7279 // FIXME: We also fall through for atomics; not sure what should 7280 // happen there, though. 7281 } else if (RHS.get()->getType() == Context.OverloadTy) { 7282 // As a set of extensions to C, we support overloading on functions. These 7283 // functions need to be resolved here. 7284 DeclAccessPair DAP; 7285 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7286 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7287 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7288 else 7289 return Incompatible; 7290 } 7291 7292 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7293 // a null pointer constant. 7294 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7295 LHSType->isBlockPointerType()) && 7296 RHS.get()->isNullPointerConstant(Context, 7297 Expr::NPC_ValueDependentIsNull)) { 7298 CastKind Kind; 7299 CXXCastPath Path; 7300 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 7301 if (ConvertRHS) 7302 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7303 return Compatible; 7304 } 7305 7306 // This check seems unnatural, however it is necessary to ensure the proper 7307 // conversion of functions/arrays. If the conversion were done for all 7308 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7309 // expressions that suppress this implicit conversion (&, sizeof). 7310 // 7311 // Suppress this for references: C++ 8.5.3p5. 7312 if (!LHSType->isReferenceType()) { 7313 // FIXME: We potentially allocate here even if ConvertRHS is false. 7314 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7315 if (RHS.isInvalid()) 7316 return Incompatible; 7317 } 7318 7319 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7320 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) { 7321 ObjCProtocolDecl *PDecl = OPE->getProtocol(); 7322 if (PDecl && !PDecl->hasDefinition()) { 7323 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7324 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7325 } 7326 } 7327 7328 CastKind Kind = CK_Invalid; 7329 Sema::AssignConvertType result = 7330 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7331 7332 // C99 6.5.16.1p2: The value of the right operand is converted to the 7333 // type of the assignment expression. 7334 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7335 // so that we can use references in built-in functions even in C. 7336 // The getNonReferenceType() call makes sure that the resulting expression 7337 // does not have reference type. 7338 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7339 QualType Ty = LHSType.getNonLValueExprType(Context); 7340 Expr *E = RHS.get(); 7341 if (getLangOpts().ObjCAutoRefCount) 7342 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7343 DiagnoseCFAudited); 7344 if (getLangOpts().ObjC1 && 7345 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 7346 LHSType, E->getType(), E) || 7347 ConversionToObjCStringLiteralCheck(LHSType, E))) { 7348 RHS = E; 7349 return Compatible; 7350 } 7351 7352 if (ConvertRHS) 7353 RHS = ImpCastExprToType(E, Ty, Kind); 7354 } 7355 return result; 7356 } 7357 7358 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7359 ExprResult &RHS) { 7360 Diag(Loc, diag::err_typecheck_invalid_operands) 7361 << LHS.get()->getType() << RHS.get()->getType() 7362 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7363 return QualType(); 7364 } 7365 7366 /// Try to convert a value of non-vector type to a vector type by converting 7367 /// the type to the element type of the vector and then performing a splat. 7368 /// If the language is OpenCL, we only use conversions that promote scalar 7369 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7370 /// for float->int. 7371 /// 7372 /// \param scalar - if non-null, actually perform the conversions 7373 /// \return true if the operation fails (but without diagnosing the failure) 7374 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7375 QualType scalarTy, 7376 QualType vectorEltTy, 7377 QualType vectorTy) { 7378 // The conversion to apply to the scalar before splatting it, 7379 // if necessary. 7380 CastKind scalarCast = CK_Invalid; 7381 7382 if (vectorEltTy->isIntegralType(S.Context)) { 7383 if (!scalarTy->isIntegralType(S.Context)) 7384 return true; 7385 if (S.getLangOpts().OpenCL && 7386 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7387 return true; 7388 scalarCast = CK_IntegralCast; 7389 } else if (vectorEltTy->isRealFloatingType()) { 7390 if (scalarTy->isRealFloatingType()) { 7391 if (S.getLangOpts().OpenCL && 7392 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7393 return true; 7394 scalarCast = CK_FloatingCast; 7395 } 7396 else if (scalarTy->isIntegralType(S.Context)) 7397 scalarCast = CK_IntegralToFloating; 7398 else 7399 return true; 7400 } else { 7401 return true; 7402 } 7403 7404 // Adjust scalar if desired. 7405 if (scalar) { 7406 if (scalarCast != CK_Invalid) 7407 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7408 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7409 } 7410 return false; 7411 } 7412 7413 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7414 SourceLocation Loc, bool IsCompAssign, 7415 bool AllowBothBool, 7416 bool AllowBoolConversions) { 7417 if (!IsCompAssign) { 7418 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7419 if (LHS.isInvalid()) 7420 return QualType(); 7421 } 7422 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7423 if (RHS.isInvalid()) 7424 return QualType(); 7425 7426 // For conversion purposes, we ignore any qualifiers. 7427 // For example, "const float" and "float" are equivalent. 7428 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7429 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7430 7431 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7432 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7433 assert(LHSVecType || RHSVecType); 7434 7435 // AltiVec-style "vector bool op vector bool" combinations are allowed 7436 // for some operators but not others. 7437 if (!AllowBothBool && 7438 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7439 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7440 return InvalidOperands(Loc, LHS, RHS); 7441 7442 // If the vector types are identical, return. 7443 if (Context.hasSameType(LHSType, RHSType)) 7444 return LHSType; 7445 7446 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7447 if (LHSVecType && RHSVecType && 7448 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7449 if (isa<ExtVectorType>(LHSVecType)) { 7450 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7451 return LHSType; 7452 } 7453 7454 if (!IsCompAssign) 7455 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7456 return RHSType; 7457 } 7458 7459 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7460 // can be mixed, with the result being the non-bool type. The non-bool 7461 // operand must have integer element type. 7462 if (AllowBoolConversions && LHSVecType && RHSVecType && 7463 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7464 (Context.getTypeSize(LHSVecType->getElementType()) == 7465 Context.getTypeSize(RHSVecType->getElementType()))) { 7466 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7467 LHSVecType->getElementType()->isIntegerType() && 7468 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7469 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7470 return LHSType; 7471 } 7472 if (!IsCompAssign && 7473 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7474 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7475 RHSVecType->getElementType()->isIntegerType()) { 7476 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7477 return RHSType; 7478 } 7479 } 7480 7481 // If there's an ext-vector type and a scalar, try to convert the scalar to 7482 // the vector element type and splat. 7483 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7484 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7485 LHSVecType->getElementType(), LHSType)) 7486 return LHSType; 7487 } 7488 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7489 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7490 LHSType, RHSVecType->getElementType(), 7491 RHSType)) 7492 return RHSType; 7493 } 7494 7495 // If we're allowing lax vector conversions, only the total (data) size 7496 // needs to be the same. 7497 // FIXME: Should we really be allowing this? 7498 // FIXME: We really just pick the LHS type arbitrarily? 7499 if (isLaxVectorConversion(RHSType, LHSType)) { 7500 QualType resultType = LHSType; 7501 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7502 return resultType; 7503 } 7504 7505 // Okay, the expression is invalid. 7506 7507 // If there's a non-vector, non-real operand, diagnose that. 7508 if ((!RHSVecType && !RHSType->isRealType()) || 7509 (!LHSVecType && !LHSType->isRealType())) { 7510 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7511 << LHSType << RHSType 7512 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7513 return QualType(); 7514 } 7515 7516 // OpenCL V1.1 6.2.6.p1: 7517 // If the operands are of more than one vector type, then an error shall 7518 // occur. Implicit conversions between vector types are not permitted, per 7519 // section 6.2.1. 7520 if (getLangOpts().OpenCL && 7521 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7522 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7523 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7524 << RHSType; 7525 return QualType(); 7526 } 7527 7528 // Otherwise, use the generic diagnostic. 7529 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7530 << LHSType << RHSType 7531 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7532 return QualType(); 7533 } 7534 7535 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7536 // expression. These are mainly cases where the null pointer is used as an 7537 // integer instead of a pointer. 7538 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7539 SourceLocation Loc, bool IsCompare) { 7540 // The canonical way to check for a GNU null is with isNullPointerConstant, 7541 // but we use a bit of a hack here for speed; this is a relatively 7542 // hot path, and isNullPointerConstant is slow. 7543 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7544 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7545 7546 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7547 7548 // Avoid analyzing cases where the result will either be invalid (and 7549 // diagnosed as such) or entirely valid and not something to warn about. 7550 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7551 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7552 return; 7553 7554 // Comparison operations would not make sense with a null pointer no matter 7555 // what the other expression is. 7556 if (!IsCompare) { 7557 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7558 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7559 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7560 return; 7561 } 7562 7563 // The rest of the operations only make sense with a null pointer 7564 // if the other expression is a pointer. 7565 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7566 NonNullType->canDecayToPointerType()) 7567 return; 7568 7569 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7570 << LHSNull /* LHS is NULL */ << NonNullType 7571 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7572 } 7573 7574 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7575 ExprResult &RHS, 7576 SourceLocation Loc, bool IsDiv) { 7577 // Check for division/remainder by zero. 7578 unsigned Diag = (IsDiv) ? diag::warn_division_by_zero : 7579 diag::warn_remainder_by_zero; 7580 llvm::APSInt RHSValue; 7581 if (!RHS.get()->isValueDependent() && 7582 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7583 S.DiagRuntimeBehavior(Loc, RHS.get(), 7584 S.PDiag(Diag) << RHS.get()->getSourceRange()); 7585 } 7586 7587 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7588 SourceLocation Loc, 7589 bool IsCompAssign, bool IsDiv) { 7590 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7591 7592 if (LHS.get()->getType()->isVectorType() || 7593 RHS.get()->getType()->isVectorType()) 7594 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7595 /*AllowBothBool*/getLangOpts().AltiVec, 7596 /*AllowBoolConversions*/false); 7597 7598 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7599 if (LHS.isInvalid() || RHS.isInvalid()) 7600 return QualType(); 7601 7602 7603 if (compType.isNull() || !compType->isArithmeticType()) 7604 return InvalidOperands(Loc, LHS, RHS); 7605 if (IsDiv) 7606 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7607 return compType; 7608 } 7609 7610 QualType Sema::CheckRemainderOperands( 7611 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7612 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7613 7614 if (LHS.get()->getType()->isVectorType() || 7615 RHS.get()->getType()->isVectorType()) { 7616 if (LHS.get()->getType()->hasIntegerRepresentation() && 7617 RHS.get()->getType()->hasIntegerRepresentation()) 7618 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7619 /*AllowBothBool*/getLangOpts().AltiVec, 7620 /*AllowBoolConversions*/false); 7621 return InvalidOperands(Loc, LHS, RHS); 7622 } 7623 7624 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7625 if (LHS.isInvalid() || RHS.isInvalid()) 7626 return QualType(); 7627 7628 if (compType.isNull() || !compType->isIntegerType()) 7629 return InvalidOperands(Loc, LHS, RHS); 7630 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 7631 return compType; 7632 } 7633 7634 /// \brief Diagnose invalid arithmetic on two void pointers. 7635 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7636 Expr *LHSExpr, Expr *RHSExpr) { 7637 S.Diag(Loc, S.getLangOpts().CPlusPlus 7638 ? diag::err_typecheck_pointer_arith_void_type 7639 : diag::ext_gnu_void_ptr) 7640 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7641 << RHSExpr->getSourceRange(); 7642 } 7643 7644 /// \brief Diagnose invalid arithmetic on a void pointer. 7645 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7646 Expr *Pointer) { 7647 S.Diag(Loc, S.getLangOpts().CPlusPlus 7648 ? diag::err_typecheck_pointer_arith_void_type 7649 : diag::ext_gnu_void_ptr) 7650 << 0 /* one pointer */ << Pointer->getSourceRange(); 7651 } 7652 7653 /// \brief Diagnose invalid arithmetic on two function pointers. 7654 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7655 Expr *LHS, Expr *RHS) { 7656 assert(LHS->getType()->isAnyPointerType()); 7657 assert(RHS->getType()->isAnyPointerType()); 7658 S.Diag(Loc, S.getLangOpts().CPlusPlus 7659 ? diag::err_typecheck_pointer_arith_function_type 7660 : diag::ext_gnu_ptr_func_arith) 7661 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7662 // We only show the second type if it differs from the first. 7663 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7664 RHS->getType()) 7665 << RHS->getType()->getPointeeType() 7666 << LHS->getSourceRange() << RHS->getSourceRange(); 7667 } 7668 7669 /// \brief Diagnose invalid arithmetic on a function pointer. 7670 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7671 Expr *Pointer) { 7672 assert(Pointer->getType()->isAnyPointerType()); 7673 S.Diag(Loc, S.getLangOpts().CPlusPlus 7674 ? diag::err_typecheck_pointer_arith_function_type 7675 : diag::ext_gnu_ptr_func_arith) 7676 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7677 << 0 /* one pointer, so only one type */ 7678 << Pointer->getSourceRange(); 7679 } 7680 7681 /// \brief Emit error if Operand is incomplete pointer type 7682 /// 7683 /// \returns True if pointer has incomplete type 7684 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7685 Expr *Operand) { 7686 QualType ResType = Operand->getType(); 7687 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7688 ResType = ResAtomicType->getValueType(); 7689 7690 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7691 QualType PointeeTy = ResType->getPointeeType(); 7692 return S.RequireCompleteType(Loc, PointeeTy, 7693 diag::err_typecheck_arithmetic_incomplete_type, 7694 PointeeTy, Operand->getSourceRange()); 7695 } 7696 7697 /// \brief Check the validity of an arithmetic pointer operand. 7698 /// 7699 /// If the operand has pointer type, this code will check for pointer types 7700 /// which are invalid in arithmetic operations. These will be diagnosed 7701 /// appropriately, including whether or not the use is supported as an 7702 /// extension. 7703 /// 7704 /// \returns True when the operand is valid to use (even if as an extension). 7705 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7706 Expr *Operand) { 7707 QualType ResType = Operand->getType(); 7708 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7709 ResType = ResAtomicType->getValueType(); 7710 7711 if (!ResType->isAnyPointerType()) return true; 7712 7713 QualType PointeeTy = ResType->getPointeeType(); 7714 if (PointeeTy->isVoidType()) { 7715 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7716 return !S.getLangOpts().CPlusPlus; 7717 } 7718 if (PointeeTy->isFunctionType()) { 7719 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7720 return !S.getLangOpts().CPlusPlus; 7721 } 7722 7723 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7724 7725 return true; 7726 } 7727 7728 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7729 /// operands. 7730 /// 7731 /// This routine will diagnose any invalid arithmetic on pointer operands much 7732 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7733 /// for emitting a single diagnostic even for operations where both LHS and RHS 7734 /// are (potentially problematic) pointers. 7735 /// 7736 /// \returns True when the operand is valid to use (even if as an extension). 7737 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7738 Expr *LHSExpr, Expr *RHSExpr) { 7739 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7740 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7741 if (!isLHSPointer && !isRHSPointer) return true; 7742 7743 QualType LHSPointeeTy, RHSPointeeTy; 7744 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7745 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7746 7747 // if both are pointers check if operation is valid wrt address spaces 7748 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 7749 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 7750 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 7751 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 7752 S.Diag(Loc, 7753 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7754 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 7755 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7756 return false; 7757 } 7758 } 7759 7760 // Check for arithmetic on pointers to incomplete types. 7761 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7762 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7763 if (isLHSVoidPtr || isRHSVoidPtr) { 7764 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7765 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7766 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7767 7768 return !S.getLangOpts().CPlusPlus; 7769 } 7770 7771 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7772 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7773 if (isLHSFuncPtr || isRHSFuncPtr) { 7774 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7775 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7776 RHSExpr); 7777 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7778 7779 return !S.getLangOpts().CPlusPlus; 7780 } 7781 7782 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7783 return false; 7784 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7785 return false; 7786 7787 return true; 7788 } 7789 7790 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7791 /// literal. 7792 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7793 Expr *LHSExpr, Expr *RHSExpr) { 7794 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7795 Expr* IndexExpr = RHSExpr; 7796 if (!StrExpr) { 7797 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7798 IndexExpr = LHSExpr; 7799 } 7800 7801 bool IsStringPlusInt = StrExpr && 7802 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7803 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 7804 return; 7805 7806 llvm::APSInt index; 7807 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7808 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7809 if (index.isNonNegative() && 7810 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7811 index.isUnsigned())) 7812 return; 7813 } 7814 7815 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7816 Self.Diag(OpLoc, diag::warn_string_plus_int) 7817 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7818 7819 // Only print a fixit for "str" + int, not for int + "str". 7820 if (IndexExpr == RHSExpr) { 7821 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7822 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7823 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7824 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7825 << FixItHint::CreateInsertion(EndLoc, "]"); 7826 } else 7827 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7828 } 7829 7830 /// \brief Emit a warning when adding a char literal to a string. 7831 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7832 Expr *LHSExpr, Expr *RHSExpr) { 7833 const Expr *StringRefExpr = LHSExpr; 7834 const CharacterLiteral *CharExpr = 7835 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7836 7837 if (!CharExpr) { 7838 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7839 StringRefExpr = RHSExpr; 7840 } 7841 7842 if (!CharExpr || !StringRefExpr) 7843 return; 7844 7845 const QualType StringType = StringRefExpr->getType(); 7846 7847 // Return if not a PointerType. 7848 if (!StringType->isAnyPointerType()) 7849 return; 7850 7851 // Return if not a CharacterType. 7852 if (!StringType->getPointeeType()->isAnyCharacterType()) 7853 return; 7854 7855 ASTContext &Ctx = Self.getASTContext(); 7856 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7857 7858 const QualType CharType = CharExpr->getType(); 7859 if (!CharType->isAnyCharacterType() && 7860 CharType->isIntegerType() && 7861 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7862 Self.Diag(OpLoc, diag::warn_string_plus_char) 7863 << DiagRange << Ctx.CharTy; 7864 } else { 7865 Self.Diag(OpLoc, diag::warn_string_plus_char) 7866 << DiagRange << CharExpr->getType(); 7867 } 7868 7869 // Only print a fixit for str + char, not for char + str. 7870 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7871 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7872 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7873 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7874 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7875 << FixItHint::CreateInsertion(EndLoc, "]"); 7876 } else { 7877 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7878 } 7879 } 7880 7881 /// \brief Emit error when two pointers are incompatible. 7882 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7883 Expr *LHSExpr, Expr *RHSExpr) { 7884 assert(LHSExpr->getType()->isAnyPointerType()); 7885 assert(RHSExpr->getType()->isAnyPointerType()); 7886 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7887 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7888 << RHSExpr->getSourceRange(); 7889 } 7890 7891 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7892 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7893 QualType* CompLHSTy) { 7894 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7895 7896 if (LHS.get()->getType()->isVectorType() || 7897 RHS.get()->getType()->isVectorType()) { 7898 QualType compType = CheckVectorOperands( 7899 LHS, RHS, Loc, CompLHSTy, 7900 /*AllowBothBool*/getLangOpts().AltiVec, 7901 /*AllowBoolConversions*/getLangOpts().ZVector); 7902 if (CompLHSTy) *CompLHSTy = compType; 7903 return compType; 7904 } 7905 7906 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7907 if (LHS.isInvalid() || RHS.isInvalid()) 7908 return QualType(); 7909 7910 // Diagnose "string literal" '+' int and string '+' "char literal". 7911 if (Opc == BO_Add) { 7912 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7913 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7914 } 7915 7916 // handle the common case first (both operands are arithmetic). 7917 if (!compType.isNull() && compType->isArithmeticType()) { 7918 if (CompLHSTy) *CompLHSTy = compType; 7919 return compType; 7920 } 7921 7922 // Type-checking. Ultimately the pointer's going to be in PExp; 7923 // note that we bias towards the LHS being the pointer. 7924 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7925 7926 bool isObjCPointer; 7927 if (PExp->getType()->isPointerType()) { 7928 isObjCPointer = false; 7929 } else if (PExp->getType()->isObjCObjectPointerType()) { 7930 isObjCPointer = true; 7931 } else { 7932 std::swap(PExp, IExp); 7933 if (PExp->getType()->isPointerType()) { 7934 isObjCPointer = false; 7935 } else if (PExp->getType()->isObjCObjectPointerType()) { 7936 isObjCPointer = true; 7937 } else { 7938 return InvalidOperands(Loc, LHS, RHS); 7939 } 7940 } 7941 assert(PExp->getType()->isAnyPointerType()); 7942 7943 if (!IExp->getType()->isIntegerType()) 7944 return InvalidOperands(Loc, LHS, RHS); 7945 7946 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7947 return QualType(); 7948 7949 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7950 return QualType(); 7951 7952 // Check array bounds for pointer arithemtic 7953 CheckArrayAccess(PExp, IExp); 7954 7955 if (CompLHSTy) { 7956 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7957 if (LHSTy.isNull()) { 7958 LHSTy = LHS.get()->getType(); 7959 if (LHSTy->isPromotableIntegerType()) 7960 LHSTy = Context.getPromotedIntegerType(LHSTy); 7961 } 7962 *CompLHSTy = LHSTy; 7963 } 7964 7965 return PExp->getType(); 7966 } 7967 7968 // C99 6.5.6 7969 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7970 SourceLocation Loc, 7971 QualType* CompLHSTy) { 7972 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7973 7974 if (LHS.get()->getType()->isVectorType() || 7975 RHS.get()->getType()->isVectorType()) { 7976 QualType compType = CheckVectorOperands( 7977 LHS, RHS, Loc, CompLHSTy, 7978 /*AllowBothBool*/getLangOpts().AltiVec, 7979 /*AllowBoolConversions*/getLangOpts().ZVector); 7980 if (CompLHSTy) *CompLHSTy = compType; 7981 return compType; 7982 } 7983 7984 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7985 if (LHS.isInvalid() || RHS.isInvalid()) 7986 return QualType(); 7987 7988 // Enforce type constraints: C99 6.5.6p3. 7989 7990 // Handle the common case first (both operands are arithmetic). 7991 if (!compType.isNull() && compType->isArithmeticType()) { 7992 if (CompLHSTy) *CompLHSTy = compType; 7993 return compType; 7994 } 7995 7996 // Either ptr - int or ptr - ptr. 7997 if (LHS.get()->getType()->isAnyPointerType()) { 7998 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7999 8000 // Diagnose bad cases where we step over interface counts. 8001 if (LHS.get()->getType()->isObjCObjectPointerType() && 8002 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8003 return QualType(); 8004 8005 // The result type of a pointer-int computation is the pointer type. 8006 if (RHS.get()->getType()->isIntegerType()) { 8007 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8008 return QualType(); 8009 8010 // Check array bounds for pointer arithemtic 8011 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8012 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8013 8014 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8015 return LHS.get()->getType(); 8016 } 8017 8018 // Handle pointer-pointer subtractions. 8019 if (const PointerType *RHSPTy 8020 = RHS.get()->getType()->getAs<PointerType>()) { 8021 QualType rpointee = RHSPTy->getPointeeType(); 8022 8023 if (getLangOpts().CPlusPlus) { 8024 // Pointee types must be the same: C++ [expr.add] 8025 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8026 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8027 } 8028 } else { 8029 // Pointee types must be compatible C99 6.5.6p3 8030 if (!Context.typesAreCompatible( 8031 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8032 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8033 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8034 return QualType(); 8035 } 8036 } 8037 8038 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8039 LHS.get(), RHS.get())) 8040 return QualType(); 8041 8042 // The pointee type may have zero size. As an extension, a structure or 8043 // union may have zero size or an array may have zero length. In this 8044 // case subtraction does not make sense. 8045 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8046 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8047 if (ElementSize.isZero()) { 8048 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8049 << rpointee.getUnqualifiedType() 8050 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8051 } 8052 } 8053 8054 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8055 return Context.getPointerDiffType(); 8056 } 8057 } 8058 8059 return InvalidOperands(Loc, LHS, RHS); 8060 } 8061 8062 static bool isScopedEnumerationType(QualType T) { 8063 if (const EnumType *ET = T->getAs<EnumType>()) 8064 return ET->getDecl()->isScoped(); 8065 return false; 8066 } 8067 8068 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8069 SourceLocation Loc, unsigned Opc, 8070 QualType LHSType) { 8071 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8072 // so skip remaining warnings as we don't want to modify values within Sema. 8073 if (S.getLangOpts().OpenCL) 8074 return; 8075 8076 llvm::APSInt Right; 8077 // Check right/shifter operand 8078 if (RHS.get()->isValueDependent() || 8079 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8080 return; 8081 8082 if (Right.isNegative()) { 8083 S.DiagRuntimeBehavior(Loc, RHS.get(), 8084 S.PDiag(diag::warn_shift_negative) 8085 << RHS.get()->getSourceRange()); 8086 return; 8087 } 8088 llvm::APInt LeftBits(Right.getBitWidth(), 8089 S.Context.getTypeSize(LHS.get()->getType())); 8090 if (Right.uge(LeftBits)) { 8091 S.DiagRuntimeBehavior(Loc, RHS.get(), 8092 S.PDiag(diag::warn_shift_gt_typewidth) 8093 << RHS.get()->getSourceRange()); 8094 return; 8095 } 8096 if (Opc != BO_Shl) 8097 return; 8098 8099 // When left shifting an ICE which is signed, we can check for overflow which 8100 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8101 // integers have defined behavior modulo one more than the maximum value 8102 // representable in the result type, so never warn for those. 8103 llvm::APSInt Left; 8104 if (LHS.get()->isValueDependent() || 8105 LHSType->hasUnsignedIntegerRepresentation() || 8106 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8107 return; 8108 8109 // If LHS does not have a signed type and non-negative value 8110 // then, the behavior is undefined. Warn about it. 8111 if (Left.isNegative()) { 8112 S.DiagRuntimeBehavior(Loc, LHS.get(), 8113 S.PDiag(diag::warn_shift_lhs_negative) 8114 << LHS.get()->getSourceRange()); 8115 return; 8116 } 8117 8118 llvm::APInt ResultBits = 8119 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8120 if (LeftBits.uge(ResultBits)) 8121 return; 8122 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8123 Result = Result.shl(Right); 8124 8125 // Print the bit representation of the signed integer as an unsigned 8126 // hexadecimal number. 8127 SmallString<40> HexResult; 8128 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8129 8130 // If we are only missing a sign bit, this is less likely to result in actual 8131 // bugs -- if the result is cast back to an unsigned type, it will have the 8132 // expected value. Thus we place this behind a different warning that can be 8133 // turned off separately if needed. 8134 if (LeftBits == ResultBits - 1) { 8135 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8136 << HexResult << LHSType 8137 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8138 return; 8139 } 8140 8141 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8142 << HexResult.str() << Result.getMinSignedBits() << LHSType 8143 << Left.getBitWidth() << LHS.get()->getSourceRange() 8144 << RHS.get()->getSourceRange(); 8145 } 8146 8147 /// \brief Return the resulting type when an OpenCL vector is shifted 8148 /// by a scalar or vector shift amount. 8149 static QualType checkOpenCLVectorShift(Sema &S, 8150 ExprResult &LHS, ExprResult &RHS, 8151 SourceLocation Loc, bool IsCompAssign) { 8152 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8153 if (!LHS.get()->getType()->isVectorType()) { 8154 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8155 << RHS.get()->getType() << LHS.get()->getType() 8156 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8157 return QualType(); 8158 } 8159 8160 if (!IsCompAssign) { 8161 LHS = S.UsualUnaryConversions(LHS.get()); 8162 if (LHS.isInvalid()) return QualType(); 8163 } 8164 8165 RHS = S.UsualUnaryConversions(RHS.get()); 8166 if (RHS.isInvalid()) return QualType(); 8167 8168 QualType LHSType = LHS.get()->getType(); 8169 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8170 QualType LHSEleType = LHSVecTy->getElementType(); 8171 8172 // Note that RHS might not be a vector. 8173 QualType RHSType = RHS.get()->getType(); 8174 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8175 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8176 8177 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8178 if (!LHSEleType->isIntegerType()) { 8179 S.Diag(Loc, diag::err_typecheck_expect_int) 8180 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8181 return QualType(); 8182 } 8183 8184 if (!RHSEleType->isIntegerType()) { 8185 S.Diag(Loc, diag::err_typecheck_expect_int) 8186 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8187 return QualType(); 8188 } 8189 8190 if (RHSVecTy) { 8191 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8192 // are applied component-wise. So if RHS is a vector, then ensure 8193 // that the number of elements is the same as LHS... 8194 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8195 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8196 << LHS.get()->getType() << RHS.get()->getType() 8197 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8198 return QualType(); 8199 } 8200 } else { 8201 // ...else expand RHS to match the number of elements in LHS. 8202 QualType VecTy = 8203 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8204 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8205 } 8206 8207 return LHSType; 8208 } 8209 8210 // C99 6.5.7 8211 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8212 SourceLocation Loc, unsigned Opc, 8213 bool IsCompAssign) { 8214 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8215 8216 // Vector shifts promote their scalar inputs to vector type. 8217 if (LHS.get()->getType()->isVectorType() || 8218 RHS.get()->getType()->isVectorType()) { 8219 if (LangOpts.OpenCL) 8220 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8221 if (LangOpts.ZVector) { 8222 // The shift operators for the z vector extensions work basically 8223 // like OpenCL shifts, except that neither the LHS nor the RHS is 8224 // allowed to be a "vector bool". 8225 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8226 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8227 return InvalidOperands(Loc, LHS, RHS); 8228 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8229 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8230 return InvalidOperands(Loc, LHS, RHS); 8231 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8232 } 8233 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8234 /*AllowBothBool*/true, 8235 /*AllowBoolConversions*/false); 8236 } 8237 8238 // Shifts don't perform usual arithmetic conversions, they just do integer 8239 // promotions on each operand. C99 6.5.7p3 8240 8241 // For the LHS, do usual unary conversions, but then reset them away 8242 // if this is a compound assignment. 8243 ExprResult OldLHS = LHS; 8244 LHS = UsualUnaryConversions(LHS.get()); 8245 if (LHS.isInvalid()) 8246 return QualType(); 8247 QualType LHSType = LHS.get()->getType(); 8248 if (IsCompAssign) LHS = OldLHS; 8249 8250 // The RHS is simpler. 8251 RHS = UsualUnaryConversions(RHS.get()); 8252 if (RHS.isInvalid()) 8253 return QualType(); 8254 QualType RHSType = RHS.get()->getType(); 8255 8256 // C99 6.5.7p2: Each of the operands shall have integer type. 8257 if (!LHSType->hasIntegerRepresentation() || 8258 !RHSType->hasIntegerRepresentation()) 8259 return InvalidOperands(Loc, LHS, RHS); 8260 8261 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8262 // hasIntegerRepresentation() above instead of this. 8263 if (isScopedEnumerationType(LHSType) || 8264 isScopedEnumerationType(RHSType)) { 8265 return InvalidOperands(Loc, LHS, RHS); 8266 } 8267 // Sanity-check shift operands 8268 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8269 8270 // "The type of the result is that of the promoted left operand." 8271 return LHSType; 8272 } 8273 8274 static bool IsWithinTemplateSpecialization(Decl *D) { 8275 if (DeclContext *DC = D->getDeclContext()) { 8276 if (isa<ClassTemplateSpecializationDecl>(DC)) 8277 return true; 8278 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8279 return FD->isFunctionTemplateSpecialization(); 8280 } 8281 return false; 8282 } 8283 8284 /// If two different enums are compared, raise a warning. 8285 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8286 Expr *RHS) { 8287 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8288 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8289 8290 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8291 if (!LHSEnumType) 8292 return; 8293 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8294 if (!RHSEnumType) 8295 return; 8296 8297 // Ignore anonymous enums. 8298 if (!LHSEnumType->getDecl()->getIdentifier()) 8299 return; 8300 if (!RHSEnumType->getDecl()->getIdentifier()) 8301 return; 8302 8303 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8304 return; 8305 8306 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8307 << LHSStrippedType << RHSStrippedType 8308 << LHS->getSourceRange() << RHS->getSourceRange(); 8309 } 8310 8311 /// \brief Diagnose bad pointer comparisons. 8312 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8313 ExprResult &LHS, ExprResult &RHS, 8314 bool IsError) { 8315 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8316 : diag::ext_typecheck_comparison_of_distinct_pointers) 8317 << LHS.get()->getType() << RHS.get()->getType() 8318 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8319 } 8320 8321 /// \brief Returns false if the pointers are converted to a composite type, 8322 /// true otherwise. 8323 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8324 ExprResult &LHS, ExprResult &RHS) { 8325 // C++ [expr.rel]p2: 8326 // [...] Pointer conversions (4.10) and qualification 8327 // conversions (4.4) are performed on pointer operands (or on 8328 // a pointer operand and a null pointer constant) to bring 8329 // them to their composite pointer type. [...] 8330 // 8331 // C++ [expr.eq]p1 uses the same notion for (in)equality 8332 // comparisons of pointers. 8333 8334 // C++ [expr.eq]p2: 8335 // In addition, pointers to members can be compared, or a pointer to 8336 // member and a null pointer constant. Pointer to member conversions 8337 // (4.11) and qualification conversions (4.4) are performed to bring 8338 // them to a common type. If one operand is a null pointer constant, 8339 // the common type is the type of the other operand. Otherwise, the 8340 // common type is a pointer to member type similar (4.4) to the type 8341 // of one of the operands, with a cv-qualification signature (4.4) 8342 // that is the union of the cv-qualification signatures of the operand 8343 // types. 8344 8345 QualType LHSType = LHS.get()->getType(); 8346 QualType RHSType = RHS.get()->getType(); 8347 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8348 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8349 8350 bool NonStandardCompositeType = false; 8351 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8352 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8353 if (T.isNull()) { 8354 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8355 return true; 8356 } 8357 8358 if (NonStandardCompositeType) 8359 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8360 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8361 << RHS.get()->getSourceRange(); 8362 8363 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8364 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8365 return false; 8366 } 8367 8368 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8369 ExprResult &LHS, 8370 ExprResult &RHS, 8371 bool IsError) { 8372 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8373 : diag::ext_typecheck_comparison_of_fptr_to_void) 8374 << LHS.get()->getType() << RHS.get()->getType() 8375 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8376 } 8377 8378 static bool isObjCObjectLiteral(ExprResult &E) { 8379 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8380 case Stmt::ObjCArrayLiteralClass: 8381 case Stmt::ObjCDictionaryLiteralClass: 8382 case Stmt::ObjCStringLiteralClass: 8383 case Stmt::ObjCBoxedExprClass: 8384 return true; 8385 default: 8386 // Note that ObjCBoolLiteral is NOT an object literal! 8387 return false; 8388 } 8389 } 8390 8391 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8392 const ObjCObjectPointerType *Type = 8393 LHS->getType()->getAs<ObjCObjectPointerType>(); 8394 8395 // If this is not actually an Objective-C object, bail out. 8396 if (!Type) 8397 return false; 8398 8399 // Get the LHS object's interface type. 8400 QualType InterfaceType = Type->getPointeeType(); 8401 8402 // If the RHS isn't an Objective-C object, bail out. 8403 if (!RHS->getType()->isObjCObjectPointerType()) 8404 return false; 8405 8406 // Try to find the -isEqual: method. 8407 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8408 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8409 InterfaceType, 8410 /*instance=*/true); 8411 if (!Method) { 8412 if (Type->isObjCIdType()) { 8413 // For 'id', just check the global pool. 8414 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8415 /*receiverId=*/true); 8416 } else { 8417 // Check protocols. 8418 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8419 /*instance=*/true); 8420 } 8421 } 8422 8423 if (!Method) 8424 return false; 8425 8426 QualType T = Method->parameters()[0]->getType(); 8427 if (!T->isObjCObjectPointerType()) 8428 return false; 8429 8430 QualType R = Method->getReturnType(); 8431 if (!R->isScalarType()) 8432 return false; 8433 8434 return true; 8435 } 8436 8437 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8438 FromE = FromE->IgnoreParenImpCasts(); 8439 switch (FromE->getStmtClass()) { 8440 default: 8441 break; 8442 case Stmt::ObjCStringLiteralClass: 8443 // "string literal" 8444 return LK_String; 8445 case Stmt::ObjCArrayLiteralClass: 8446 // "array literal" 8447 return LK_Array; 8448 case Stmt::ObjCDictionaryLiteralClass: 8449 // "dictionary literal" 8450 return LK_Dictionary; 8451 case Stmt::BlockExprClass: 8452 return LK_Block; 8453 case Stmt::ObjCBoxedExprClass: { 8454 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8455 switch (Inner->getStmtClass()) { 8456 case Stmt::IntegerLiteralClass: 8457 case Stmt::FloatingLiteralClass: 8458 case Stmt::CharacterLiteralClass: 8459 case Stmt::ObjCBoolLiteralExprClass: 8460 case Stmt::CXXBoolLiteralExprClass: 8461 // "numeric literal" 8462 return LK_Numeric; 8463 case Stmt::ImplicitCastExprClass: { 8464 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8465 // Boolean literals can be represented by implicit casts. 8466 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8467 return LK_Numeric; 8468 break; 8469 } 8470 default: 8471 break; 8472 } 8473 return LK_Boxed; 8474 } 8475 } 8476 return LK_None; 8477 } 8478 8479 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8480 ExprResult &LHS, ExprResult &RHS, 8481 BinaryOperator::Opcode Opc){ 8482 Expr *Literal; 8483 Expr *Other; 8484 if (isObjCObjectLiteral(LHS)) { 8485 Literal = LHS.get(); 8486 Other = RHS.get(); 8487 } else { 8488 Literal = RHS.get(); 8489 Other = LHS.get(); 8490 } 8491 8492 // Don't warn on comparisons against nil. 8493 Other = Other->IgnoreParenCasts(); 8494 if (Other->isNullPointerConstant(S.getASTContext(), 8495 Expr::NPC_ValueDependentIsNotNull)) 8496 return; 8497 8498 // This should be kept in sync with warn_objc_literal_comparison. 8499 // LK_String should always be after the other literals, since it has its own 8500 // warning flag. 8501 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8502 assert(LiteralKind != Sema::LK_Block); 8503 if (LiteralKind == Sema::LK_None) { 8504 llvm_unreachable("Unknown Objective-C object literal kind"); 8505 } 8506 8507 if (LiteralKind == Sema::LK_String) 8508 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8509 << Literal->getSourceRange(); 8510 else 8511 S.Diag(Loc, diag::warn_objc_literal_comparison) 8512 << LiteralKind << Literal->getSourceRange(); 8513 8514 if (BinaryOperator::isEqualityOp(Opc) && 8515 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8516 SourceLocation Start = LHS.get()->getLocStart(); 8517 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 8518 CharSourceRange OpRange = 8519 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 8520 8521 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8522 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8523 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8524 << FixItHint::CreateInsertion(End, "]"); 8525 } 8526 } 8527 8528 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8529 ExprResult &RHS, 8530 SourceLocation Loc, 8531 unsigned OpaqueOpc) { 8532 // Check that left hand side is !something. 8533 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8534 if (!UO || UO->getOpcode() != UO_LNot) return; 8535 8536 // Only check if the right hand side is non-bool arithmetic type. 8537 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8538 8539 // Make sure that the something in !something is not bool. 8540 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8541 if (SubExpr->isKnownToHaveBooleanValue()) return; 8542 8543 // Emit warning. 8544 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8545 << Loc; 8546 8547 // First note suggest !(x < y) 8548 SourceLocation FirstOpen = SubExpr->getLocStart(); 8549 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8550 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 8551 if (FirstClose.isInvalid()) 8552 FirstOpen = SourceLocation(); 8553 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8554 << FixItHint::CreateInsertion(FirstOpen, "(") 8555 << FixItHint::CreateInsertion(FirstClose, ")"); 8556 8557 // Second note suggests (!x) < y 8558 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8559 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8560 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 8561 if (SecondClose.isInvalid()) 8562 SecondOpen = SourceLocation(); 8563 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8564 << FixItHint::CreateInsertion(SecondOpen, "(") 8565 << FixItHint::CreateInsertion(SecondClose, ")"); 8566 } 8567 8568 // Get the decl for a simple expression: a reference to a variable, 8569 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8570 static ValueDecl *getCompareDecl(Expr *E) { 8571 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8572 return DR->getDecl(); 8573 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8574 if (Ivar->isFreeIvar()) 8575 return Ivar->getDecl(); 8576 } 8577 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8578 if (Mem->isImplicitAccess()) 8579 return Mem->getMemberDecl(); 8580 } 8581 return nullptr; 8582 } 8583 8584 // C99 6.5.8, C++ [expr.rel] 8585 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8586 SourceLocation Loc, unsigned OpaqueOpc, 8587 bool IsRelational) { 8588 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8589 8590 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 8591 8592 // Handle vector comparisons separately. 8593 if (LHS.get()->getType()->isVectorType() || 8594 RHS.get()->getType()->isVectorType()) 8595 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8596 8597 QualType LHSType = LHS.get()->getType(); 8598 QualType RHSType = RHS.get()->getType(); 8599 8600 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8601 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8602 8603 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8604 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 8605 8606 if (!LHSType->hasFloatingRepresentation() && 8607 !(LHSType->isBlockPointerType() && IsRelational) && 8608 !LHS.get()->getLocStart().isMacroID() && 8609 !RHS.get()->getLocStart().isMacroID() && 8610 ActiveTemplateInstantiations.empty()) { 8611 // For non-floating point types, check for self-comparisons of the form 8612 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8613 // often indicate logic errors in the program. 8614 // 8615 // NOTE: Don't warn about comparison expressions resulting from macro 8616 // expansion. Also don't warn about comparisons which are only self 8617 // comparisons within a template specialization. The warnings should catch 8618 // obvious cases in the definition of the template anyways. The idea is to 8619 // warn when the typed comparison operator will always evaluate to the same 8620 // result. 8621 ValueDecl *DL = getCompareDecl(LHSStripped); 8622 ValueDecl *DR = getCompareDecl(RHSStripped); 8623 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8624 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8625 << 0 // self- 8626 << (Opc == BO_EQ 8627 || Opc == BO_LE 8628 || Opc == BO_GE)); 8629 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8630 !DL->getType()->isReferenceType() && 8631 !DR->getType()->isReferenceType()) { 8632 // what is it always going to eval to? 8633 char always_evals_to; 8634 switch(Opc) { 8635 case BO_EQ: // e.g. array1 == array2 8636 always_evals_to = 0; // false 8637 break; 8638 case BO_NE: // e.g. array1 != array2 8639 always_evals_to = 1; // true 8640 break; 8641 default: 8642 // best we can say is 'a constant' 8643 always_evals_to = 2; // e.g. array1 <= array2 8644 break; 8645 } 8646 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8647 << 1 // array 8648 << always_evals_to); 8649 } 8650 8651 if (isa<CastExpr>(LHSStripped)) 8652 LHSStripped = LHSStripped->IgnoreParenCasts(); 8653 if (isa<CastExpr>(RHSStripped)) 8654 RHSStripped = RHSStripped->IgnoreParenCasts(); 8655 8656 // Warn about comparisons against a string constant (unless the other 8657 // operand is null), the user probably wants strcmp. 8658 Expr *literalString = nullptr; 8659 Expr *literalStringStripped = nullptr; 8660 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8661 !RHSStripped->isNullPointerConstant(Context, 8662 Expr::NPC_ValueDependentIsNull)) { 8663 literalString = LHS.get(); 8664 literalStringStripped = LHSStripped; 8665 } else if ((isa<StringLiteral>(RHSStripped) || 8666 isa<ObjCEncodeExpr>(RHSStripped)) && 8667 !LHSStripped->isNullPointerConstant(Context, 8668 Expr::NPC_ValueDependentIsNull)) { 8669 literalString = RHS.get(); 8670 literalStringStripped = RHSStripped; 8671 } 8672 8673 if (literalString) { 8674 DiagRuntimeBehavior(Loc, nullptr, 8675 PDiag(diag::warn_stringcompare) 8676 << isa<ObjCEncodeExpr>(literalStringStripped) 8677 << literalString->getSourceRange()); 8678 } 8679 } 8680 8681 // C99 6.5.8p3 / C99 6.5.9p4 8682 UsualArithmeticConversions(LHS, RHS); 8683 if (LHS.isInvalid() || RHS.isInvalid()) 8684 return QualType(); 8685 8686 LHSType = LHS.get()->getType(); 8687 RHSType = RHS.get()->getType(); 8688 8689 // The result of comparisons is 'bool' in C++, 'int' in C. 8690 QualType ResultTy = Context.getLogicalOperationType(); 8691 8692 if (IsRelational) { 8693 if (LHSType->isRealType() && RHSType->isRealType()) 8694 return ResultTy; 8695 } else { 8696 // Check for comparisons of floating point operands using != and ==. 8697 if (LHSType->hasFloatingRepresentation()) 8698 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8699 8700 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8701 return ResultTy; 8702 } 8703 8704 const Expr::NullPointerConstantKind LHSNullKind = 8705 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8706 const Expr::NullPointerConstantKind RHSNullKind = 8707 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8708 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8709 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8710 8711 if (!IsRelational && LHSIsNull != RHSIsNull) { 8712 bool IsEquality = Opc == BO_EQ; 8713 if (RHSIsNull) 8714 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 8715 RHS.get()->getSourceRange()); 8716 else 8717 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 8718 LHS.get()->getSourceRange()); 8719 } 8720 8721 // All of the following pointer-related warnings are GCC extensions, except 8722 // when handling null pointer constants. 8723 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 8724 QualType LCanPointeeTy = 8725 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8726 QualType RCanPointeeTy = 8727 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8728 8729 if (getLangOpts().CPlusPlus) { 8730 if (LCanPointeeTy == RCanPointeeTy) 8731 return ResultTy; 8732 if (!IsRelational && 8733 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8734 // Valid unless comparison between non-null pointer and function pointer 8735 // This is a gcc extension compatibility comparison. 8736 // In a SFINAE context, we treat this as a hard error to maintain 8737 // conformance with the C++ standard. 8738 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8739 && !LHSIsNull && !RHSIsNull) { 8740 diagnoseFunctionPointerToVoidComparison( 8741 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8742 8743 if (isSFINAEContext()) 8744 return QualType(); 8745 8746 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8747 return ResultTy; 8748 } 8749 } 8750 8751 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8752 return QualType(); 8753 else 8754 return ResultTy; 8755 } 8756 // C99 6.5.9p2 and C99 6.5.8p2 8757 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8758 RCanPointeeTy.getUnqualifiedType())) { 8759 // Valid unless a relational comparison of function pointers 8760 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8761 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8762 << LHSType << RHSType << LHS.get()->getSourceRange() 8763 << RHS.get()->getSourceRange(); 8764 } 8765 } else if (!IsRelational && 8766 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8767 // Valid unless comparison between non-null pointer and function pointer 8768 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8769 && !LHSIsNull && !RHSIsNull) 8770 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8771 /*isError*/false); 8772 } else { 8773 // Invalid 8774 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8775 } 8776 if (LCanPointeeTy != RCanPointeeTy) { 8777 if (getLangOpts().OpenCL) { 8778 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 8779 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 8780 Diag(Loc, 8781 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8782 << LHSType << RHSType << 0 /* comparison */ 8783 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8784 } 8785 } 8786 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 8787 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 8788 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 8789 : CK_BitCast; 8790 if (LHSIsNull && !RHSIsNull) 8791 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 8792 else 8793 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 8794 } 8795 return ResultTy; 8796 } 8797 8798 if (getLangOpts().CPlusPlus) { 8799 // Comparison of nullptr_t with itself. 8800 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 8801 return ResultTy; 8802 8803 // Comparison of pointers with null pointer constants and equality 8804 // comparisons of member pointers to null pointer constants. 8805 if (RHSIsNull && 8806 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 8807 (!IsRelational && 8808 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 8809 RHS = ImpCastExprToType(RHS.get(), LHSType, 8810 LHSType->isMemberPointerType() 8811 ? CK_NullToMemberPointer 8812 : CK_NullToPointer); 8813 return ResultTy; 8814 } 8815 if (LHSIsNull && 8816 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 8817 (!IsRelational && 8818 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 8819 LHS = ImpCastExprToType(LHS.get(), RHSType, 8820 RHSType->isMemberPointerType() 8821 ? CK_NullToMemberPointer 8822 : CK_NullToPointer); 8823 return ResultTy; 8824 } 8825 8826 // Comparison of member pointers. 8827 if (!IsRelational && 8828 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 8829 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8830 return QualType(); 8831 else 8832 return ResultTy; 8833 } 8834 8835 // Handle scoped enumeration types specifically, since they don't promote 8836 // to integers. 8837 if (LHS.get()->getType()->isEnumeralType() && 8838 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8839 RHS.get()->getType())) 8840 return ResultTy; 8841 } 8842 8843 // Handle block pointer types. 8844 if (!IsRelational && LHSType->isBlockPointerType() && 8845 RHSType->isBlockPointerType()) { 8846 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8847 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8848 8849 if (!LHSIsNull && !RHSIsNull && 8850 !Context.typesAreCompatible(lpointee, rpointee)) { 8851 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8852 << LHSType << RHSType << LHS.get()->getSourceRange() 8853 << RHS.get()->getSourceRange(); 8854 } 8855 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8856 return ResultTy; 8857 } 8858 8859 // Allow block pointers to be compared with null pointer constants. 8860 if (!IsRelational 8861 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8862 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8863 if (!LHSIsNull && !RHSIsNull) { 8864 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8865 ->getPointeeType()->isVoidType()) 8866 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8867 ->getPointeeType()->isVoidType()))) 8868 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8869 << LHSType << RHSType << LHS.get()->getSourceRange() 8870 << RHS.get()->getSourceRange(); 8871 } 8872 if (LHSIsNull && !RHSIsNull) 8873 LHS = ImpCastExprToType(LHS.get(), RHSType, 8874 RHSType->isPointerType() ? CK_BitCast 8875 : CK_AnyPointerToBlockPointerCast); 8876 else 8877 RHS = ImpCastExprToType(RHS.get(), LHSType, 8878 LHSType->isPointerType() ? CK_BitCast 8879 : CK_AnyPointerToBlockPointerCast); 8880 return ResultTy; 8881 } 8882 8883 if (LHSType->isObjCObjectPointerType() || 8884 RHSType->isObjCObjectPointerType()) { 8885 const PointerType *LPT = LHSType->getAs<PointerType>(); 8886 const PointerType *RPT = RHSType->getAs<PointerType>(); 8887 if (LPT || RPT) { 8888 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8889 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8890 8891 if (!LPtrToVoid && !RPtrToVoid && 8892 !Context.typesAreCompatible(LHSType, RHSType)) { 8893 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8894 /*isError*/false); 8895 } 8896 if (LHSIsNull && !RHSIsNull) { 8897 Expr *E = LHS.get(); 8898 if (getLangOpts().ObjCAutoRefCount) 8899 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8900 LHS = ImpCastExprToType(E, RHSType, 8901 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8902 } 8903 else { 8904 Expr *E = RHS.get(); 8905 if (getLangOpts().ObjCAutoRefCount) 8906 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false, 8907 Opc); 8908 RHS = ImpCastExprToType(E, LHSType, 8909 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8910 } 8911 return ResultTy; 8912 } 8913 if (LHSType->isObjCObjectPointerType() && 8914 RHSType->isObjCObjectPointerType()) { 8915 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8916 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8917 /*isError*/false); 8918 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8919 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8920 8921 if (LHSIsNull && !RHSIsNull) 8922 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8923 else 8924 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8925 return ResultTy; 8926 } 8927 } 8928 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8929 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8930 unsigned DiagID = 0; 8931 bool isError = false; 8932 if (LangOpts.DebuggerSupport) { 8933 // Under a debugger, allow the comparison of pointers to integers, 8934 // since users tend to want to compare addresses. 8935 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8936 (RHSIsNull && RHSType->isIntegerType())) { 8937 if (IsRelational && !getLangOpts().CPlusPlus) 8938 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8939 } else if (IsRelational && !getLangOpts().CPlusPlus) 8940 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8941 else if (getLangOpts().CPlusPlus) { 8942 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8943 isError = true; 8944 } else 8945 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8946 8947 if (DiagID) { 8948 Diag(Loc, DiagID) 8949 << LHSType << RHSType << LHS.get()->getSourceRange() 8950 << RHS.get()->getSourceRange(); 8951 if (isError) 8952 return QualType(); 8953 } 8954 8955 if (LHSType->isIntegerType()) 8956 LHS = ImpCastExprToType(LHS.get(), RHSType, 8957 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8958 else 8959 RHS = ImpCastExprToType(RHS.get(), LHSType, 8960 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8961 return ResultTy; 8962 } 8963 8964 // Handle block pointers. 8965 if (!IsRelational && RHSIsNull 8966 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8967 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8968 return ResultTy; 8969 } 8970 if (!IsRelational && LHSIsNull 8971 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8972 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 8973 return ResultTy; 8974 } 8975 8976 return InvalidOperands(Loc, LHS, RHS); 8977 } 8978 8979 8980 // Return a signed type that is of identical size and number of elements. 8981 // For floating point vectors, return an integer type of identical size 8982 // and number of elements. 8983 QualType Sema::GetSignedVectorType(QualType V) { 8984 const VectorType *VTy = V->getAs<VectorType>(); 8985 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8986 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8987 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8988 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8989 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8990 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8991 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8992 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8993 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8994 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8995 "Unhandled vector element size in vector compare"); 8996 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8997 } 8998 8999 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9000 /// operates on extended vector types. Instead of producing an IntTy result, 9001 /// like a scalar comparison, a vector comparison produces a vector of integer 9002 /// types. 9003 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9004 SourceLocation Loc, 9005 bool IsRelational) { 9006 // Check to make sure we're operating on vectors of the same type and width, 9007 // Allowing one side to be a scalar of element type. 9008 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9009 /*AllowBothBool*/true, 9010 /*AllowBoolConversions*/getLangOpts().ZVector); 9011 if (vType.isNull()) 9012 return vType; 9013 9014 QualType LHSType = LHS.get()->getType(); 9015 9016 // If AltiVec, the comparison results in a numeric type, i.e. 9017 // bool for C++, int for C 9018 if (getLangOpts().AltiVec && 9019 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9020 return Context.getLogicalOperationType(); 9021 9022 // For non-floating point types, check for self-comparisons of the form 9023 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9024 // often indicate logic errors in the program. 9025 if (!LHSType->hasFloatingRepresentation() && 9026 ActiveTemplateInstantiations.empty()) { 9027 if (DeclRefExpr* DRL 9028 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9029 if (DeclRefExpr* DRR 9030 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9031 if (DRL->getDecl() == DRR->getDecl()) 9032 DiagRuntimeBehavior(Loc, nullptr, 9033 PDiag(diag::warn_comparison_always) 9034 << 0 // self- 9035 << 2 // "a constant" 9036 ); 9037 } 9038 9039 // Check for comparisons of floating point operands using != and ==. 9040 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9041 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9042 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9043 } 9044 9045 // Return a signed type for the vector. 9046 return GetSignedVectorType(LHSType); 9047 } 9048 9049 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9050 SourceLocation Loc) { 9051 // Ensure that either both operands are of the same vector type, or 9052 // one operand is of a vector type and the other is of its element type. 9053 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9054 /*AllowBothBool*/true, 9055 /*AllowBoolConversions*/false); 9056 if (vType.isNull()) 9057 return InvalidOperands(Loc, LHS, RHS); 9058 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9059 vType->hasFloatingRepresentation()) 9060 return InvalidOperands(Loc, LHS, RHS); 9061 9062 return GetSignedVectorType(LHS.get()->getType()); 9063 } 9064 9065 inline QualType Sema::CheckBitwiseOperands( 9066 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9067 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9068 9069 if (LHS.get()->getType()->isVectorType() || 9070 RHS.get()->getType()->isVectorType()) { 9071 if (LHS.get()->getType()->hasIntegerRepresentation() && 9072 RHS.get()->getType()->hasIntegerRepresentation()) 9073 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9074 /*AllowBothBool*/true, 9075 /*AllowBoolConversions*/getLangOpts().ZVector); 9076 return InvalidOperands(Loc, LHS, RHS); 9077 } 9078 9079 ExprResult LHSResult = LHS, RHSResult = RHS; 9080 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9081 IsCompAssign); 9082 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9083 return QualType(); 9084 LHS = LHSResult.get(); 9085 RHS = RHSResult.get(); 9086 9087 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9088 return compType; 9089 return InvalidOperands(Loc, LHS, RHS); 9090 } 9091 9092 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 9093 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 9094 9095 // Check vector operands differently. 9096 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9097 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9098 9099 // Diagnose cases where the user write a logical and/or but probably meant a 9100 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9101 // is a constant. 9102 if (LHS.get()->getType()->isIntegerType() && 9103 !LHS.get()->getType()->isBooleanType() && 9104 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9105 // Don't warn in macros or template instantiations. 9106 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9107 // If the RHS can be constant folded, and if it constant folds to something 9108 // that isn't 0 or 1 (which indicate a potential logical operation that 9109 // happened to fold to true/false) then warn. 9110 // Parens on the RHS are ignored. 9111 llvm::APSInt Result; 9112 if (RHS.get()->EvaluateAsInt(Result, Context)) 9113 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9114 !RHS.get()->getExprLoc().isMacroID()) || 9115 (Result != 0 && Result != 1)) { 9116 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9117 << RHS.get()->getSourceRange() 9118 << (Opc == BO_LAnd ? "&&" : "||"); 9119 // Suggest replacing the logical operator with the bitwise version 9120 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9121 << (Opc == BO_LAnd ? "&" : "|") 9122 << FixItHint::CreateReplacement(SourceRange( 9123 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 9124 getLangOpts())), 9125 Opc == BO_LAnd ? "&" : "|"); 9126 if (Opc == BO_LAnd) 9127 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9128 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9129 << FixItHint::CreateRemoval( 9130 SourceRange( 9131 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 9132 0, getSourceManager(), 9133 getLangOpts()), 9134 RHS.get()->getLocEnd())); 9135 } 9136 } 9137 9138 if (!Context.getLangOpts().CPlusPlus) { 9139 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9140 // not operate on the built-in scalar and vector float types. 9141 if (Context.getLangOpts().OpenCL && 9142 Context.getLangOpts().OpenCLVersion < 120) { 9143 if (LHS.get()->getType()->isFloatingType() || 9144 RHS.get()->getType()->isFloatingType()) 9145 return InvalidOperands(Loc, LHS, RHS); 9146 } 9147 9148 LHS = UsualUnaryConversions(LHS.get()); 9149 if (LHS.isInvalid()) 9150 return QualType(); 9151 9152 RHS = UsualUnaryConversions(RHS.get()); 9153 if (RHS.isInvalid()) 9154 return QualType(); 9155 9156 if (!LHS.get()->getType()->isScalarType() || 9157 !RHS.get()->getType()->isScalarType()) 9158 return InvalidOperands(Loc, LHS, RHS); 9159 9160 return Context.IntTy; 9161 } 9162 9163 // The following is safe because we only use this method for 9164 // non-overloadable operands. 9165 9166 // C++ [expr.log.and]p1 9167 // C++ [expr.log.or]p1 9168 // The operands are both contextually converted to type bool. 9169 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9170 if (LHSRes.isInvalid()) 9171 return InvalidOperands(Loc, LHS, RHS); 9172 LHS = LHSRes; 9173 9174 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9175 if (RHSRes.isInvalid()) 9176 return InvalidOperands(Loc, LHS, RHS); 9177 RHS = RHSRes; 9178 9179 // C++ [expr.log.and]p2 9180 // C++ [expr.log.or]p2 9181 // The result is a bool. 9182 return Context.BoolTy; 9183 } 9184 9185 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9186 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9187 if (!ME) return false; 9188 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9189 ObjCMessageExpr *Base = 9190 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9191 if (!Base) return false; 9192 return Base->getMethodDecl() != nullptr; 9193 } 9194 9195 /// Is the given expression (which must be 'const') a reference to a 9196 /// variable which was originally non-const, but which has become 9197 /// 'const' due to being captured within a block? 9198 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9199 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9200 assert(E->isLValue() && E->getType().isConstQualified()); 9201 E = E->IgnoreParens(); 9202 9203 // Must be a reference to a declaration from an enclosing scope. 9204 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9205 if (!DRE) return NCCK_None; 9206 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9207 9208 // The declaration must be a variable which is not declared 'const'. 9209 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9210 if (!var) return NCCK_None; 9211 if (var->getType().isConstQualified()) return NCCK_None; 9212 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9213 9214 // Decide whether the first capture was for a block or a lambda. 9215 DeclContext *DC = S.CurContext, *Prev = nullptr; 9216 while (DC != var->getDeclContext()) { 9217 Prev = DC; 9218 DC = DC->getParent(); 9219 } 9220 // Unless we have an init-capture, we've gone one step too far. 9221 if (!var->isInitCapture()) 9222 DC = Prev; 9223 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9224 } 9225 9226 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9227 Ty = Ty.getNonReferenceType(); 9228 if (IsDereference && Ty->isPointerType()) 9229 Ty = Ty->getPointeeType(); 9230 return !Ty.isConstQualified(); 9231 } 9232 9233 /// Emit the "read-only variable not assignable" error and print notes to give 9234 /// more information about why the variable is not assignable, such as pointing 9235 /// to the declaration of a const variable, showing that a method is const, or 9236 /// that the function is returning a const reference. 9237 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9238 SourceLocation Loc) { 9239 // Update err_typecheck_assign_const and note_typecheck_assign_const 9240 // when this enum is changed. 9241 enum { 9242 ConstFunction, 9243 ConstVariable, 9244 ConstMember, 9245 ConstMethod, 9246 ConstUnknown, // Keep as last element 9247 }; 9248 9249 SourceRange ExprRange = E->getSourceRange(); 9250 9251 // Only emit one error on the first const found. All other consts will emit 9252 // a note to the error. 9253 bool DiagnosticEmitted = false; 9254 9255 // Track if the current expression is the result of a derefence, and if the 9256 // next checked expression is the result of a derefence. 9257 bool IsDereference = false; 9258 bool NextIsDereference = false; 9259 9260 // Loop to process MemberExpr chains. 9261 while (true) { 9262 IsDereference = NextIsDereference; 9263 NextIsDereference = false; 9264 9265 E = E->IgnoreParenImpCasts(); 9266 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9267 NextIsDereference = ME->isArrow(); 9268 const ValueDecl *VD = ME->getMemberDecl(); 9269 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9270 // Mutable fields can be modified even if the class is const. 9271 if (Field->isMutable()) { 9272 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9273 break; 9274 } 9275 9276 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9277 if (!DiagnosticEmitted) { 9278 S.Diag(Loc, diag::err_typecheck_assign_const) 9279 << ExprRange << ConstMember << false /*static*/ << Field 9280 << Field->getType(); 9281 DiagnosticEmitted = true; 9282 } 9283 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9284 << ConstMember << false /*static*/ << Field << Field->getType() 9285 << Field->getSourceRange(); 9286 } 9287 E = ME->getBase(); 9288 continue; 9289 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9290 if (VDecl->getType().isConstQualified()) { 9291 if (!DiagnosticEmitted) { 9292 S.Diag(Loc, diag::err_typecheck_assign_const) 9293 << ExprRange << ConstMember << true /*static*/ << VDecl 9294 << VDecl->getType(); 9295 DiagnosticEmitted = true; 9296 } 9297 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9298 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9299 << VDecl->getSourceRange(); 9300 } 9301 // Static fields do not inherit constness from parents. 9302 break; 9303 } 9304 break; 9305 } // End MemberExpr 9306 break; 9307 } 9308 9309 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9310 // Function calls 9311 const FunctionDecl *FD = CE->getDirectCallee(); 9312 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9313 if (!DiagnosticEmitted) { 9314 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9315 << ConstFunction << FD; 9316 DiagnosticEmitted = true; 9317 } 9318 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9319 diag::note_typecheck_assign_const) 9320 << ConstFunction << FD << FD->getReturnType() 9321 << FD->getReturnTypeSourceRange(); 9322 } 9323 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9324 // Point to variable declaration. 9325 if (const ValueDecl *VD = DRE->getDecl()) { 9326 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9327 if (!DiagnosticEmitted) { 9328 S.Diag(Loc, diag::err_typecheck_assign_const) 9329 << ExprRange << ConstVariable << VD << VD->getType(); 9330 DiagnosticEmitted = true; 9331 } 9332 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9333 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9334 } 9335 } 9336 } else if (isa<CXXThisExpr>(E)) { 9337 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9338 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9339 if (MD->isConst()) { 9340 if (!DiagnosticEmitted) { 9341 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9342 << ConstMethod << MD; 9343 DiagnosticEmitted = true; 9344 } 9345 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9346 << ConstMethod << MD << MD->getSourceRange(); 9347 } 9348 } 9349 } 9350 } 9351 9352 if (DiagnosticEmitted) 9353 return; 9354 9355 // Can't determine a more specific message, so display the generic error. 9356 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9357 } 9358 9359 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9360 /// emit an error and return true. If so, return false. 9361 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9362 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9363 SourceLocation OrigLoc = Loc; 9364 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9365 &Loc); 9366 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9367 IsLV = Expr::MLV_InvalidMessageExpression; 9368 if (IsLV == Expr::MLV_Valid) 9369 return false; 9370 9371 unsigned DiagID = 0; 9372 bool NeedType = false; 9373 switch (IsLV) { // C99 6.5.16p2 9374 case Expr::MLV_ConstQualified: 9375 // Use a specialized diagnostic when we're assigning to an object 9376 // from an enclosing function or block. 9377 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9378 if (NCCK == NCCK_Block) 9379 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9380 else 9381 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9382 break; 9383 } 9384 9385 // In ARC, use some specialized diagnostics for occasions where we 9386 // infer 'const'. These are always pseudo-strong variables. 9387 if (S.getLangOpts().ObjCAutoRefCount) { 9388 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9389 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9390 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9391 9392 // Use the normal diagnostic if it's pseudo-__strong but the 9393 // user actually wrote 'const'. 9394 if (var->isARCPseudoStrong() && 9395 (!var->getTypeSourceInfo() || 9396 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9397 // There are two pseudo-strong cases: 9398 // - self 9399 ObjCMethodDecl *method = S.getCurMethodDecl(); 9400 if (method && var == method->getSelfDecl()) 9401 DiagID = method->isClassMethod() 9402 ? diag::err_typecheck_arc_assign_self_class_method 9403 : diag::err_typecheck_arc_assign_self; 9404 9405 // - fast enumeration variables 9406 else 9407 DiagID = diag::err_typecheck_arr_assign_enumeration; 9408 9409 SourceRange Assign; 9410 if (Loc != OrigLoc) 9411 Assign = SourceRange(OrigLoc, OrigLoc); 9412 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9413 // We need to preserve the AST regardless, so migration tool 9414 // can do its job. 9415 return false; 9416 } 9417 } 9418 } 9419 9420 // If none of the special cases above are triggered, then this is a 9421 // simple const assignment. 9422 if (DiagID == 0) { 9423 DiagnoseConstAssignment(S, E, Loc); 9424 return true; 9425 } 9426 9427 break; 9428 case Expr::MLV_ConstAddrSpace: 9429 DiagnoseConstAssignment(S, E, Loc); 9430 return true; 9431 case Expr::MLV_ArrayType: 9432 case Expr::MLV_ArrayTemporary: 9433 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9434 NeedType = true; 9435 break; 9436 case Expr::MLV_NotObjectType: 9437 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9438 NeedType = true; 9439 break; 9440 case Expr::MLV_LValueCast: 9441 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9442 break; 9443 case Expr::MLV_Valid: 9444 llvm_unreachable("did not take early return for MLV_Valid"); 9445 case Expr::MLV_InvalidExpression: 9446 case Expr::MLV_MemberFunction: 9447 case Expr::MLV_ClassTemporary: 9448 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9449 break; 9450 case Expr::MLV_IncompleteType: 9451 case Expr::MLV_IncompleteVoidType: 9452 return S.RequireCompleteType(Loc, E->getType(), 9453 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9454 case Expr::MLV_DuplicateVectorComponents: 9455 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9456 break; 9457 case Expr::MLV_NoSetterProperty: 9458 llvm_unreachable("readonly properties should be processed differently"); 9459 case Expr::MLV_InvalidMessageExpression: 9460 DiagID = diag::error_readonly_message_assignment; 9461 break; 9462 case Expr::MLV_SubObjCPropertySetting: 9463 DiagID = diag::error_no_subobject_property_setting; 9464 break; 9465 } 9466 9467 SourceRange Assign; 9468 if (Loc != OrigLoc) 9469 Assign = SourceRange(OrigLoc, OrigLoc); 9470 if (NeedType) 9471 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9472 else 9473 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9474 return true; 9475 } 9476 9477 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9478 SourceLocation Loc, 9479 Sema &Sema) { 9480 // C / C++ fields 9481 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9482 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9483 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9484 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9485 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9486 } 9487 9488 // Objective-C instance variables 9489 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9490 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9491 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9492 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9493 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9494 if (RL && RR && RL->getDecl() == RR->getDecl()) 9495 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9496 } 9497 } 9498 9499 // C99 6.5.16.1 9500 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9501 SourceLocation Loc, 9502 QualType CompoundType) { 9503 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9504 9505 // Verify that LHS is a modifiable lvalue, and emit error if not. 9506 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9507 return QualType(); 9508 9509 QualType LHSType = LHSExpr->getType(); 9510 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9511 CompoundType; 9512 AssignConvertType ConvTy; 9513 if (CompoundType.isNull()) { 9514 Expr *RHSCheck = RHS.get(); 9515 9516 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9517 9518 QualType LHSTy(LHSType); 9519 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9520 if (RHS.isInvalid()) 9521 return QualType(); 9522 // Special case of NSObject attributes on c-style pointer types. 9523 if (ConvTy == IncompatiblePointer && 9524 ((Context.isObjCNSObjectType(LHSType) && 9525 RHSType->isObjCObjectPointerType()) || 9526 (Context.isObjCNSObjectType(RHSType) && 9527 LHSType->isObjCObjectPointerType()))) 9528 ConvTy = Compatible; 9529 9530 if (ConvTy == Compatible && 9531 LHSType->isObjCObjectType()) 9532 Diag(Loc, diag::err_objc_object_assignment) 9533 << LHSType; 9534 9535 // If the RHS is a unary plus or minus, check to see if they = and + are 9536 // right next to each other. If so, the user may have typo'd "x =+ 4" 9537 // instead of "x += 4". 9538 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9539 RHSCheck = ICE->getSubExpr(); 9540 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9541 if ((UO->getOpcode() == UO_Plus || 9542 UO->getOpcode() == UO_Minus) && 9543 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9544 // Only if the two operators are exactly adjacent. 9545 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9546 // And there is a space or other character before the subexpr of the 9547 // unary +/-. We don't want to warn on "x=-1". 9548 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9549 UO->getSubExpr()->getLocStart().isFileID()) { 9550 Diag(Loc, diag::warn_not_compound_assign) 9551 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9552 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9553 } 9554 } 9555 9556 if (ConvTy == Compatible) { 9557 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9558 // Warn about retain cycles where a block captures the LHS, but 9559 // not if the LHS is a simple variable into which the block is 9560 // being stored...unless that variable can be captured by reference! 9561 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9562 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9563 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9564 checkRetainCycles(LHSExpr, RHS.get()); 9565 9566 // It is safe to assign a weak reference into a strong variable. 9567 // Although this code can still have problems: 9568 // id x = self.weakProp; 9569 // id y = self.weakProp; 9570 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9571 // paths through the function. This should be revisited if 9572 // -Wrepeated-use-of-weak is made flow-sensitive. 9573 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9574 RHS.get()->getLocStart())) 9575 getCurFunction()->markSafeWeakUse(RHS.get()); 9576 9577 } else if (getLangOpts().ObjCAutoRefCount) { 9578 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9579 } 9580 } 9581 } else { 9582 // Compound assignment "x += y" 9583 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9584 } 9585 9586 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9587 RHS.get(), AA_Assigning)) 9588 return QualType(); 9589 9590 CheckForNullPointerDereference(*this, LHSExpr); 9591 9592 // C99 6.5.16p3: The type of an assignment expression is the type of the 9593 // left operand unless the left operand has qualified type, in which case 9594 // it is the unqualified version of the type of the left operand. 9595 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9596 // is converted to the type of the assignment expression (above). 9597 // C++ 5.17p1: the type of the assignment expression is that of its left 9598 // operand. 9599 return (getLangOpts().CPlusPlus 9600 ? LHSType : LHSType.getUnqualifiedType()); 9601 } 9602 9603 // C99 6.5.17 9604 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9605 SourceLocation Loc) { 9606 LHS = S.CheckPlaceholderExpr(LHS.get()); 9607 RHS = S.CheckPlaceholderExpr(RHS.get()); 9608 if (LHS.isInvalid() || RHS.isInvalid()) 9609 return QualType(); 9610 9611 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9612 // operands, but not unary promotions. 9613 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9614 9615 // So we treat the LHS as a ignored value, and in C++ we allow the 9616 // containing site to determine what should be done with the RHS. 9617 LHS = S.IgnoredValueConversions(LHS.get()); 9618 if (LHS.isInvalid()) 9619 return QualType(); 9620 9621 S.DiagnoseUnusedExprResult(LHS.get()); 9622 9623 if (!S.getLangOpts().CPlusPlus) { 9624 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9625 if (RHS.isInvalid()) 9626 return QualType(); 9627 if (!RHS.get()->getType()->isVoidType()) 9628 S.RequireCompleteType(Loc, RHS.get()->getType(), 9629 diag::err_incomplete_type); 9630 } 9631 9632 return RHS.get()->getType(); 9633 } 9634 9635 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9636 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9637 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9638 ExprValueKind &VK, 9639 ExprObjectKind &OK, 9640 SourceLocation OpLoc, 9641 bool IsInc, bool IsPrefix) { 9642 if (Op->isTypeDependent()) 9643 return S.Context.DependentTy; 9644 9645 QualType ResType = Op->getType(); 9646 // Atomic types can be used for increment / decrement where the non-atomic 9647 // versions can, so ignore the _Atomic() specifier for the purpose of 9648 // checking. 9649 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9650 ResType = ResAtomicType->getValueType(); 9651 9652 assert(!ResType.isNull() && "no type for increment/decrement expression"); 9653 9654 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 9655 // Decrement of bool is not allowed. 9656 if (!IsInc) { 9657 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 9658 return QualType(); 9659 } 9660 // Increment of bool sets it to true, but is deprecated. 9661 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 9662 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 9663 // Error on enum increments and decrements in C++ mode 9664 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 9665 return QualType(); 9666 } else if (ResType->isRealType()) { 9667 // OK! 9668 } else if (ResType->isPointerType()) { 9669 // C99 6.5.2.4p2, 6.5.6p2 9670 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 9671 return QualType(); 9672 } else if (ResType->isObjCObjectPointerType()) { 9673 // On modern runtimes, ObjC pointer arithmetic is forbidden. 9674 // Otherwise, we just need a complete type. 9675 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 9676 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 9677 return QualType(); 9678 } else if (ResType->isAnyComplexType()) { 9679 // C99 does not support ++/-- on complex types, we allow as an extension. 9680 S.Diag(OpLoc, diag::ext_integer_increment_complex) 9681 << ResType << Op->getSourceRange(); 9682 } else if (ResType->isPlaceholderType()) { 9683 ExprResult PR = S.CheckPlaceholderExpr(Op); 9684 if (PR.isInvalid()) return QualType(); 9685 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 9686 IsInc, IsPrefix); 9687 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 9688 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 9689 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 9690 (ResType->getAs<VectorType>()->getVectorKind() != 9691 VectorType::AltiVecBool)) { 9692 // The z vector extensions allow ++ and -- for non-bool vectors. 9693 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 9694 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 9695 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 9696 } else { 9697 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 9698 << ResType << int(IsInc) << Op->getSourceRange(); 9699 return QualType(); 9700 } 9701 // At this point, we know we have a real, complex or pointer type. 9702 // Now make sure the operand is a modifiable lvalue. 9703 if (CheckForModifiableLvalue(Op, OpLoc, S)) 9704 return QualType(); 9705 // In C++, a prefix increment is the same type as the operand. Otherwise 9706 // (in C or with postfix), the increment is the unqualified type of the 9707 // operand. 9708 if (IsPrefix && S.getLangOpts().CPlusPlus) { 9709 VK = VK_LValue; 9710 OK = Op->getObjectKind(); 9711 return ResType; 9712 } else { 9713 VK = VK_RValue; 9714 return ResType.getUnqualifiedType(); 9715 } 9716 } 9717 9718 9719 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 9720 /// This routine allows us to typecheck complex/recursive expressions 9721 /// where the declaration is needed for type checking. We only need to 9722 /// handle cases when the expression references a function designator 9723 /// or is an lvalue. Here are some examples: 9724 /// - &(x) => x 9725 /// - &*****f => f for f a function designator. 9726 /// - &s.xx => s 9727 /// - &s.zz[1].yy -> s, if zz is an array 9728 /// - *(x + 1) -> x, if x is an array 9729 /// - &"123"[2] -> 0 9730 /// - & __real__ x -> x 9731 static ValueDecl *getPrimaryDecl(Expr *E) { 9732 switch (E->getStmtClass()) { 9733 case Stmt::DeclRefExprClass: 9734 return cast<DeclRefExpr>(E)->getDecl(); 9735 case Stmt::MemberExprClass: 9736 // If this is an arrow operator, the address is an offset from 9737 // the base's value, so the object the base refers to is 9738 // irrelevant. 9739 if (cast<MemberExpr>(E)->isArrow()) 9740 return nullptr; 9741 // Otherwise, the expression refers to a part of the base 9742 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 9743 case Stmt::ArraySubscriptExprClass: { 9744 // FIXME: This code shouldn't be necessary! We should catch the implicit 9745 // promotion of register arrays earlier. 9746 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 9747 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 9748 if (ICE->getSubExpr()->getType()->isArrayType()) 9749 return getPrimaryDecl(ICE->getSubExpr()); 9750 } 9751 return nullptr; 9752 } 9753 case Stmt::UnaryOperatorClass: { 9754 UnaryOperator *UO = cast<UnaryOperator>(E); 9755 9756 switch(UO->getOpcode()) { 9757 case UO_Real: 9758 case UO_Imag: 9759 case UO_Extension: 9760 return getPrimaryDecl(UO->getSubExpr()); 9761 default: 9762 return nullptr; 9763 } 9764 } 9765 case Stmt::ParenExprClass: 9766 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 9767 case Stmt::ImplicitCastExprClass: 9768 // If the result of an implicit cast is an l-value, we care about 9769 // the sub-expression; otherwise, the result here doesn't matter. 9770 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 9771 default: 9772 return nullptr; 9773 } 9774 } 9775 9776 namespace { 9777 enum { 9778 AO_Bit_Field = 0, 9779 AO_Vector_Element = 1, 9780 AO_Property_Expansion = 2, 9781 AO_Register_Variable = 3, 9782 AO_No_Error = 4 9783 }; 9784 } 9785 /// \brief Diagnose invalid operand for address of operations. 9786 /// 9787 /// \param Type The type of operand which cannot have its address taken. 9788 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 9789 Expr *E, unsigned Type) { 9790 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 9791 } 9792 9793 /// CheckAddressOfOperand - The operand of & must be either a function 9794 /// designator or an lvalue designating an object. If it is an lvalue, the 9795 /// object cannot be declared with storage class register or be a bit field. 9796 /// Note: The usual conversions are *not* applied to the operand of the & 9797 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 9798 /// In C++, the operand might be an overloaded function name, in which case 9799 /// we allow the '&' but retain the overloaded-function type. 9800 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 9801 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 9802 if (PTy->getKind() == BuiltinType::Overload) { 9803 Expr *E = OrigOp.get()->IgnoreParens(); 9804 if (!isa<OverloadExpr>(E)) { 9805 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 9806 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 9807 << OrigOp.get()->getSourceRange(); 9808 return QualType(); 9809 } 9810 9811 OverloadExpr *Ovl = cast<OverloadExpr>(E); 9812 if (isa<UnresolvedMemberExpr>(Ovl)) 9813 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 9814 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9815 << OrigOp.get()->getSourceRange(); 9816 return QualType(); 9817 } 9818 9819 return Context.OverloadTy; 9820 } 9821 9822 if (PTy->getKind() == BuiltinType::UnknownAny) 9823 return Context.UnknownAnyTy; 9824 9825 if (PTy->getKind() == BuiltinType::BoundMember) { 9826 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9827 << OrigOp.get()->getSourceRange(); 9828 return QualType(); 9829 } 9830 9831 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 9832 if (OrigOp.isInvalid()) return QualType(); 9833 } 9834 9835 if (OrigOp.get()->isTypeDependent()) 9836 return Context.DependentTy; 9837 9838 assert(!OrigOp.get()->getType()->isPlaceholderType()); 9839 9840 // Make sure to ignore parentheses in subsequent checks 9841 Expr *op = OrigOp.get()->IgnoreParens(); 9842 9843 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 9844 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 9845 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 9846 return QualType(); 9847 } 9848 9849 if (getLangOpts().C99) { 9850 // Implement C99-only parts of addressof rules. 9851 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 9852 if (uOp->getOpcode() == UO_Deref) 9853 // Per C99 6.5.3.2, the address of a deref always returns a valid result 9854 // (assuming the deref expression is valid). 9855 return uOp->getSubExpr()->getType(); 9856 } 9857 // Technically, there should be a check for array subscript 9858 // expressions here, but the result of one is always an lvalue anyway. 9859 } 9860 ValueDecl *dcl = getPrimaryDecl(op); 9861 Expr::LValueClassification lval = op->ClassifyLValue(Context); 9862 unsigned AddressOfError = AO_No_Error; 9863 9864 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 9865 bool sfinae = (bool)isSFINAEContext(); 9866 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 9867 : diag::ext_typecheck_addrof_temporary) 9868 << op->getType() << op->getSourceRange(); 9869 if (sfinae) 9870 return QualType(); 9871 // Materialize the temporary as an lvalue so that we can take its address. 9872 OrigOp = op = new (Context) 9873 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 9874 } else if (isa<ObjCSelectorExpr>(op)) { 9875 return Context.getPointerType(op->getType()); 9876 } else if (lval == Expr::LV_MemberFunction) { 9877 // If it's an instance method, make a member pointer. 9878 // The expression must have exactly the form &A::foo. 9879 9880 // If the underlying expression isn't a decl ref, give up. 9881 if (!isa<DeclRefExpr>(op)) { 9882 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9883 << OrigOp.get()->getSourceRange(); 9884 return QualType(); 9885 } 9886 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 9887 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 9888 9889 // The id-expression was parenthesized. 9890 if (OrigOp.get() != DRE) { 9891 Diag(OpLoc, diag::err_parens_pointer_member_function) 9892 << OrigOp.get()->getSourceRange(); 9893 9894 // The method was named without a qualifier. 9895 } else if (!DRE->getQualifier()) { 9896 if (MD->getParent()->getName().empty()) 9897 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9898 << op->getSourceRange(); 9899 else { 9900 SmallString<32> Str; 9901 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 9902 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9903 << op->getSourceRange() 9904 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 9905 } 9906 } 9907 9908 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 9909 if (isa<CXXDestructorDecl>(MD)) 9910 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 9911 9912 QualType MPTy = Context.getMemberPointerType( 9913 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 9914 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9915 RequireCompleteType(OpLoc, MPTy, 0); 9916 return MPTy; 9917 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 9918 // C99 6.5.3.2p1 9919 // The operand must be either an l-value or a function designator 9920 if (!op->getType()->isFunctionType()) { 9921 // Use a special diagnostic for loads from property references. 9922 if (isa<PseudoObjectExpr>(op)) { 9923 AddressOfError = AO_Property_Expansion; 9924 } else { 9925 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 9926 << op->getType() << op->getSourceRange(); 9927 return QualType(); 9928 } 9929 } 9930 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 9931 // The operand cannot be a bit-field 9932 AddressOfError = AO_Bit_Field; 9933 } else if (op->getObjectKind() == OK_VectorComponent) { 9934 // The operand cannot be an element of a vector 9935 AddressOfError = AO_Vector_Element; 9936 } else if (dcl) { // C99 6.5.3.2p1 9937 // We have an lvalue with a decl. Make sure the decl is not declared 9938 // with the register storage-class specifier. 9939 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 9940 // in C++ it is not error to take address of a register 9941 // variable (c++03 7.1.1P3) 9942 if (vd->getStorageClass() == SC_Register && 9943 !getLangOpts().CPlusPlus) { 9944 AddressOfError = AO_Register_Variable; 9945 } 9946 } else if (isa<MSPropertyDecl>(dcl)) { 9947 AddressOfError = AO_Property_Expansion; 9948 } else if (isa<FunctionTemplateDecl>(dcl)) { 9949 return Context.OverloadTy; 9950 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 9951 // Okay: we can take the address of a field. 9952 // Could be a pointer to member, though, if there is an explicit 9953 // scope qualifier for the class. 9954 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 9955 DeclContext *Ctx = dcl->getDeclContext(); 9956 if (Ctx && Ctx->isRecord()) { 9957 if (dcl->getType()->isReferenceType()) { 9958 Diag(OpLoc, 9959 diag::err_cannot_form_pointer_to_member_of_reference_type) 9960 << dcl->getDeclName() << dcl->getType(); 9961 return QualType(); 9962 } 9963 9964 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 9965 Ctx = Ctx->getParent(); 9966 9967 QualType MPTy = Context.getMemberPointerType( 9968 op->getType(), 9969 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 9970 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9971 RequireCompleteType(OpLoc, MPTy, 0); 9972 return MPTy; 9973 } 9974 } 9975 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 9976 llvm_unreachable("Unknown/unexpected decl type"); 9977 } 9978 9979 if (AddressOfError != AO_No_Error) { 9980 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 9981 return QualType(); 9982 } 9983 9984 if (lval == Expr::LV_IncompleteVoidType) { 9985 // Taking the address of a void variable is technically illegal, but we 9986 // allow it in cases which are otherwise valid. 9987 // Example: "extern void x; void* y = &x;". 9988 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 9989 } 9990 9991 // If the operand has type "type", the result has type "pointer to type". 9992 if (op->getType()->isObjCObjectType()) 9993 return Context.getObjCObjectPointerType(op->getType()); 9994 return Context.getPointerType(op->getType()); 9995 } 9996 9997 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 9998 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 9999 if (!DRE) 10000 return; 10001 const Decl *D = DRE->getDecl(); 10002 if (!D) 10003 return; 10004 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10005 if (!Param) 10006 return; 10007 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10008 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10009 return; 10010 if (FunctionScopeInfo *FD = S.getCurFunction()) 10011 if (!FD->ModifiedNonNullParams.count(Param)) 10012 FD->ModifiedNonNullParams.insert(Param); 10013 } 10014 10015 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10016 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10017 SourceLocation OpLoc) { 10018 if (Op->isTypeDependent()) 10019 return S.Context.DependentTy; 10020 10021 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10022 if (ConvResult.isInvalid()) 10023 return QualType(); 10024 Op = ConvResult.get(); 10025 QualType OpTy = Op->getType(); 10026 QualType Result; 10027 10028 if (isa<CXXReinterpretCastExpr>(Op)) { 10029 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10030 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10031 Op->getSourceRange()); 10032 } 10033 10034 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10035 Result = PT->getPointeeType(); 10036 else if (const ObjCObjectPointerType *OPT = 10037 OpTy->getAs<ObjCObjectPointerType>()) 10038 Result = OPT->getPointeeType(); 10039 else { 10040 ExprResult PR = S.CheckPlaceholderExpr(Op); 10041 if (PR.isInvalid()) return QualType(); 10042 if (PR.get() != Op) 10043 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10044 } 10045 10046 if (Result.isNull()) { 10047 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10048 << OpTy << Op->getSourceRange(); 10049 return QualType(); 10050 } 10051 10052 // Note that per both C89 and C99, indirection is always legal, even if Result 10053 // is an incomplete type or void. It would be possible to warn about 10054 // dereferencing a void pointer, but it's completely well-defined, and such a 10055 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10056 // for pointers to 'void' but is fine for any other pointer type: 10057 // 10058 // C++ [expr.unary.op]p1: 10059 // [...] the expression to which [the unary * operator] is applied shall 10060 // be a pointer to an object type, or a pointer to a function type 10061 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10062 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10063 << OpTy << Op->getSourceRange(); 10064 10065 // Dereferences are usually l-values... 10066 VK = VK_LValue; 10067 10068 // ...except that certain expressions are never l-values in C. 10069 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10070 VK = VK_RValue; 10071 10072 return Result; 10073 } 10074 10075 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10076 BinaryOperatorKind Opc; 10077 switch (Kind) { 10078 default: llvm_unreachable("Unknown binop!"); 10079 case tok::periodstar: Opc = BO_PtrMemD; break; 10080 case tok::arrowstar: Opc = BO_PtrMemI; break; 10081 case tok::star: Opc = BO_Mul; break; 10082 case tok::slash: Opc = BO_Div; break; 10083 case tok::percent: Opc = BO_Rem; break; 10084 case tok::plus: Opc = BO_Add; break; 10085 case tok::minus: Opc = BO_Sub; break; 10086 case tok::lessless: Opc = BO_Shl; break; 10087 case tok::greatergreater: Opc = BO_Shr; break; 10088 case tok::lessequal: Opc = BO_LE; break; 10089 case tok::less: Opc = BO_LT; break; 10090 case tok::greaterequal: Opc = BO_GE; break; 10091 case tok::greater: Opc = BO_GT; break; 10092 case tok::exclaimequal: Opc = BO_NE; break; 10093 case tok::equalequal: Opc = BO_EQ; break; 10094 case tok::amp: Opc = BO_And; break; 10095 case tok::caret: Opc = BO_Xor; break; 10096 case tok::pipe: Opc = BO_Or; break; 10097 case tok::ampamp: Opc = BO_LAnd; break; 10098 case tok::pipepipe: Opc = BO_LOr; break; 10099 case tok::equal: Opc = BO_Assign; break; 10100 case tok::starequal: Opc = BO_MulAssign; break; 10101 case tok::slashequal: Opc = BO_DivAssign; break; 10102 case tok::percentequal: Opc = BO_RemAssign; break; 10103 case tok::plusequal: Opc = BO_AddAssign; break; 10104 case tok::minusequal: Opc = BO_SubAssign; break; 10105 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10106 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10107 case tok::ampequal: Opc = BO_AndAssign; break; 10108 case tok::caretequal: Opc = BO_XorAssign; break; 10109 case tok::pipeequal: Opc = BO_OrAssign; break; 10110 case tok::comma: Opc = BO_Comma; break; 10111 } 10112 return Opc; 10113 } 10114 10115 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10116 tok::TokenKind Kind) { 10117 UnaryOperatorKind Opc; 10118 switch (Kind) { 10119 default: llvm_unreachable("Unknown unary op!"); 10120 case tok::plusplus: Opc = UO_PreInc; break; 10121 case tok::minusminus: Opc = UO_PreDec; break; 10122 case tok::amp: Opc = UO_AddrOf; break; 10123 case tok::star: Opc = UO_Deref; break; 10124 case tok::plus: Opc = UO_Plus; break; 10125 case tok::minus: Opc = UO_Minus; break; 10126 case tok::tilde: Opc = UO_Not; break; 10127 case tok::exclaim: Opc = UO_LNot; break; 10128 case tok::kw___real: Opc = UO_Real; break; 10129 case tok::kw___imag: Opc = UO_Imag; break; 10130 case tok::kw___extension__: Opc = UO_Extension; break; 10131 } 10132 return Opc; 10133 } 10134 10135 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10136 /// This warning is only emitted for builtin assignment operations. It is also 10137 /// suppressed in the event of macro expansions. 10138 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10139 SourceLocation OpLoc) { 10140 if (!S.ActiveTemplateInstantiations.empty()) 10141 return; 10142 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10143 return; 10144 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10145 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10146 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10147 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10148 if (!LHSDeclRef || !RHSDeclRef || 10149 LHSDeclRef->getLocation().isMacroID() || 10150 RHSDeclRef->getLocation().isMacroID()) 10151 return; 10152 const ValueDecl *LHSDecl = 10153 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10154 const ValueDecl *RHSDecl = 10155 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10156 if (LHSDecl != RHSDecl) 10157 return; 10158 if (LHSDecl->getType().isVolatileQualified()) 10159 return; 10160 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10161 if (RefTy->getPointeeType().isVolatileQualified()) 10162 return; 10163 10164 S.Diag(OpLoc, diag::warn_self_assignment) 10165 << LHSDeclRef->getType() 10166 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10167 } 10168 10169 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10170 /// is usually indicative of introspection within the Objective-C pointer. 10171 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10172 SourceLocation OpLoc) { 10173 if (!S.getLangOpts().ObjC1) 10174 return; 10175 10176 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10177 const Expr *LHS = L.get(); 10178 const Expr *RHS = R.get(); 10179 10180 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10181 ObjCPointerExpr = LHS; 10182 OtherExpr = RHS; 10183 } 10184 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10185 ObjCPointerExpr = RHS; 10186 OtherExpr = LHS; 10187 } 10188 10189 // This warning is deliberately made very specific to reduce false 10190 // positives with logic that uses '&' for hashing. This logic mainly 10191 // looks for code trying to introspect into tagged pointers, which 10192 // code should generally never do. 10193 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10194 unsigned Diag = diag::warn_objc_pointer_masking; 10195 // Determine if we are introspecting the result of performSelectorXXX. 10196 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10197 // Special case messages to -performSelector and friends, which 10198 // can return non-pointer values boxed in a pointer value. 10199 // Some clients may wish to silence warnings in this subcase. 10200 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10201 Selector S = ME->getSelector(); 10202 StringRef SelArg0 = S.getNameForSlot(0); 10203 if (SelArg0.startswith("performSelector")) 10204 Diag = diag::warn_objc_pointer_masking_performSelector; 10205 } 10206 10207 S.Diag(OpLoc, Diag) 10208 << ObjCPointerExpr->getSourceRange(); 10209 } 10210 } 10211 10212 static NamedDecl *getDeclFromExpr(Expr *E) { 10213 if (!E) 10214 return nullptr; 10215 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10216 return DRE->getDecl(); 10217 if (auto *ME = dyn_cast<MemberExpr>(E)) 10218 return ME->getMemberDecl(); 10219 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10220 return IRE->getDecl(); 10221 return nullptr; 10222 } 10223 10224 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10225 /// operator @p Opc at location @c TokLoc. This routine only supports 10226 /// built-in operations; ActOnBinOp handles overloaded operators. 10227 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10228 BinaryOperatorKind Opc, 10229 Expr *LHSExpr, Expr *RHSExpr) { 10230 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10231 // The syntax only allows initializer lists on the RHS of assignment, 10232 // so we don't need to worry about accepting invalid code for 10233 // non-assignment operators. 10234 // C++11 5.17p9: 10235 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10236 // of x = {} is x = T(). 10237 InitializationKind Kind = 10238 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10239 InitializedEntity Entity = 10240 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10241 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10242 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10243 if (Init.isInvalid()) 10244 return Init; 10245 RHSExpr = Init.get(); 10246 } 10247 10248 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10249 QualType ResultTy; // Result type of the binary operator. 10250 // The following two variables are used for compound assignment operators 10251 QualType CompLHSTy; // Type of LHS after promotions for computation 10252 QualType CompResultTy; // Type of computation result 10253 ExprValueKind VK = VK_RValue; 10254 ExprObjectKind OK = OK_Ordinary; 10255 10256 if (!getLangOpts().CPlusPlus) { 10257 // C cannot handle TypoExpr nodes on either side of a binop because it 10258 // doesn't handle dependent types properly, so make sure any TypoExprs have 10259 // been dealt with before checking the operands. 10260 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10261 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10262 if (Opc != BO_Assign) 10263 return ExprResult(E); 10264 // Avoid correcting the RHS to the same Expr as the LHS. 10265 Decl *D = getDeclFromExpr(E); 10266 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10267 }); 10268 if (!LHS.isUsable() || !RHS.isUsable()) 10269 return ExprError(); 10270 } 10271 10272 if (getLangOpts().OpenCL) { 10273 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10274 // the ATOMIC_VAR_INIT macro. 10275 if (LHSExpr->getType()->isAtomicType() || 10276 RHSExpr->getType()->isAtomicType()) { 10277 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10278 if (BO_Assign == Opc) 10279 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10280 else 10281 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10282 return ExprError(); 10283 } 10284 } 10285 10286 switch (Opc) { 10287 case BO_Assign: 10288 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10289 if (getLangOpts().CPlusPlus && 10290 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10291 VK = LHS.get()->getValueKind(); 10292 OK = LHS.get()->getObjectKind(); 10293 } 10294 if (!ResultTy.isNull()) { 10295 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10296 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10297 } 10298 RecordModifiableNonNullParam(*this, LHS.get()); 10299 break; 10300 case BO_PtrMemD: 10301 case BO_PtrMemI: 10302 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10303 Opc == BO_PtrMemI); 10304 break; 10305 case BO_Mul: 10306 case BO_Div: 10307 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10308 Opc == BO_Div); 10309 break; 10310 case BO_Rem: 10311 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10312 break; 10313 case BO_Add: 10314 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10315 break; 10316 case BO_Sub: 10317 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10318 break; 10319 case BO_Shl: 10320 case BO_Shr: 10321 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10322 break; 10323 case BO_LE: 10324 case BO_LT: 10325 case BO_GE: 10326 case BO_GT: 10327 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10328 break; 10329 case BO_EQ: 10330 case BO_NE: 10331 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10332 break; 10333 case BO_And: 10334 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10335 case BO_Xor: 10336 case BO_Or: 10337 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10338 break; 10339 case BO_LAnd: 10340 case BO_LOr: 10341 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10342 break; 10343 case BO_MulAssign: 10344 case BO_DivAssign: 10345 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10346 Opc == BO_DivAssign); 10347 CompLHSTy = CompResultTy; 10348 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10349 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10350 break; 10351 case BO_RemAssign: 10352 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10353 CompLHSTy = CompResultTy; 10354 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10355 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10356 break; 10357 case BO_AddAssign: 10358 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10359 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10360 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10361 break; 10362 case BO_SubAssign: 10363 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10364 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10365 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10366 break; 10367 case BO_ShlAssign: 10368 case BO_ShrAssign: 10369 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10370 CompLHSTy = CompResultTy; 10371 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10372 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10373 break; 10374 case BO_AndAssign: 10375 case BO_OrAssign: // fallthrough 10376 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10377 case BO_XorAssign: 10378 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10379 CompLHSTy = CompResultTy; 10380 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10381 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10382 break; 10383 case BO_Comma: 10384 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10385 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10386 VK = RHS.get()->getValueKind(); 10387 OK = RHS.get()->getObjectKind(); 10388 } 10389 break; 10390 } 10391 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10392 return ExprError(); 10393 10394 // Check for array bounds violations for both sides of the BinaryOperator 10395 CheckArrayAccess(LHS.get()); 10396 CheckArrayAccess(RHS.get()); 10397 10398 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10399 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10400 &Context.Idents.get("object_setClass"), 10401 SourceLocation(), LookupOrdinaryName); 10402 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10403 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 10404 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10405 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10406 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10407 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10408 } 10409 else 10410 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10411 } 10412 else if (const ObjCIvarRefExpr *OIRE = 10413 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10414 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10415 10416 if (CompResultTy.isNull()) 10417 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10418 OK, OpLoc, FPFeatures.fp_contract); 10419 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10420 OK_ObjCProperty) { 10421 VK = VK_LValue; 10422 OK = LHS.get()->getObjectKind(); 10423 } 10424 return new (Context) CompoundAssignOperator( 10425 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10426 OpLoc, FPFeatures.fp_contract); 10427 } 10428 10429 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10430 /// operators are mixed in a way that suggests that the programmer forgot that 10431 /// comparison operators have higher precedence. The most typical example of 10432 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10433 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10434 SourceLocation OpLoc, Expr *LHSExpr, 10435 Expr *RHSExpr) { 10436 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10437 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10438 10439 // Check that one of the sides is a comparison operator. 10440 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10441 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10442 if (!isLeftComp && !isRightComp) 10443 return; 10444 10445 // Bitwise operations are sometimes used as eager logical ops. 10446 // Don't diagnose this. 10447 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10448 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10449 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 10450 return; 10451 10452 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10453 OpLoc) 10454 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10455 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10456 SourceRange ParensRange = isLeftComp ? 10457 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10458 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10459 10460 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10461 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10462 SuggestParentheses(Self, OpLoc, 10463 Self.PDiag(diag::note_precedence_silence) << OpStr, 10464 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10465 SuggestParentheses(Self, OpLoc, 10466 Self.PDiag(diag::note_precedence_bitwise_first) 10467 << BinaryOperator::getOpcodeStr(Opc), 10468 ParensRange); 10469 } 10470 10471 /// \brief It accepts a '&' expr that is inside a '|' one. 10472 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 10473 /// in parentheses. 10474 static void 10475 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 10476 BinaryOperator *Bop) { 10477 assert(Bop->getOpcode() == BO_And); 10478 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 10479 << Bop->getSourceRange() << OpLoc; 10480 SuggestParentheses(Self, Bop->getOperatorLoc(), 10481 Self.PDiag(diag::note_precedence_silence) 10482 << Bop->getOpcodeStr(), 10483 Bop->getSourceRange()); 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 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10491 BinaryOperator *Bop) { 10492 assert(Bop->getOpcode() == BO_LAnd); 10493 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_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 Returns true if the given expression can be evaluated as a constant 10502 /// 'true'. 10503 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10504 bool Res; 10505 return !E->isValueDependent() && 10506 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10507 } 10508 10509 /// \brief Returns true if the given expression can be evaluated as a constant 10510 /// 'false'. 10511 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10512 bool Res; 10513 return !E->isValueDependent() && 10514 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10515 } 10516 10517 /// \brief Look for '&&' in the left hand of a '||' expr. 10518 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10519 Expr *LHSExpr, Expr *RHSExpr) { 10520 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10521 if (Bop->getOpcode() == BO_LAnd) { 10522 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10523 if (EvaluatesAsFalse(S, RHSExpr)) 10524 return; 10525 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10526 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10527 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10528 } else if (Bop->getOpcode() == BO_LOr) { 10529 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10530 // If it's "a || b && 1 || c" we didn't warn earlier for 10531 // "a || b && 1", but warn now. 10532 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10533 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10534 } 10535 } 10536 } 10537 } 10538 10539 /// \brief Look for '&&' in the right hand of a '||' expr. 10540 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10541 Expr *LHSExpr, Expr *RHSExpr) { 10542 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10543 if (Bop->getOpcode() == BO_LAnd) { 10544 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10545 if (EvaluatesAsFalse(S, LHSExpr)) 10546 return; 10547 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10548 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10549 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10550 } 10551 } 10552 } 10553 10554 /// \brief Look for '&' in the left or right hand of a '|' expr. 10555 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 10556 Expr *OrArg) { 10557 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 10558 if (Bop->getOpcode() == BO_And) 10559 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 10560 } 10561 } 10562 10563 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10564 Expr *SubExpr, StringRef Shift) { 10565 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10566 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10567 StringRef Op = Bop->getOpcodeStr(); 10568 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10569 << Bop->getSourceRange() << OpLoc << Shift << Op; 10570 SuggestParentheses(S, Bop->getOperatorLoc(), 10571 S.PDiag(diag::note_precedence_silence) << Op, 10572 Bop->getSourceRange()); 10573 } 10574 } 10575 } 10576 10577 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10578 Expr *LHSExpr, Expr *RHSExpr) { 10579 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10580 if (!OCE) 10581 return; 10582 10583 FunctionDecl *FD = OCE->getDirectCallee(); 10584 if (!FD || !FD->isOverloadedOperator()) 10585 return; 10586 10587 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10588 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10589 return; 10590 10591 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10592 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10593 << (Kind == OO_LessLess); 10594 SuggestParentheses(S, OCE->getOperatorLoc(), 10595 S.PDiag(diag::note_precedence_silence) 10596 << (Kind == OO_LessLess ? "<<" : ">>"), 10597 OCE->getSourceRange()); 10598 SuggestParentheses(S, OpLoc, 10599 S.PDiag(diag::note_evaluate_comparison_first), 10600 SourceRange(OCE->getArg(1)->getLocStart(), 10601 RHSExpr->getLocEnd())); 10602 } 10603 10604 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10605 /// precedence. 10606 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10607 SourceLocation OpLoc, Expr *LHSExpr, 10608 Expr *RHSExpr){ 10609 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10610 if (BinaryOperator::isBitwiseOp(Opc)) 10611 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10612 10613 // Diagnose "arg1 & arg2 | arg3" 10614 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10615 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 10616 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 10617 } 10618 10619 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10620 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10621 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10622 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10623 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10624 } 10625 10626 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 10627 || Opc == BO_Shr) { 10628 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 10629 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 10630 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 10631 } 10632 10633 // Warn on overloaded shift operators and comparisons, such as: 10634 // cout << 5 == 4; 10635 if (BinaryOperator::isComparisonOp(Opc)) 10636 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 10637 } 10638 10639 // Binary Operators. 'Tok' is the token for the operator. 10640 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 10641 tok::TokenKind Kind, 10642 Expr *LHSExpr, Expr *RHSExpr) { 10643 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 10644 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 10645 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 10646 10647 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 10648 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 10649 10650 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 10651 } 10652 10653 /// Build an overloaded binary operator expression in the given scope. 10654 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 10655 BinaryOperatorKind Opc, 10656 Expr *LHS, Expr *RHS) { 10657 // Find all of the overloaded operators visible from this 10658 // point. We perform both an operator-name lookup from the local 10659 // scope and an argument-dependent lookup based on the types of 10660 // the arguments. 10661 UnresolvedSet<16> Functions; 10662 OverloadedOperatorKind OverOp 10663 = BinaryOperator::getOverloadedOperator(Opc); 10664 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 10665 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 10666 RHS->getType(), Functions); 10667 10668 // Build the (potentially-overloaded, potentially-dependent) 10669 // binary operation. 10670 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 10671 } 10672 10673 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 10674 BinaryOperatorKind Opc, 10675 Expr *LHSExpr, Expr *RHSExpr) { 10676 // We want to end up calling one of checkPseudoObjectAssignment 10677 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 10678 // both expressions are overloadable or either is type-dependent), 10679 // or CreateBuiltinBinOp (in any other case). We also want to get 10680 // any placeholder types out of the way. 10681 10682 // Handle pseudo-objects in the LHS. 10683 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 10684 // Assignments with a pseudo-object l-value need special analysis. 10685 if (pty->getKind() == BuiltinType::PseudoObject && 10686 BinaryOperator::isAssignmentOp(Opc)) 10687 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 10688 10689 // Don't resolve overloads if the other type is overloadable. 10690 if (pty->getKind() == BuiltinType::Overload) { 10691 // We can't actually test that if we still have a placeholder, 10692 // though. Fortunately, none of the exceptions we see in that 10693 // code below are valid when the LHS is an overload set. Note 10694 // that an overload set can be dependently-typed, but it never 10695 // instantiates to having an overloadable type. 10696 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10697 if (resolvedRHS.isInvalid()) return ExprError(); 10698 RHSExpr = resolvedRHS.get(); 10699 10700 if (RHSExpr->isTypeDependent() || 10701 RHSExpr->getType()->isOverloadableType()) 10702 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10703 } 10704 10705 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 10706 if (LHS.isInvalid()) return ExprError(); 10707 LHSExpr = LHS.get(); 10708 } 10709 10710 // Handle pseudo-objects in the RHS. 10711 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 10712 // An overload in the RHS can potentially be resolved by the type 10713 // being assigned to. 10714 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 10715 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10716 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10717 10718 if (LHSExpr->getType()->isOverloadableType()) 10719 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10720 10721 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10722 } 10723 10724 // Don't resolve overloads if the other type is overloadable. 10725 if (pty->getKind() == BuiltinType::Overload && 10726 LHSExpr->getType()->isOverloadableType()) 10727 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10728 10729 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10730 if (!resolvedRHS.isUsable()) return ExprError(); 10731 RHSExpr = resolvedRHS.get(); 10732 } 10733 10734 if (getLangOpts().CPlusPlus) { 10735 // If either expression is type-dependent, always build an 10736 // overloaded op. 10737 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10738 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10739 10740 // Otherwise, build an overloaded op if either expression has an 10741 // overloadable type. 10742 if (LHSExpr->getType()->isOverloadableType() || 10743 RHSExpr->getType()->isOverloadableType()) 10744 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10745 } 10746 10747 // Build a built-in binary operation. 10748 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10749 } 10750 10751 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 10752 UnaryOperatorKind Opc, 10753 Expr *InputExpr) { 10754 ExprResult Input = InputExpr; 10755 ExprValueKind VK = VK_RValue; 10756 ExprObjectKind OK = OK_Ordinary; 10757 QualType resultType; 10758 if (getLangOpts().OpenCL) { 10759 // The only legal unary operation for atomics is '&'. 10760 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 10761 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10762 << InputExpr->getType() 10763 << Input.get()->getSourceRange()); 10764 } 10765 } 10766 switch (Opc) { 10767 case UO_PreInc: 10768 case UO_PreDec: 10769 case UO_PostInc: 10770 case UO_PostDec: 10771 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 10772 OpLoc, 10773 Opc == UO_PreInc || 10774 Opc == UO_PostInc, 10775 Opc == UO_PreInc || 10776 Opc == UO_PreDec); 10777 break; 10778 case UO_AddrOf: 10779 resultType = CheckAddressOfOperand(Input, OpLoc); 10780 RecordModifiableNonNullParam(*this, InputExpr); 10781 break; 10782 case UO_Deref: { 10783 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10784 if (Input.isInvalid()) return ExprError(); 10785 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 10786 break; 10787 } 10788 case UO_Plus: 10789 case UO_Minus: 10790 Input = UsualUnaryConversions(Input.get()); 10791 if (Input.isInvalid()) return ExprError(); 10792 resultType = Input.get()->getType(); 10793 if (resultType->isDependentType()) 10794 break; 10795 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 10796 break; 10797 else if (resultType->isVectorType() && 10798 // The z vector extensions don't allow + or - with bool vectors. 10799 (!Context.getLangOpts().ZVector || 10800 resultType->getAs<VectorType>()->getVectorKind() != 10801 VectorType::AltiVecBool)) 10802 break; 10803 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 10804 Opc == UO_Plus && 10805 resultType->isPointerType()) 10806 break; 10807 10808 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10809 << resultType << Input.get()->getSourceRange()); 10810 10811 case UO_Not: // bitwise complement 10812 Input = UsualUnaryConversions(Input.get()); 10813 if (Input.isInvalid()) 10814 return ExprError(); 10815 resultType = Input.get()->getType(); 10816 if (resultType->isDependentType()) 10817 break; 10818 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 10819 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 10820 // C99 does not support '~' for complex conjugation. 10821 Diag(OpLoc, diag::ext_integer_complement_complex) 10822 << resultType << Input.get()->getSourceRange(); 10823 else if (resultType->hasIntegerRepresentation()) 10824 break; 10825 else if (resultType->isExtVectorType()) { 10826 if (Context.getLangOpts().OpenCL) { 10827 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 10828 // on vector float types. 10829 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10830 if (!T->isIntegerType()) 10831 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10832 << resultType << Input.get()->getSourceRange()); 10833 } 10834 break; 10835 } else { 10836 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10837 << resultType << Input.get()->getSourceRange()); 10838 } 10839 break; 10840 10841 case UO_LNot: // logical negation 10842 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 10843 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10844 if (Input.isInvalid()) return ExprError(); 10845 resultType = Input.get()->getType(); 10846 10847 // Though we still have to promote half FP to float... 10848 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 10849 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 10850 resultType = Context.FloatTy; 10851 } 10852 10853 if (resultType->isDependentType()) 10854 break; 10855 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 10856 // C99 6.5.3.3p1: ok, fallthrough; 10857 if (Context.getLangOpts().CPlusPlus) { 10858 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 10859 // operand contextually converted to bool. 10860 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 10861 ScalarTypeToBooleanCastKind(resultType)); 10862 } else if (Context.getLangOpts().OpenCL && 10863 Context.getLangOpts().OpenCLVersion < 120) { 10864 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10865 // operate on scalar float types. 10866 if (!resultType->isIntegerType()) 10867 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10868 << resultType << Input.get()->getSourceRange()); 10869 } 10870 } else if (resultType->isExtVectorType()) { 10871 if (Context.getLangOpts().OpenCL && 10872 Context.getLangOpts().OpenCLVersion < 120) { 10873 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10874 // operate on vector float types. 10875 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10876 if (!T->isIntegerType()) 10877 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10878 << resultType << Input.get()->getSourceRange()); 10879 } 10880 // Vector logical not returns the signed variant of the operand type. 10881 resultType = GetSignedVectorType(resultType); 10882 break; 10883 } else { 10884 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10885 << resultType << Input.get()->getSourceRange()); 10886 } 10887 10888 // LNot always has type int. C99 6.5.3.3p5. 10889 // In C++, it's bool. C++ 5.3.1p8 10890 resultType = Context.getLogicalOperationType(); 10891 break; 10892 case UO_Real: 10893 case UO_Imag: 10894 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 10895 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 10896 // complex l-values to ordinary l-values and all other values to r-values. 10897 if (Input.isInvalid()) return ExprError(); 10898 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 10899 if (Input.get()->getValueKind() != VK_RValue && 10900 Input.get()->getObjectKind() == OK_Ordinary) 10901 VK = Input.get()->getValueKind(); 10902 } else if (!getLangOpts().CPlusPlus) { 10903 // In C, a volatile scalar is read by __imag. In C++, it is not. 10904 Input = DefaultLvalueConversion(Input.get()); 10905 } 10906 break; 10907 case UO_Extension: 10908 case UO_Coawait: 10909 resultType = Input.get()->getType(); 10910 VK = Input.get()->getValueKind(); 10911 OK = Input.get()->getObjectKind(); 10912 break; 10913 } 10914 if (resultType.isNull() || Input.isInvalid()) 10915 return ExprError(); 10916 10917 // Check for array bounds violations in the operand of the UnaryOperator, 10918 // except for the '*' and '&' operators that have to be handled specially 10919 // by CheckArrayAccess (as there are special cases like &array[arraysize] 10920 // that are explicitly defined as valid by the standard). 10921 if (Opc != UO_AddrOf && Opc != UO_Deref) 10922 CheckArrayAccess(Input.get()); 10923 10924 return new (Context) 10925 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 10926 } 10927 10928 /// \brief Determine whether the given expression is a qualified member 10929 /// access expression, of a form that could be turned into a pointer to member 10930 /// with the address-of operator. 10931 static bool isQualifiedMemberAccess(Expr *E) { 10932 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10933 if (!DRE->getQualifier()) 10934 return false; 10935 10936 ValueDecl *VD = DRE->getDecl(); 10937 if (!VD->isCXXClassMember()) 10938 return false; 10939 10940 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 10941 return true; 10942 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 10943 return Method->isInstance(); 10944 10945 return false; 10946 } 10947 10948 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 10949 if (!ULE->getQualifier()) 10950 return false; 10951 10952 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 10953 DEnd = ULE->decls_end(); 10954 D != DEnd; ++D) { 10955 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 10956 if (Method->isInstance()) 10957 return true; 10958 } else { 10959 // Overload set does not contain methods. 10960 break; 10961 } 10962 } 10963 10964 return false; 10965 } 10966 10967 return false; 10968 } 10969 10970 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 10971 UnaryOperatorKind Opc, Expr *Input) { 10972 // First things first: handle placeholders so that the 10973 // overloaded-operator check considers the right type. 10974 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 10975 // Increment and decrement of pseudo-object references. 10976 if (pty->getKind() == BuiltinType::PseudoObject && 10977 UnaryOperator::isIncrementDecrementOp(Opc)) 10978 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 10979 10980 // extension is always a builtin operator. 10981 if (Opc == UO_Extension) 10982 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10983 10984 // & gets special logic for several kinds of placeholder. 10985 // The builtin code knows what to do. 10986 if (Opc == UO_AddrOf && 10987 (pty->getKind() == BuiltinType::Overload || 10988 pty->getKind() == BuiltinType::UnknownAny || 10989 pty->getKind() == BuiltinType::BoundMember)) 10990 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10991 10992 // Anything else needs to be handled now. 10993 ExprResult Result = CheckPlaceholderExpr(Input); 10994 if (Result.isInvalid()) return ExprError(); 10995 Input = Result.get(); 10996 } 10997 10998 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 10999 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11000 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11001 // Find all of the overloaded operators visible from this 11002 // point. We perform both an operator-name lookup from the local 11003 // scope and an argument-dependent lookup based on the types of 11004 // the arguments. 11005 UnresolvedSet<16> Functions; 11006 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11007 if (S && OverOp != OO_None) 11008 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11009 Functions); 11010 11011 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11012 } 11013 11014 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11015 } 11016 11017 // Unary Operators. 'Tok' is the token for the operator. 11018 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11019 tok::TokenKind Op, Expr *Input) { 11020 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11021 } 11022 11023 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11024 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11025 LabelDecl *TheDecl) { 11026 TheDecl->markUsed(Context); 11027 // Create the AST node. The address of a label always has type 'void*'. 11028 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11029 Context.getPointerType(Context.VoidTy)); 11030 } 11031 11032 /// Given the last statement in a statement-expression, check whether 11033 /// the result is a producing expression (like a call to an 11034 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11035 /// release out of the full-expression. Otherwise, return null. 11036 /// Cannot fail. 11037 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11038 // Should always be wrapped with one of these. 11039 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11040 if (!cleanups) return nullptr; 11041 11042 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11043 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11044 return nullptr; 11045 11046 // Splice out the cast. This shouldn't modify any interesting 11047 // features of the statement. 11048 Expr *producer = cast->getSubExpr(); 11049 assert(producer->getType() == cast->getType()); 11050 assert(producer->getValueKind() == cast->getValueKind()); 11051 cleanups->setSubExpr(producer); 11052 return cleanups; 11053 } 11054 11055 void Sema::ActOnStartStmtExpr() { 11056 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11057 } 11058 11059 void Sema::ActOnStmtExprError() { 11060 // Note that function is also called by TreeTransform when leaving a 11061 // StmtExpr scope without rebuilding anything. 11062 11063 DiscardCleanupsInEvaluationContext(); 11064 PopExpressionEvaluationContext(); 11065 } 11066 11067 ExprResult 11068 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11069 SourceLocation RPLoc) { // "({..})" 11070 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11071 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11072 11073 if (hasAnyUnrecoverableErrorsInThisFunction()) 11074 DiscardCleanupsInEvaluationContext(); 11075 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11076 PopExpressionEvaluationContext(); 11077 11078 // FIXME: there are a variety of strange constraints to enforce here, for 11079 // example, it is not possible to goto into a stmt expression apparently. 11080 // More semantic analysis is needed. 11081 11082 // If there are sub-stmts in the compound stmt, take the type of the last one 11083 // as the type of the stmtexpr. 11084 QualType Ty = Context.VoidTy; 11085 bool StmtExprMayBindToTemp = false; 11086 if (!Compound->body_empty()) { 11087 Stmt *LastStmt = Compound->body_back(); 11088 LabelStmt *LastLabelStmt = nullptr; 11089 // If LastStmt is a label, skip down through into the body. 11090 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11091 LastLabelStmt = Label; 11092 LastStmt = Label->getSubStmt(); 11093 } 11094 11095 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11096 // Do function/array conversion on the last expression, but not 11097 // lvalue-to-rvalue. However, initialize an unqualified type. 11098 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11099 if (LastExpr.isInvalid()) 11100 return ExprError(); 11101 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11102 11103 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11104 // In ARC, if the final expression ends in a consume, splice 11105 // the consume out and bind it later. In the alternate case 11106 // (when dealing with a retainable type), the result 11107 // initialization will create a produce. In both cases the 11108 // result will be +1, and we'll need to balance that out with 11109 // a bind. 11110 if (Expr *rebuiltLastStmt 11111 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11112 LastExpr = rebuiltLastStmt; 11113 } else { 11114 LastExpr = PerformCopyInitialization( 11115 InitializedEntity::InitializeResult(LPLoc, 11116 Ty, 11117 false), 11118 SourceLocation(), 11119 LastExpr); 11120 } 11121 11122 if (LastExpr.isInvalid()) 11123 return ExprError(); 11124 if (LastExpr.get() != nullptr) { 11125 if (!LastLabelStmt) 11126 Compound->setLastStmt(LastExpr.get()); 11127 else 11128 LastLabelStmt->setSubStmt(LastExpr.get()); 11129 StmtExprMayBindToTemp = true; 11130 } 11131 } 11132 } 11133 } 11134 11135 // FIXME: Check that expression type is complete/non-abstract; statement 11136 // expressions are not lvalues. 11137 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11138 if (StmtExprMayBindToTemp) 11139 return MaybeBindToTemporary(ResStmtExpr); 11140 return ResStmtExpr; 11141 } 11142 11143 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11144 TypeSourceInfo *TInfo, 11145 ArrayRef<OffsetOfComponent> Components, 11146 SourceLocation RParenLoc) { 11147 QualType ArgTy = TInfo->getType(); 11148 bool Dependent = ArgTy->isDependentType(); 11149 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11150 11151 // We must have at least one component that refers to the type, and the first 11152 // one is known to be a field designator. Verify that the ArgTy represents 11153 // a struct/union/class. 11154 if (!Dependent && !ArgTy->isRecordType()) 11155 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11156 << ArgTy << TypeRange); 11157 11158 // Type must be complete per C99 7.17p3 because a declaring a variable 11159 // with an incomplete type would be ill-formed. 11160 if (!Dependent 11161 && RequireCompleteType(BuiltinLoc, ArgTy, 11162 diag::err_offsetof_incomplete_type, TypeRange)) 11163 return ExprError(); 11164 11165 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11166 // GCC extension, diagnose them. 11167 // FIXME: This diagnostic isn't actually visible because the location is in 11168 // a system header! 11169 if (Components.size() != 1) 11170 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11171 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11172 11173 bool DidWarnAboutNonPOD = false; 11174 QualType CurrentType = ArgTy; 11175 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 11176 SmallVector<OffsetOfNode, 4> Comps; 11177 SmallVector<Expr*, 4> Exprs; 11178 for (const OffsetOfComponent &OC : Components) { 11179 if (OC.isBrackets) { 11180 // Offset of an array sub-field. TODO: Should we allow vector elements? 11181 if (!CurrentType->isDependentType()) { 11182 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11183 if(!AT) 11184 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11185 << CurrentType); 11186 CurrentType = AT->getElementType(); 11187 } else 11188 CurrentType = Context.DependentTy; 11189 11190 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11191 if (IdxRval.isInvalid()) 11192 return ExprError(); 11193 Expr *Idx = IdxRval.get(); 11194 11195 // The expression must be an integral expression. 11196 // FIXME: An integral constant expression? 11197 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11198 !Idx->getType()->isIntegerType()) 11199 return ExprError(Diag(Idx->getLocStart(), 11200 diag::err_typecheck_subscript_not_integer) 11201 << Idx->getSourceRange()); 11202 11203 // Record this array index. 11204 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11205 Exprs.push_back(Idx); 11206 continue; 11207 } 11208 11209 // Offset of a field. 11210 if (CurrentType->isDependentType()) { 11211 // We have the offset of a field, but we can't look into the dependent 11212 // type. Just record the identifier of the field. 11213 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11214 CurrentType = Context.DependentTy; 11215 continue; 11216 } 11217 11218 // We need to have a complete type to look into. 11219 if (RequireCompleteType(OC.LocStart, CurrentType, 11220 diag::err_offsetof_incomplete_type)) 11221 return ExprError(); 11222 11223 // Look for the designated field. 11224 const RecordType *RC = CurrentType->getAs<RecordType>(); 11225 if (!RC) 11226 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11227 << CurrentType); 11228 RecordDecl *RD = RC->getDecl(); 11229 11230 // C++ [lib.support.types]p5: 11231 // The macro offsetof accepts a restricted set of type arguments in this 11232 // International Standard. type shall be a POD structure or a POD union 11233 // (clause 9). 11234 // C++11 [support.types]p4: 11235 // If type is not a standard-layout class (Clause 9), the results are 11236 // undefined. 11237 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11238 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11239 unsigned DiagID = 11240 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11241 : diag::ext_offsetof_non_pod_type; 11242 11243 if (!IsSafe && !DidWarnAboutNonPOD && 11244 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11245 PDiag(DiagID) 11246 << SourceRange(Components[0].LocStart, OC.LocEnd) 11247 << CurrentType)) 11248 DidWarnAboutNonPOD = true; 11249 } 11250 11251 // Look for the field. 11252 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11253 LookupQualifiedName(R, RD); 11254 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11255 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11256 if (!MemberDecl) { 11257 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11258 MemberDecl = IndirectMemberDecl->getAnonField(); 11259 } 11260 11261 if (!MemberDecl) 11262 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11263 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11264 OC.LocEnd)); 11265 11266 // C99 7.17p3: 11267 // (If the specified member is a bit-field, the behavior is undefined.) 11268 // 11269 // We diagnose this as an error. 11270 if (MemberDecl->isBitField()) { 11271 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11272 << MemberDecl->getDeclName() 11273 << SourceRange(BuiltinLoc, RParenLoc); 11274 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11275 return ExprError(); 11276 } 11277 11278 RecordDecl *Parent = MemberDecl->getParent(); 11279 if (IndirectMemberDecl) 11280 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11281 11282 // If the member was found in a base class, introduce OffsetOfNodes for 11283 // the base class indirections. 11284 CXXBasePaths Paths; 11285 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 11286 if (Paths.getDetectedVirtual()) { 11287 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11288 << MemberDecl->getDeclName() 11289 << SourceRange(BuiltinLoc, RParenLoc); 11290 return ExprError(); 11291 } 11292 11293 CXXBasePath &Path = Paths.front(); 11294 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 11295 B != BEnd; ++B) 11296 Comps.push_back(OffsetOfNode(B->Base)); 11297 } 11298 11299 if (IndirectMemberDecl) { 11300 for (auto *FI : IndirectMemberDecl->chain()) { 11301 assert(isa<FieldDecl>(FI)); 11302 Comps.push_back(OffsetOfNode(OC.LocStart, 11303 cast<FieldDecl>(FI), OC.LocEnd)); 11304 } 11305 } else 11306 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11307 11308 CurrentType = MemberDecl->getType().getNonReferenceType(); 11309 } 11310 11311 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11312 Comps, Exprs, RParenLoc); 11313 } 11314 11315 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11316 SourceLocation BuiltinLoc, 11317 SourceLocation TypeLoc, 11318 ParsedType ParsedArgTy, 11319 ArrayRef<OffsetOfComponent> Components, 11320 SourceLocation RParenLoc) { 11321 11322 TypeSourceInfo *ArgTInfo; 11323 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11324 if (ArgTy.isNull()) 11325 return ExprError(); 11326 11327 if (!ArgTInfo) 11328 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11329 11330 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11331 } 11332 11333 11334 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11335 Expr *CondExpr, 11336 Expr *LHSExpr, Expr *RHSExpr, 11337 SourceLocation RPLoc) { 11338 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11339 11340 ExprValueKind VK = VK_RValue; 11341 ExprObjectKind OK = OK_Ordinary; 11342 QualType resType; 11343 bool ValueDependent = false; 11344 bool CondIsTrue = false; 11345 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11346 resType = Context.DependentTy; 11347 ValueDependent = true; 11348 } else { 11349 // The conditional expression is required to be a constant expression. 11350 llvm::APSInt condEval(32); 11351 ExprResult CondICE 11352 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11353 diag::err_typecheck_choose_expr_requires_constant, false); 11354 if (CondICE.isInvalid()) 11355 return ExprError(); 11356 CondExpr = CondICE.get(); 11357 CondIsTrue = condEval.getZExtValue(); 11358 11359 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11360 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11361 11362 resType = ActiveExpr->getType(); 11363 ValueDependent = ActiveExpr->isValueDependent(); 11364 VK = ActiveExpr->getValueKind(); 11365 OK = ActiveExpr->getObjectKind(); 11366 } 11367 11368 return new (Context) 11369 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11370 CondIsTrue, resType->isDependentType(), ValueDependent); 11371 } 11372 11373 //===----------------------------------------------------------------------===// 11374 // Clang Extensions. 11375 //===----------------------------------------------------------------------===// 11376 11377 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11378 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11379 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11380 11381 if (LangOpts.CPlusPlus) { 11382 Decl *ManglingContextDecl; 11383 if (MangleNumberingContext *MCtx = 11384 getCurrentMangleNumberContext(Block->getDeclContext(), 11385 ManglingContextDecl)) { 11386 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11387 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11388 } 11389 } 11390 11391 PushBlockScope(CurScope, Block); 11392 CurContext->addDecl(Block); 11393 if (CurScope) 11394 PushDeclContext(CurScope, Block); 11395 else 11396 CurContext = Block; 11397 11398 getCurBlock()->HasImplicitReturnType = true; 11399 11400 // Enter a new evaluation context to insulate the block from any 11401 // cleanups from the enclosing full-expression. 11402 PushExpressionEvaluationContext(PotentiallyEvaluated); 11403 } 11404 11405 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11406 Scope *CurScope) { 11407 assert(ParamInfo.getIdentifier() == nullptr && 11408 "block-id should have no identifier!"); 11409 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11410 BlockScopeInfo *CurBlock = getCurBlock(); 11411 11412 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11413 QualType T = Sig->getType(); 11414 11415 // FIXME: We should allow unexpanded parameter packs here, but that would, 11416 // in turn, make the block expression contain unexpanded parameter packs. 11417 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11418 // Drop the parameters. 11419 FunctionProtoType::ExtProtoInfo EPI; 11420 EPI.HasTrailingReturn = false; 11421 EPI.TypeQuals |= DeclSpec::TQ_const; 11422 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11423 Sig = Context.getTrivialTypeSourceInfo(T); 11424 } 11425 11426 // GetTypeForDeclarator always produces a function type for a block 11427 // literal signature. Furthermore, it is always a FunctionProtoType 11428 // unless the function was written with a typedef. 11429 assert(T->isFunctionType() && 11430 "GetTypeForDeclarator made a non-function block signature"); 11431 11432 // Look for an explicit signature in that function type. 11433 FunctionProtoTypeLoc ExplicitSignature; 11434 11435 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11436 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11437 11438 // Check whether that explicit signature was synthesized by 11439 // GetTypeForDeclarator. If so, don't save that as part of the 11440 // written signature. 11441 if (ExplicitSignature.getLocalRangeBegin() == 11442 ExplicitSignature.getLocalRangeEnd()) { 11443 // This would be much cheaper if we stored TypeLocs instead of 11444 // TypeSourceInfos. 11445 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11446 unsigned Size = Result.getFullDataSize(); 11447 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11448 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11449 11450 ExplicitSignature = FunctionProtoTypeLoc(); 11451 } 11452 } 11453 11454 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11455 CurBlock->FunctionType = T; 11456 11457 const FunctionType *Fn = T->getAs<FunctionType>(); 11458 QualType RetTy = Fn->getReturnType(); 11459 bool isVariadic = 11460 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11461 11462 CurBlock->TheDecl->setIsVariadic(isVariadic); 11463 11464 // Context.DependentTy is used as a placeholder for a missing block 11465 // return type. TODO: what should we do with declarators like: 11466 // ^ * { ... } 11467 // If the answer is "apply template argument deduction".... 11468 if (RetTy != Context.DependentTy) { 11469 CurBlock->ReturnType = RetTy; 11470 CurBlock->TheDecl->setBlockMissingReturnType(false); 11471 CurBlock->HasImplicitReturnType = false; 11472 } 11473 11474 // Push block parameters from the declarator if we had them. 11475 SmallVector<ParmVarDecl*, 8> Params; 11476 if (ExplicitSignature) { 11477 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11478 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11479 if (Param->getIdentifier() == nullptr && 11480 !Param->isImplicit() && 11481 !Param->isInvalidDecl() && 11482 !getLangOpts().CPlusPlus) 11483 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11484 Params.push_back(Param); 11485 } 11486 11487 // Fake up parameter variables if we have a typedef, like 11488 // ^ fntype { ... } 11489 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11490 for (const auto &I : Fn->param_types()) { 11491 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11492 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11493 Params.push_back(Param); 11494 } 11495 } 11496 11497 // Set the parameters on the block decl. 11498 if (!Params.empty()) { 11499 CurBlock->TheDecl->setParams(Params); 11500 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11501 CurBlock->TheDecl->param_end(), 11502 /*CheckParameterNames=*/false); 11503 } 11504 11505 // Finally we can process decl attributes. 11506 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11507 11508 // Put the parameter variables in scope. 11509 for (auto AI : CurBlock->TheDecl->params()) { 11510 AI->setOwningFunction(CurBlock->TheDecl); 11511 11512 // If this has an identifier, add it to the scope stack. 11513 if (AI->getIdentifier()) { 11514 CheckShadow(CurBlock->TheScope, AI); 11515 11516 PushOnScopeChains(AI, CurBlock->TheScope); 11517 } 11518 } 11519 } 11520 11521 /// ActOnBlockError - If there is an error parsing a block, this callback 11522 /// is invoked to pop the information about the block from the action impl. 11523 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11524 // Leave the expression-evaluation context. 11525 DiscardCleanupsInEvaluationContext(); 11526 PopExpressionEvaluationContext(); 11527 11528 // Pop off CurBlock, handle nested blocks. 11529 PopDeclContext(); 11530 PopFunctionScopeInfo(); 11531 } 11532 11533 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11534 /// literal was successfully completed. ^(int x){...} 11535 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11536 Stmt *Body, Scope *CurScope) { 11537 // If blocks are disabled, emit an error. 11538 if (!LangOpts.Blocks) 11539 Diag(CaretLoc, diag::err_blocks_disable); 11540 11541 // Leave the expression-evaluation context. 11542 if (hasAnyUnrecoverableErrorsInThisFunction()) 11543 DiscardCleanupsInEvaluationContext(); 11544 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11545 PopExpressionEvaluationContext(); 11546 11547 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11548 11549 if (BSI->HasImplicitReturnType) 11550 deduceClosureReturnType(*BSI); 11551 11552 PopDeclContext(); 11553 11554 QualType RetTy = Context.VoidTy; 11555 if (!BSI->ReturnType.isNull()) 11556 RetTy = BSI->ReturnType; 11557 11558 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11559 QualType BlockTy; 11560 11561 // Set the captured variables on the block. 11562 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11563 SmallVector<BlockDecl::Capture, 4> Captures; 11564 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 11565 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 11566 if (Cap.isThisCapture()) 11567 continue; 11568 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11569 Cap.isNested(), Cap.getInitExpr()); 11570 Captures.push_back(NewCap); 11571 } 11572 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 11573 11574 // If the user wrote a function type in some form, try to use that. 11575 if (!BSI->FunctionType.isNull()) { 11576 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11577 11578 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11579 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11580 11581 // Turn protoless block types into nullary block types. 11582 if (isa<FunctionNoProtoType>(FTy)) { 11583 FunctionProtoType::ExtProtoInfo EPI; 11584 EPI.ExtInfo = Ext; 11585 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11586 11587 // Otherwise, if we don't need to change anything about the function type, 11588 // preserve its sugar structure. 11589 } else if (FTy->getReturnType() == RetTy && 11590 (!NoReturn || FTy->getNoReturnAttr())) { 11591 BlockTy = BSI->FunctionType; 11592 11593 // Otherwise, make the minimal modifications to the function type. 11594 } else { 11595 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11596 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11597 EPI.TypeQuals = 0; // FIXME: silently? 11598 EPI.ExtInfo = Ext; 11599 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11600 } 11601 11602 // If we don't have a function type, just build one from nothing. 11603 } else { 11604 FunctionProtoType::ExtProtoInfo EPI; 11605 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11606 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11607 } 11608 11609 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11610 BSI->TheDecl->param_end()); 11611 BlockTy = Context.getBlockPointerType(BlockTy); 11612 11613 // If needed, diagnose invalid gotos and switches in the block. 11614 if (getCurFunction()->NeedsScopeChecking() && 11615 !PP.isCodeCompletionEnabled()) 11616 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11617 11618 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11619 11620 // Try to apply the named return value optimization. We have to check again 11621 // if we can do this, though, because blocks keep return statements around 11622 // to deduce an implicit return type. 11623 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11624 !BSI->TheDecl->isDependentContext()) 11625 computeNRVO(Body, BSI); 11626 11627 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11628 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11629 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11630 11631 // If the block isn't obviously global, i.e. it captures anything at 11632 // all, then we need to do a few things in the surrounding context: 11633 if (Result->getBlockDecl()->hasCaptures()) { 11634 // First, this expression has a new cleanup object. 11635 ExprCleanupObjects.push_back(Result->getBlockDecl()); 11636 ExprNeedsCleanups = true; 11637 11638 // It also gets a branch-protected scope if any of the captured 11639 // variables needs destruction. 11640 for (const auto &CI : Result->getBlockDecl()->captures()) { 11641 const VarDecl *var = CI.getVariable(); 11642 if (var->getType().isDestructedType() != QualType::DK_none) { 11643 getCurFunction()->setHasBranchProtectedScope(); 11644 break; 11645 } 11646 } 11647 } 11648 11649 return Result; 11650 } 11651 11652 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 11653 Expr *E, ParsedType Ty, 11654 SourceLocation RPLoc) { 11655 TypeSourceInfo *TInfo; 11656 GetTypeFromParser(Ty, &TInfo); 11657 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 11658 } 11659 11660 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 11661 Expr *E, TypeSourceInfo *TInfo, 11662 SourceLocation RPLoc) { 11663 Expr *OrigExpr = E; 11664 bool IsMS = false; 11665 11666 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 11667 // as Microsoft ABI on an actual Microsoft platform, where 11668 // __builtin_ms_va_list and __builtin_va_list are the same.) 11669 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 11670 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 11671 QualType MSVaListType = Context.getBuiltinMSVaListType(); 11672 if (Context.hasSameType(MSVaListType, E->getType())) { 11673 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11674 return ExprError(); 11675 IsMS = true; 11676 } 11677 } 11678 11679 // Get the va_list type 11680 QualType VaListType = Context.getBuiltinVaListType(); 11681 if (!IsMS) { 11682 if (VaListType->isArrayType()) { 11683 // Deal with implicit array decay; for example, on x86-64, 11684 // va_list is an array, but it's supposed to decay to 11685 // a pointer for va_arg. 11686 VaListType = Context.getArrayDecayedType(VaListType); 11687 // Make sure the input expression also decays appropriately. 11688 ExprResult Result = UsualUnaryConversions(E); 11689 if (Result.isInvalid()) 11690 return ExprError(); 11691 E = Result.get(); 11692 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 11693 // If va_list is a record type and we are compiling in C++ mode, 11694 // check the argument using reference binding. 11695 InitializedEntity Entity = InitializedEntity::InitializeParameter( 11696 Context, Context.getLValueReferenceType(VaListType), false); 11697 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 11698 if (Init.isInvalid()) 11699 return ExprError(); 11700 E = Init.getAs<Expr>(); 11701 } else { 11702 // Otherwise, the va_list argument must be an l-value because 11703 // it is modified by va_arg. 11704 if (!E->isTypeDependent() && 11705 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11706 return ExprError(); 11707 } 11708 } 11709 11710 if (!IsMS && !E->isTypeDependent() && 11711 !Context.hasSameType(VaListType, E->getType())) 11712 return ExprError(Diag(E->getLocStart(), 11713 diag::err_first_argument_to_va_arg_not_of_type_va_list) 11714 << OrigExpr->getType() << E->getSourceRange()); 11715 11716 if (!TInfo->getType()->isDependentType()) { 11717 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 11718 diag::err_second_parameter_to_va_arg_incomplete, 11719 TInfo->getTypeLoc())) 11720 return ExprError(); 11721 11722 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 11723 TInfo->getType(), 11724 diag::err_second_parameter_to_va_arg_abstract, 11725 TInfo->getTypeLoc())) 11726 return ExprError(); 11727 11728 if (!TInfo->getType().isPODType(Context)) { 11729 Diag(TInfo->getTypeLoc().getBeginLoc(), 11730 TInfo->getType()->isObjCLifetimeType() 11731 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 11732 : diag::warn_second_parameter_to_va_arg_not_pod) 11733 << TInfo->getType() 11734 << TInfo->getTypeLoc().getSourceRange(); 11735 } 11736 11737 // Check for va_arg where arguments of the given type will be promoted 11738 // (i.e. this va_arg is guaranteed to have undefined behavior). 11739 QualType PromoteType; 11740 if (TInfo->getType()->isPromotableIntegerType()) { 11741 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 11742 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 11743 PromoteType = QualType(); 11744 } 11745 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 11746 PromoteType = Context.DoubleTy; 11747 if (!PromoteType.isNull()) 11748 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 11749 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 11750 << TInfo->getType() 11751 << PromoteType 11752 << TInfo->getTypeLoc().getSourceRange()); 11753 } 11754 11755 QualType T = TInfo->getType().getNonLValueExprType(Context); 11756 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 11757 } 11758 11759 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 11760 // The type of __null will be int or long, depending on the size of 11761 // pointers on the target. 11762 QualType Ty; 11763 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 11764 if (pw == Context.getTargetInfo().getIntWidth()) 11765 Ty = Context.IntTy; 11766 else if (pw == Context.getTargetInfo().getLongWidth()) 11767 Ty = Context.LongTy; 11768 else if (pw == Context.getTargetInfo().getLongLongWidth()) 11769 Ty = Context.LongLongTy; 11770 else { 11771 llvm_unreachable("I don't know size of pointer!"); 11772 } 11773 11774 return new (Context) GNUNullExpr(Ty, TokenLoc); 11775 } 11776 11777 bool 11778 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 11779 if (!getLangOpts().ObjC1) 11780 return false; 11781 11782 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 11783 if (!PT) 11784 return false; 11785 11786 if (!PT->isObjCIdType()) { 11787 // Check if the destination is the 'NSString' interface. 11788 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 11789 if (!ID || !ID->getIdentifier()->isStr("NSString")) 11790 return false; 11791 } 11792 11793 // Ignore any parens, implicit casts (should only be 11794 // array-to-pointer decays), and not-so-opaque values. The last is 11795 // important for making this trigger for property assignments. 11796 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 11797 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 11798 if (OV->getSourceExpr()) 11799 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 11800 11801 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 11802 if (!SL || !SL->isAscii()) 11803 return false; 11804 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 11805 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 11806 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 11807 return true; 11808 } 11809 11810 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 11811 SourceLocation Loc, 11812 QualType DstType, QualType SrcType, 11813 Expr *SrcExpr, AssignmentAction Action, 11814 bool *Complained) { 11815 if (Complained) 11816 *Complained = false; 11817 11818 // Decode the result (notice that AST's are still created for extensions). 11819 bool CheckInferredResultType = false; 11820 bool isInvalid = false; 11821 unsigned DiagKind = 0; 11822 FixItHint Hint; 11823 ConversionFixItGenerator ConvHints; 11824 bool MayHaveConvFixit = false; 11825 bool MayHaveFunctionDiff = false; 11826 const ObjCInterfaceDecl *IFace = nullptr; 11827 const ObjCProtocolDecl *PDecl = nullptr; 11828 11829 switch (ConvTy) { 11830 case Compatible: 11831 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 11832 return false; 11833 11834 case PointerToInt: 11835 DiagKind = diag::ext_typecheck_convert_pointer_int; 11836 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11837 MayHaveConvFixit = true; 11838 break; 11839 case IntToPointer: 11840 DiagKind = diag::ext_typecheck_convert_int_pointer; 11841 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11842 MayHaveConvFixit = true; 11843 break; 11844 case IncompatiblePointer: 11845 DiagKind = 11846 (Action == AA_Passing_CFAudited ? 11847 diag::err_arc_typecheck_convert_incompatible_pointer : 11848 diag::ext_typecheck_convert_incompatible_pointer); 11849 CheckInferredResultType = DstType->isObjCObjectPointerType() && 11850 SrcType->isObjCObjectPointerType(); 11851 if (Hint.isNull() && !CheckInferredResultType) { 11852 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11853 } 11854 else if (CheckInferredResultType) { 11855 SrcType = SrcType.getUnqualifiedType(); 11856 DstType = DstType.getUnqualifiedType(); 11857 } 11858 MayHaveConvFixit = true; 11859 break; 11860 case IncompatiblePointerSign: 11861 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 11862 break; 11863 case FunctionVoidPointer: 11864 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 11865 break; 11866 case IncompatiblePointerDiscardsQualifiers: { 11867 // Perform array-to-pointer decay if necessary. 11868 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 11869 11870 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 11871 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 11872 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 11873 DiagKind = diag::err_typecheck_incompatible_address_space; 11874 break; 11875 11876 11877 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 11878 DiagKind = diag::err_typecheck_incompatible_ownership; 11879 break; 11880 } 11881 11882 llvm_unreachable("unknown error case for discarding qualifiers!"); 11883 // fallthrough 11884 } 11885 case CompatiblePointerDiscardsQualifiers: 11886 // If the qualifiers lost were because we were applying the 11887 // (deprecated) C++ conversion from a string literal to a char* 11888 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 11889 // Ideally, this check would be performed in 11890 // checkPointerTypesForAssignment. However, that would require a 11891 // bit of refactoring (so that the second argument is an 11892 // expression, rather than a type), which should be done as part 11893 // of a larger effort to fix checkPointerTypesForAssignment for 11894 // C++ semantics. 11895 if (getLangOpts().CPlusPlus && 11896 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 11897 return false; 11898 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 11899 break; 11900 case IncompatibleNestedPointerQualifiers: 11901 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 11902 break; 11903 case IntToBlockPointer: 11904 DiagKind = diag::err_int_to_block_pointer; 11905 break; 11906 case IncompatibleBlockPointer: 11907 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 11908 break; 11909 case IncompatibleObjCQualifiedId: { 11910 if (SrcType->isObjCQualifiedIdType()) { 11911 const ObjCObjectPointerType *srcOPT = 11912 SrcType->getAs<ObjCObjectPointerType>(); 11913 for (auto *srcProto : srcOPT->quals()) { 11914 PDecl = srcProto; 11915 break; 11916 } 11917 if (const ObjCInterfaceType *IFaceT = 11918 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11919 IFace = IFaceT->getDecl(); 11920 } 11921 else if (DstType->isObjCQualifiedIdType()) { 11922 const ObjCObjectPointerType *dstOPT = 11923 DstType->getAs<ObjCObjectPointerType>(); 11924 for (auto *dstProto : dstOPT->quals()) { 11925 PDecl = dstProto; 11926 break; 11927 } 11928 if (const ObjCInterfaceType *IFaceT = 11929 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11930 IFace = IFaceT->getDecl(); 11931 } 11932 DiagKind = diag::warn_incompatible_qualified_id; 11933 break; 11934 } 11935 case IncompatibleVectors: 11936 DiagKind = diag::warn_incompatible_vectors; 11937 break; 11938 case IncompatibleObjCWeakRef: 11939 DiagKind = diag::err_arc_weak_unavailable_assign; 11940 break; 11941 case Incompatible: 11942 DiagKind = diag::err_typecheck_convert_incompatible; 11943 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11944 MayHaveConvFixit = true; 11945 isInvalid = true; 11946 MayHaveFunctionDiff = true; 11947 break; 11948 } 11949 11950 QualType FirstType, SecondType; 11951 switch (Action) { 11952 case AA_Assigning: 11953 case AA_Initializing: 11954 // The destination type comes first. 11955 FirstType = DstType; 11956 SecondType = SrcType; 11957 break; 11958 11959 case AA_Returning: 11960 case AA_Passing: 11961 case AA_Passing_CFAudited: 11962 case AA_Converting: 11963 case AA_Sending: 11964 case AA_Casting: 11965 // The source type comes first. 11966 FirstType = SrcType; 11967 SecondType = DstType; 11968 break; 11969 } 11970 11971 PartialDiagnostic FDiag = PDiag(DiagKind); 11972 if (Action == AA_Passing_CFAudited) 11973 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 11974 else 11975 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 11976 11977 // If we can fix the conversion, suggest the FixIts. 11978 assert(ConvHints.isNull() || Hint.isNull()); 11979 if (!ConvHints.isNull()) { 11980 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 11981 HE = ConvHints.Hints.end(); HI != HE; ++HI) 11982 FDiag << *HI; 11983 } else { 11984 FDiag << Hint; 11985 } 11986 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 11987 11988 if (MayHaveFunctionDiff) 11989 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 11990 11991 Diag(Loc, FDiag); 11992 if (DiagKind == diag::warn_incompatible_qualified_id && 11993 PDecl && IFace && !IFace->hasDefinition()) 11994 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 11995 << IFace->getName() << PDecl->getName(); 11996 11997 if (SecondType == Context.OverloadTy) 11998 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 11999 FirstType, /*TakingAddress=*/true); 12000 12001 if (CheckInferredResultType) 12002 EmitRelatedResultTypeNote(SrcExpr); 12003 12004 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12005 EmitRelatedResultTypeNoteForReturn(DstType); 12006 12007 if (Complained) 12008 *Complained = true; 12009 return isInvalid; 12010 } 12011 12012 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12013 llvm::APSInt *Result) { 12014 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12015 public: 12016 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12017 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12018 } 12019 } Diagnoser; 12020 12021 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12022 } 12023 12024 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12025 llvm::APSInt *Result, 12026 unsigned DiagID, 12027 bool AllowFold) { 12028 class IDDiagnoser : public VerifyICEDiagnoser { 12029 unsigned DiagID; 12030 12031 public: 12032 IDDiagnoser(unsigned DiagID) 12033 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12034 12035 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12036 S.Diag(Loc, DiagID) << SR; 12037 } 12038 } Diagnoser(DiagID); 12039 12040 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12041 } 12042 12043 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12044 SourceRange SR) { 12045 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12046 } 12047 12048 ExprResult 12049 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12050 VerifyICEDiagnoser &Diagnoser, 12051 bool AllowFold) { 12052 SourceLocation DiagLoc = E->getLocStart(); 12053 12054 if (getLangOpts().CPlusPlus11) { 12055 // C++11 [expr.const]p5: 12056 // If an expression of literal class type is used in a context where an 12057 // integral constant expression is required, then that class type shall 12058 // have a single non-explicit conversion function to an integral or 12059 // unscoped enumeration type 12060 ExprResult Converted; 12061 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12062 public: 12063 CXX11ConvertDiagnoser(bool Silent) 12064 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12065 Silent, true) {} 12066 12067 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12068 QualType T) override { 12069 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12070 } 12071 12072 SemaDiagnosticBuilder diagnoseIncomplete( 12073 Sema &S, SourceLocation Loc, QualType T) override { 12074 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12075 } 12076 12077 SemaDiagnosticBuilder diagnoseExplicitConv( 12078 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12079 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12080 } 12081 12082 SemaDiagnosticBuilder noteExplicitConv( 12083 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12084 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12085 << ConvTy->isEnumeralType() << ConvTy; 12086 } 12087 12088 SemaDiagnosticBuilder diagnoseAmbiguous( 12089 Sema &S, SourceLocation Loc, QualType T) override { 12090 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12091 } 12092 12093 SemaDiagnosticBuilder noteAmbiguous( 12094 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12095 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12096 << ConvTy->isEnumeralType() << ConvTy; 12097 } 12098 12099 SemaDiagnosticBuilder diagnoseConversion( 12100 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12101 llvm_unreachable("conversion functions are permitted"); 12102 } 12103 } ConvertDiagnoser(Diagnoser.Suppress); 12104 12105 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12106 ConvertDiagnoser); 12107 if (Converted.isInvalid()) 12108 return Converted; 12109 E = Converted.get(); 12110 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12111 return ExprError(); 12112 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12113 // An ICE must be of integral or unscoped enumeration type. 12114 if (!Diagnoser.Suppress) 12115 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12116 return ExprError(); 12117 } 12118 12119 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12120 // in the non-ICE case. 12121 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12122 if (Result) 12123 *Result = E->EvaluateKnownConstInt(Context); 12124 return E; 12125 } 12126 12127 Expr::EvalResult EvalResult; 12128 SmallVector<PartialDiagnosticAt, 8> Notes; 12129 EvalResult.Diag = &Notes; 12130 12131 // Try to evaluate the expression, and produce diagnostics explaining why it's 12132 // not a constant expression as a side-effect. 12133 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12134 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12135 12136 // In C++11, we can rely on diagnostics being produced for any expression 12137 // which is not a constant expression. If no diagnostics were produced, then 12138 // this is a constant expression. 12139 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12140 if (Result) 12141 *Result = EvalResult.Val.getInt(); 12142 return E; 12143 } 12144 12145 // If our only note is the usual "invalid subexpression" note, just point 12146 // the caret at its location rather than producing an essentially 12147 // redundant note. 12148 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12149 diag::note_invalid_subexpr_in_const_expr) { 12150 DiagLoc = Notes[0].first; 12151 Notes.clear(); 12152 } 12153 12154 if (!Folded || !AllowFold) { 12155 if (!Diagnoser.Suppress) { 12156 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12157 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12158 Diag(Notes[I].first, Notes[I].second); 12159 } 12160 12161 return ExprError(); 12162 } 12163 12164 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12165 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12166 Diag(Notes[I].first, Notes[I].second); 12167 12168 if (Result) 12169 *Result = EvalResult.Val.getInt(); 12170 return E; 12171 } 12172 12173 namespace { 12174 // Handle the case where we conclude a expression which we speculatively 12175 // considered to be unevaluated is actually evaluated. 12176 class TransformToPE : public TreeTransform<TransformToPE> { 12177 typedef TreeTransform<TransformToPE> BaseTransform; 12178 12179 public: 12180 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12181 12182 // Make sure we redo semantic analysis 12183 bool AlwaysRebuild() { return true; } 12184 12185 // Make sure we handle LabelStmts correctly. 12186 // FIXME: This does the right thing, but maybe we need a more general 12187 // fix to TreeTransform? 12188 StmtResult TransformLabelStmt(LabelStmt *S) { 12189 S->getDecl()->setStmt(nullptr); 12190 return BaseTransform::TransformLabelStmt(S); 12191 } 12192 12193 // We need to special-case DeclRefExprs referring to FieldDecls which 12194 // are not part of a member pointer formation; normal TreeTransforming 12195 // doesn't catch this case because of the way we represent them in the AST. 12196 // FIXME: This is a bit ugly; is it really the best way to handle this 12197 // case? 12198 // 12199 // Error on DeclRefExprs referring to FieldDecls. 12200 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12201 if (isa<FieldDecl>(E->getDecl()) && 12202 !SemaRef.isUnevaluatedContext()) 12203 return SemaRef.Diag(E->getLocation(), 12204 diag::err_invalid_non_static_member_use) 12205 << E->getDecl() << E->getSourceRange(); 12206 12207 return BaseTransform::TransformDeclRefExpr(E); 12208 } 12209 12210 // Exception: filter out member pointer formation 12211 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12212 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12213 return E; 12214 12215 return BaseTransform::TransformUnaryOperator(E); 12216 } 12217 12218 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12219 // Lambdas never need to be transformed. 12220 return E; 12221 } 12222 }; 12223 } 12224 12225 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12226 assert(isUnevaluatedContext() && 12227 "Should only transform unevaluated expressions"); 12228 ExprEvalContexts.back().Context = 12229 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12230 if (isUnevaluatedContext()) 12231 return E; 12232 return TransformToPE(*this).TransformExpr(E); 12233 } 12234 12235 void 12236 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12237 Decl *LambdaContextDecl, 12238 bool IsDecltype) { 12239 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12240 ExprNeedsCleanups, LambdaContextDecl, 12241 IsDecltype); 12242 ExprNeedsCleanups = false; 12243 if (!MaybeODRUseExprs.empty()) 12244 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12245 } 12246 12247 void 12248 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12249 ReuseLambdaContextDecl_t, 12250 bool IsDecltype) { 12251 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12252 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12253 } 12254 12255 void Sema::PopExpressionEvaluationContext() { 12256 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12257 unsigned NumTypos = Rec.NumTypos; 12258 12259 if (!Rec.Lambdas.empty()) { 12260 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12261 unsigned D; 12262 if (Rec.isUnevaluated()) { 12263 // C++11 [expr.prim.lambda]p2: 12264 // A lambda-expression shall not appear in an unevaluated operand 12265 // (Clause 5). 12266 D = diag::err_lambda_unevaluated_operand; 12267 } else { 12268 // C++1y [expr.const]p2: 12269 // A conditional-expression e is a core constant expression unless the 12270 // evaluation of e, following the rules of the abstract machine, would 12271 // evaluate [...] a lambda-expression. 12272 D = diag::err_lambda_in_constant_expression; 12273 } 12274 for (const auto *L : Rec.Lambdas) 12275 Diag(L->getLocStart(), D); 12276 } else { 12277 // Mark the capture expressions odr-used. This was deferred 12278 // during lambda expression creation. 12279 for (auto *Lambda : Rec.Lambdas) { 12280 for (auto *C : Lambda->capture_inits()) 12281 MarkDeclarationsReferencedInExpr(C); 12282 } 12283 } 12284 } 12285 12286 // When are coming out of an unevaluated context, clear out any 12287 // temporaries that we may have created as part of the evaluation of 12288 // the expression in that context: they aren't relevant because they 12289 // will never be constructed. 12290 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12291 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12292 ExprCleanupObjects.end()); 12293 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12294 CleanupVarDeclMarking(); 12295 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12296 // Otherwise, merge the contexts together. 12297 } else { 12298 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12299 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12300 Rec.SavedMaybeODRUseExprs.end()); 12301 } 12302 12303 // Pop the current expression evaluation context off the stack. 12304 ExprEvalContexts.pop_back(); 12305 12306 if (!ExprEvalContexts.empty()) 12307 ExprEvalContexts.back().NumTypos += NumTypos; 12308 else 12309 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12310 "last ExpressionEvaluationContextRecord"); 12311 } 12312 12313 void Sema::DiscardCleanupsInEvaluationContext() { 12314 ExprCleanupObjects.erase( 12315 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12316 ExprCleanupObjects.end()); 12317 ExprNeedsCleanups = false; 12318 MaybeODRUseExprs.clear(); 12319 } 12320 12321 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12322 if (!E->getType()->isVariablyModifiedType()) 12323 return E; 12324 return TransformToPotentiallyEvaluated(E); 12325 } 12326 12327 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12328 // Do not mark anything as "used" within a dependent context; wait for 12329 // an instantiation. 12330 if (SemaRef.CurContext->isDependentContext()) 12331 return false; 12332 12333 switch (SemaRef.ExprEvalContexts.back().Context) { 12334 case Sema::Unevaluated: 12335 case Sema::UnevaluatedAbstract: 12336 // We are in an expression that is not potentially evaluated; do nothing. 12337 // (Depending on how you read the standard, we actually do need to do 12338 // something here for null pointer constants, but the standard's 12339 // definition of a null pointer constant is completely crazy.) 12340 return false; 12341 12342 case Sema::ConstantEvaluated: 12343 case Sema::PotentiallyEvaluated: 12344 // We are in a potentially evaluated expression (or a constant-expression 12345 // in C++03); we need to do implicit template instantiation, implicitly 12346 // define class members, and mark most declarations as used. 12347 return true; 12348 12349 case Sema::PotentiallyEvaluatedIfUsed: 12350 // Referenced declarations will only be used if the construct in the 12351 // containing expression is used. 12352 return false; 12353 } 12354 llvm_unreachable("Invalid context"); 12355 } 12356 12357 /// \brief Mark a function referenced, and check whether it is odr-used 12358 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12359 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12360 bool OdrUse) { 12361 assert(Func && "No function?"); 12362 12363 Func->setReferenced(); 12364 12365 // C++11 [basic.def.odr]p3: 12366 // A function whose name appears as a potentially-evaluated expression is 12367 // odr-used if it is the unique lookup result or the selected member of a 12368 // set of overloaded functions [...]. 12369 // 12370 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12371 // can just check that here. Skip the rest of this function if we've already 12372 // marked the function as used. 12373 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12374 !IsPotentiallyEvaluatedContext(*this)) { 12375 // C++11 [temp.inst]p3: 12376 // Unless a function template specialization has been explicitly 12377 // instantiated or explicitly specialized, the function template 12378 // specialization is implicitly instantiated when the specialization is 12379 // referenced in a context that requires a function definition to exist. 12380 // 12381 // We consider constexpr function templates to be referenced in a context 12382 // that requires a definition to exist whenever they are referenced. 12383 // 12384 // FIXME: This instantiates constexpr functions too frequently. If this is 12385 // really an unevaluated context (and we're not just in the definition of a 12386 // function template or overload resolution or other cases which we 12387 // incorrectly consider to be unevaluated contexts), and we're not in a 12388 // subexpression which we actually need to evaluate (for instance, a 12389 // template argument, array bound or an expression in a braced-init-list), 12390 // we are not permitted to instantiate this constexpr function definition. 12391 // 12392 // FIXME: This also implicitly defines special members too frequently. They 12393 // are only supposed to be implicitly defined if they are odr-used, but they 12394 // are not odr-used from constant expressions in unevaluated contexts. 12395 // However, they cannot be referenced if they are deleted, and they are 12396 // deleted whenever the implicit definition of the special member would 12397 // fail. 12398 if (!Func->isConstexpr() || Func->getBody()) 12399 return; 12400 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12401 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12402 return; 12403 } 12404 12405 // Note that this declaration has been used. 12406 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12407 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12408 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12409 if (Constructor->isDefaultConstructor()) { 12410 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12411 return; 12412 DefineImplicitDefaultConstructor(Loc, Constructor); 12413 } else if (Constructor->isCopyConstructor()) { 12414 DefineImplicitCopyConstructor(Loc, Constructor); 12415 } else if (Constructor->isMoveConstructor()) { 12416 DefineImplicitMoveConstructor(Loc, Constructor); 12417 } 12418 } else if (Constructor->getInheritedConstructor()) { 12419 DefineInheritingConstructor(Loc, Constructor); 12420 } 12421 } else if (CXXDestructorDecl *Destructor = 12422 dyn_cast<CXXDestructorDecl>(Func)) { 12423 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12424 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12425 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12426 return; 12427 DefineImplicitDestructor(Loc, Destructor); 12428 } 12429 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12430 MarkVTableUsed(Loc, Destructor->getParent()); 12431 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12432 if (MethodDecl->isOverloadedOperator() && 12433 MethodDecl->getOverloadedOperator() == OO_Equal) { 12434 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12435 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12436 if (MethodDecl->isCopyAssignmentOperator()) 12437 DefineImplicitCopyAssignment(Loc, MethodDecl); 12438 else 12439 DefineImplicitMoveAssignment(Loc, MethodDecl); 12440 } 12441 } else if (isa<CXXConversionDecl>(MethodDecl) && 12442 MethodDecl->getParent()->isLambda()) { 12443 CXXConversionDecl *Conversion = 12444 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12445 if (Conversion->isLambdaToBlockPointerConversion()) 12446 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12447 else 12448 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12449 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12450 MarkVTableUsed(Loc, MethodDecl->getParent()); 12451 } 12452 12453 // Recursive functions should be marked when used from another function. 12454 // FIXME: Is this really right? 12455 if (CurContext == Func) return; 12456 12457 // Resolve the exception specification for any function which is 12458 // used: CodeGen will need it. 12459 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12460 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12461 ResolveExceptionSpec(Loc, FPT); 12462 12463 if (!OdrUse) return; 12464 12465 // Implicit instantiation of function templates and member functions of 12466 // class templates. 12467 if (Func->isImplicitlyInstantiable()) { 12468 bool AlreadyInstantiated = false; 12469 SourceLocation PointOfInstantiation = Loc; 12470 if (FunctionTemplateSpecializationInfo *SpecInfo 12471 = Func->getTemplateSpecializationInfo()) { 12472 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12473 SpecInfo->setPointOfInstantiation(Loc); 12474 else if (SpecInfo->getTemplateSpecializationKind() 12475 == TSK_ImplicitInstantiation) { 12476 AlreadyInstantiated = true; 12477 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12478 } 12479 } else if (MemberSpecializationInfo *MSInfo 12480 = Func->getMemberSpecializationInfo()) { 12481 if (MSInfo->getPointOfInstantiation().isInvalid()) 12482 MSInfo->setPointOfInstantiation(Loc); 12483 else if (MSInfo->getTemplateSpecializationKind() 12484 == TSK_ImplicitInstantiation) { 12485 AlreadyInstantiated = true; 12486 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12487 } 12488 } 12489 12490 if (!AlreadyInstantiated || Func->isConstexpr()) { 12491 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12492 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12493 ActiveTemplateInstantiations.size()) 12494 PendingLocalImplicitInstantiations.push_back( 12495 std::make_pair(Func, PointOfInstantiation)); 12496 else if (Func->isConstexpr()) 12497 // Do not defer instantiations of constexpr functions, to avoid the 12498 // expression evaluator needing to call back into Sema if it sees a 12499 // call to such a function. 12500 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12501 else { 12502 PendingInstantiations.push_back(std::make_pair(Func, 12503 PointOfInstantiation)); 12504 // Notify the consumer that a function was implicitly instantiated. 12505 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12506 } 12507 } 12508 } else { 12509 // Walk redefinitions, as some of them may be instantiable. 12510 for (auto i : Func->redecls()) { 12511 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12512 MarkFunctionReferenced(Loc, i); 12513 } 12514 } 12515 12516 // Keep track of used but undefined functions. 12517 if (!Func->isDefined()) { 12518 if (mightHaveNonExternalLinkage(Func)) 12519 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12520 else if (Func->getMostRecentDecl()->isInlined() && 12521 !LangOpts.GNUInline && 12522 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12523 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12524 } 12525 12526 // Normally the most current decl is marked used while processing the use and 12527 // any subsequent decls are marked used by decl merging. This fails with 12528 // template instantiation since marking can happen at the end of the file 12529 // and, because of the two phase lookup, this function is called with at 12530 // decl in the middle of a decl chain. We loop to maintain the invariant 12531 // that once a decl is used, all decls after it are also used. 12532 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12533 F->markUsed(Context); 12534 if (F == Func) 12535 break; 12536 } 12537 } 12538 12539 static void 12540 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12541 VarDecl *var, DeclContext *DC) { 12542 DeclContext *VarDC = var->getDeclContext(); 12543 12544 // If the parameter still belongs to the translation unit, then 12545 // we're actually just using one parameter in the declaration of 12546 // the next. 12547 if (isa<ParmVarDecl>(var) && 12548 isa<TranslationUnitDecl>(VarDC)) 12549 return; 12550 12551 // For C code, don't diagnose about capture if we're not actually in code 12552 // right now; it's impossible to write a non-constant expression outside of 12553 // function context, so we'll get other (more useful) diagnostics later. 12554 // 12555 // For C++, things get a bit more nasty... it would be nice to suppress this 12556 // diagnostic for certain cases like using a local variable in an array bound 12557 // for a member of a local class, but the correct predicate is not obvious. 12558 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12559 return; 12560 12561 if (isa<CXXMethodDecl>(VarDC) && 12562 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12563 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12564 << var->getIdentifier(); 12565 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12566 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12567 << var->getIdentifier() << fn->getDeclName(); 12568 } else if (isa<BlockDecl>(VarDC)) { 12569 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12570 << var->getIdentifier(); 12571 } else { 12572 // FIXME: Is there any other context where a local variable can be 12573 // declared? 12574 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12575 << var->getIdentifier(); 12576 } 12577 12578 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12579 << var->getIdentifier(); 12580 12581 // FIXME: Add additional diagnostic info about class etc. which prevents 12582 // capture. 12583 } 12584 12585 12586 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12587 bool &SubCapturesAreNested, 12588 QualType &CaptureType, 12589 QualType &DeclRefType) { 12590 // Check whether we've already captured it. 12591 if (CSI->CaptureMap.count(Var)) { 12592 // If we found a capture, any subcaptures are nested. 12593 SubCapturesAreNested = true; 12594 12595 // Retrieve the capture type for this variable. 12596 CaptureType = CSI->getCapture(Var).getCaptureType(); 12597 12598 // Compute the type of an expression that refers to this variable. 12599 DeclRefType = CaptureType.getNonReferenceType(); 12600 12601 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 12602 if (Cap.isCopyCapture() && 12603 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 12604 DeclRefType.addConst(); 12605 return true; 12606 } 12607 return false; 12608 } 12609 12610 // Only block literals, captured statements, and lambda expressions can 12611 // capture; other scopes don't work. 12612 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 12613 SourceLocation Loc, 12614 const bool Diagnose, Sema &S) { 12615 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 12616 return getLambdaAwareParentOfDeclContext(DC); 12617 else if (Var->hasLocalStorage()) { 12618 if (Diagnose) 12619 diagnoseUncapturableValueReference(S, Loc, Var, DC); 12620 } 12621 return nullptr; 12622 } 12623 12624 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12625 // certain types of variables (unnamed, variably modified types etc.) 12626 // so check for eligibility. 12627 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 12628 SourceLocation Loc, 12629 const bool Diagnose, Sema &S) { 12630 12631 bool IsBlock = isa<BlockScopeInfo>(CSI); 12632 bool IsLambda = isa<LambdaScopeInfo>(CSI); 12633 12634 // Lambdas are not allowed to capture unnamed variables 12635 // (e.g. anonymous unions). 12636 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 12637 // assuming that's the intent. 12638 if (IsLambda && !Var->getDeclName()) { 12639 if (Diagnose) { 12640 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 12641 S.Diag(Var->getLocation(), diag::note_declared_at); 12642 } 12643 return false; 12644 } 12645 12646 // Prohibit variably-modified types in blocks; they're difficult to deal with. 12647 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 12648 if (Diagnose) { 12649 S.Diag(Loc, diag::err_ref_vm_type); 12650 S.Diag(Var->getLocation(), diag::note_previous_decl) 12651 << Var->getDeclName(); 12652 } 12653 return false; 12654 } 12655 // Prohibit structs with flexible array members too. 12656 // We cannot capture what is in the tail end of the struct. 12657 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 12658 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 12659 if (Diagnose) { 12660 if (IsBlock) 12661 S.Diag(Loc, diag::err_ref_flexarray_type); 12662 else 12663 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 12664 << Var->getDeclName(); 12665 S.Diag(Var->getLocation(), diag::note_previous_decl) 12666 << Var->getDeclName(); 12667 } 12668 return false; 12669 } 12670 } 12671 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12672 // Lambdas and captured statements are not allowed to capture __block 12673 // variables; they don't support the expected semantics. 12674 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 12675 if (Diagnose) { 12676 S.Diag(Loc, diag::err_capture_block_variable) 12677 << Var->getDeclName() << !IsLambda; 12678 S.Diag(Var->getLocation(), diag::note_previous_decl) 12679 << Var->getDeclName(); 12680 } 12681 return false; 12682 } 12683 12684 return true; 12685 } 12686 12687 // Returns true if the capture by block was successful. 12688 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 12689 SourceLocation Loc, 12690 const bool BuildAndDiagnose, 12691 QualType &CaptureType, 12692 QualType &DeclRefType, 12693 const bool Nested, 12694 Sema &S) { 12695 Expr *CopyExpr = nullptr; 12696 bool ByRef = false; 12697 12698 // Blocks are not allowed to capture arrays. 12699 if (CaptureType->isArrayType()) { 12700 if (BuildAndDiagnose) { 12701 S.Diag(Loc, diag::err_ref_array_type); 12702 S.Diag(Var->getLocation(), diag::note_previous_decl) 12703 << Var->getDeclName(); 12704 } 12705 return false; 12706 } 12707 12708 // Forbid the block-capture of autoreleasing variables. 12709 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12710 if (BuildAndDiagnose) { 12711 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 12712 << /*block*/ 0; 12713 S.Diag(Var->getLocation(), diag::note_previous_decl) 12714 << Var->getDeclName(); 12715 } 12716 return false; 12717 } 12718 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12719 if (HasBlocksAttr || CaptureType->isReferenceType()) { 12720 // Block capture by reference does not change the capture or 12721 // declaration reference types. 12722 ByRef = true; 12723 } else { 12724 // Block capture by copy introduces 'const'. 12725 CaptureType = CaptureType.getNonReferenceType().withConst(); 12726 DeclRefType = CaptureType; 12727 12728 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 12729 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 12730 // The capture logic needs the destructor, so make sure we mark it. 12731 // Usually this is unnecessary because most local variables have 12732 // their destructors marked at declaration time, but parameters are 12733 // an exception because it's technically only the call site that 12734 // actually requires the destructor. 12735 if (isa<ParmVarDecl>(Var)) 12736 S.FinalizeVarWithDestructor(Var, Record); 12737 12738 // Enter a new evaluation context to insulate the copy 12739 // full-expression. 12740 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 12741 12742 // According to the blocks spec, the capture of a variable from 12743 // the stack requires a const copy constructor. This is not true 12744 // of the copy/move done to move a __block variable to the heap. 12745 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 12746 DeclRefType.withConst(), 12747 VK_LValue, Loc); 12748 12749 ExprResult Result 12750 = S.PerformCopyInitialization( 12751 InitializedEntity::InitializeBlock(Var->getLocation(), 12752 CaptureType, false), 12753 Loc, DeclRef); 12754 12755 // Build a full-expression copy expression if initialization 12756 // succeeded and used a non-trivial constructor. Recover from 12757 // errors by pretending that the copy isn't necessary. 12758 if (!Result.isInvalid() && 12759 !cast<CXXConstructExpr>(Result.get())->getConstructor() 12760 ->isTrivial()) { 12761 Result = S.MaybeCreateExprWithCleanups(Result); 12762 CopyExpr = Result.get(); 12763 } 12764 } 12765 } 12766 } 12767 12768 // Actually capture the variable. 12769 if (BuildAndDiagnose) 12770 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 12771 SourceLocation(), CaptureType, CopyExpr); 12772 12773 return true; 12774 12775 } 12776 12777 12778 /// \brief Capture the given variable in the captured region. 12779 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 12780 VarDecl *Var, 12781 SourceLocation Loc, 12782 const bool BuildAndDiagnose, 12783 QualType &CaptureType, 12784 QualType &DeclRefType, 12785 const bool RefersToCapturedVariable, 12786 Sema &S) { 12787 12788 // By default, capture variables by reference. 12789 bool ByRef = true; 12790 // Using an LValue reference type is consistent with Lambdas (see below). 12791 if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var)) 12792 DeclRefType = DeclRefType.getUnqualifiedType(); 12793 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12794 Expr *CopyExpr = nullptr; 12795 if (BuildAndDiagnose) { 12796 // The current implementation assumes that all variables are captured 12797 // by references. Since there is no capture by copy, no expression 12798 // evaluation will be needed. 12799 RecordDecl *RD = RSI->TheRecordDecl; 12800 12801 FieldDecl *Field 12802 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 12803 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 12804 nullptr, false, ICIS_NoInit); 12805 Field->setImplicit(true); 12806 Field->setAccess(AS_private); 12807 RD->addDecl(Field); 12808 12809 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 12810 DeclRefType, VK_LValue, Loc); 12811 Var->setReferenced(true); 12812 Var->markUsed(S.Context); 12813 } 12814 12815 // Actually capture the variable. 12816 if (BuildAndDiagnose) 12817 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 12818 SourceLocation(), CaptureType, CopyExpr); 12819 12820 12821 return true; 12822 } 12823 12824 /// \brief Create a field within the lambda class for the variable 12825 /// being captured. 12826 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 12827 QualType FieldType, QualType DeclRefType, 12828 SourceLocation Loc, 12829 bool RefersToCapturedVariable) { 12830 CXXRecordDecl *Lambda = LSI->Lambda; 12831 12832 // Build the non-static data member. 12833 FieldDecl *Field 12834 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 12835 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 12836 nullptr, false, ICIS_NoInit); 12837 Field->setImplicit(true); 12838 Field->setAccess(AS_private); 12839 Lambda->addDecl(Field); 12840 } 12841 12842 /// \brief Capture the given variable in the lambda. 12843 static bool captureInLambda(LambdaScopeInfo *LSI, 12844 VarDecl *Var, 12845 SourceLocation Loc, 12846 const bool BuildAndDiagnose, 12847 QualType &CaptureType, 12848 QualType &DeclRefType, 12849 const bool RefersToCapturedVariable, 12850 const Sema::TryCaptureKind Kind, 12851 SourceLocation EllipsisLoc, 12852 const bool IsTopScope, 12853 Sema &S) { 12854 12855 // Determine whether we are capturing by reference or by value. 12856 bool ByRef = false; 12857 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 12858 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 12859 } else { 12860 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 12861 } 12862 12863 // Compute the type of the field that will capture this variable. 12864 if (ByRef) { 12865 // C++11 [expr.prim.lambda]p15: 12866 // An entity is captured by reference if it is implicitly or 12867 // explicitly captured but not captured by copy. It is 12868 // unspecified whether additional unnamed non-static data 12869 // members are declared in the closure type for entities 12870 // captured by reference. 12871 // 12872 // FIXME: It is not clear whether we want to build an lvalue reference 12873 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 12874 // to do the former, while EDG does the latter. Core issue 1249 will 12875 // clarify, but for now we follow GCC because it's a more permissive and 12876 // easily defensible position. 12877 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12878 } else { 12879 // C++11 [expr.prim.lambda]p14: 12880 // For each entity captured by copy, an unnamed non-static 12881 // data member is declared in the closure type. The 12882 // declaration order of these members is unspecified. The type 12883 // of such a data member is the type of the corresponding 12884 // captured entity if the entity is not a reference to an 12885 // object, or the referenced type otherwise. [Note: If the 12886 // captured entity is a reference to a function, the 12887 // corresponding data member is also a reference to a 12888 // function. - end note ] 12889 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 12890 if (!RefType->getPointeeType()->isFunctionType()) 12891 CaptureType = RefType->getPointeeType(); 12892 } 12893 12894 // Forbid the lambda copy-capture of autoreleasing variables. 12895 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12896 if (BuildAndDiagnose) { 12897 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 12898 S.Diag(Var->getLocation(), diag::note_previous_decl) 12899 << Var->getDeclName(); 12900 } 12901 return false; 12902 } 12903 12904 // Make sure that by-copy captures are of a complete and non-abstract type. 12905 if (BuildAndDiagnose) { 12906 if (!CaptureType->isDependentType() && 12907 S.RequireCompleteType(Loc, CaptureType, 12908 diag::err_capture_of_incomplete_type, 12909 Var->getDeclName())) 12910 return false; 12911 12912 if (S.RequireNonAbstractType(Loc, CaptureType, 12913 diag::err_capture_of_abstract_type)) 12914 return false; 12915 } 12916 } 12917 12918 // Capture this variable in the lambda. 12919 if (BuildAndDiagnose) 12920 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 12921 RefersToCapturedVariable); 12922 12923 // Compute the type of a reference to this captured variable. 12924 if (ByRef) 12925 DeclRefType = CaptureType.getNonReferenceType(); 12926 else { 12927 // C++ [expr.prim.lambda]p5: 12928 // The closure type for a lambda-expression has a public inline 12929 // function call operator [...]. This function call operator is 12930 // declared const (9.3.1) if and only if the lambda-expression’s 12931 // parameter-declaration-clause is not followed by mutable. 12932 DeclRefType = CaptureType.getNonReferenceType(); 12933 if (!LSI->Mutable && !CaptureType->isReferenceType()) 12934 DeclRefType.addConst(); 12935 } 12936 12937 // Add the capture. 12938 if (BuildAndDiagnose) 12939 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 12940 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 12941 12942 return true; 12943 } 12944 12945 bool Sema::tryCaptureVariable( 12946 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 12947 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 12948 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 12949 // An init-capture is notionally from the context surrounding its 12950 // declaration, but its parent DC is the lambda class. 12951 DeclContext *VarDC = Var->getDeclContext(); 12952 if (Var->isInitCapture()) 12953 VarDC = VarDC->getParent(); 12954 12955 DeclContext *DC = CurContext; 12956 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12957 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 12958 // We need to sync up the Declaration Context with the 12959 // FunctionScopeIndexToStopAt 12960 if (FunctionScopeIndexToStopAt) { 12961 unsigned FSIndex = FunctionScopes.size() - 1; 12962 while (FSIndex != MaxFunctionScopesIndex) { 12963 DC = getLambdaAwareParentOfDeclContext(DC); 12964 --FSIndex; 12965 } 12966 } 12967 12968 12969 // If the variable is declared in the current context, there is no need to 12970 // capture it. 12971 if (VarDC == DC) return true; 12972 12973 // Capture global variables if it is required to use private copy of this 12974 // variable. 12975 bool IsGlobal = !Var->hasLocalStorage(); 12976 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var))) 12977 return true; 12978 12979 // Walk up the stack to determine whether we can capture the variable, 12980 // performing the "simple" checks that don't depend on type. We stop when 12981 // we've either hit the declared scope of the variable or find an existing 12982 // capture of that variable. We start from the innermost capturing-entity 12983 // (the DC) and ensure that all intervening capturing-entities 12984 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 12985 // declcontext can either capture the variable or have already captured 12986 // the variable. 12987 CaptureType = Var->getType(); 12988 DeclRefType = CaptureType.getNonReferenceType(); 12989 bool Nested = false; 12990 bool Explicit = (Kind != TryCapture_Implicit); 12991 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 12992 unsigned OpenMPLevel = 0; 12993 do { 12994 // Only block literals, captured statements, and lambda expressions can 12995 // capture; other scopes don't work. 12996 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 12997 ExprLoc, 12998 BuildAndDiagnose, 12999 *this); 13000 // We need to check for the parent *first* because, if we *have* 13001 // private-captured a global variable, we need to recursively capture it in 13002 // intermediate blocks, lambdas, etc. 13003 if (!ParentDC) { 13004 if (IsGlobal) { 13005 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13006 break; 13007 } 13008 return true; 13009 } 13010 13011 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13012 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13013 13014 13015 // Check whether we've already captured it. 13016 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13017 DeclRefType)) 13018 break; 13019 // If we are instantiating a generic lambda call operator body, 13020 // we do not want to capture new variables. What was captured 13021 // during either a lambdas transformation or initial parsing 13022 // should be used. 13023 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13024 if (BuildAndDiagnose) { 13025 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13026 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13027 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13028 Diag(Var->getLocation(), diag::note_previous_decl) 13029 << Var->getDeclName(); 13030 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13031 } else 13032 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13033 } 13034 return true; 13035 } 13036 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13037 // certain types of variables (unnamed, variably modified types etc.) 13038 // so check for eligibility. 13039 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13040 return true; 13041 13042 // Try to capture variable-length arrays types. 13043 if (Var->getType()->isVariablyModifiedType()) { 13044 // We're going to walk down into the type and look for VLA 13045 // expressions. 13046 QualType QTy = Var->getType(); 13047 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13048 QTy = PVD->getOriginalType(); 13049 do { 13050 const Type *Ty = QTy.getTypePtr(); 13051 switch (Ty->getTypeClass()) { 13052 #define TYPE(Class, Base) 13053 #define ABSTRACT_TYPE(Class, Base) 13054 #define NON_CANONICAL_TYPE(Class, Base) 13055 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 13056 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 13057 #include "clang/AST/TypeNodes.def" 13058 QTy = QualType(); 13059 break; 13060 // These types are never variably-modified. 13061 case Type::Builtin: 13062 case Type::Complex: 13063 case Type::Vector: 13064 case Type::ExtVector: 13065 case Type::Record: 13066 case Type::Enum: 13067 case Type::Elaborated: 13068 case Type::TemplateSpecialization: 13069 case Type::ObjCObject: 13070 case Type::ObjCInterface: 13071 case Type::ObjCObjectPointer: 13072 llvm_unreachable("type class is never variably-modified!"); 13073 case Type::Adjusted: 13074 QTy = cast<AdjustedType>(Ty)->getOriginalType(); 13075 break; 13076 case Type::Decayed: 13077 QTy = cast<DecayedType>(Ty)->getPointeeType(); 13078 break; 13079 case Type::Pointer: 13080 QTy = cast<PointerType>(Ty)->getPointeeType(); 13081 break; 13082 case Type::BlockPointer: 13083 QTy = cast<BlockPointerType>(Ty)->getPointeeType(); 13084 break; 13085 case Type::LValueReference: 13086 case Type::RValueReference: 13087 QTy = cast<ReferenceType>(Ty)->getPointeeType(); 13088 break; 13089 case Type::MemberPointer: 13090 QTy = cast<MemberPointerType>(Ty)->getPointeeType(); 13091 break; 13092 case Type::ConstantArray: 13093 case Type::IncompleteArray: 13094 // Losing element qualification here is fine. 13095 QTy = cast<ArrayType>(Ty)->getElementType(); 13096 break; 13097 case Type::VariableArray: { 13098 // Losing element qualification here is fine. 13099 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 13100 13101 // Unknown size indication requires no size computation. 13102 // Otherwise, evaluate and record it. 13103 if (auto Size = VAT->getSizeExpr()) { 13104 if (!CSI->isVLATypeCaptured(VAT)) { 13105 RecordDecl *CapRecord = nullptr; 13106 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 13107 CapRecord = LSI->Lambda; 13108 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13109 CapRecord = CRSI->TheRecordDecl; 13110 } 13111 if (CapRecord) { 13112 auto ExprLoc = Size->getExprLoc(); 13113 auto SizeType = Context.getSizeType(); 13114 // Build the non-static data member. 13115 auto Field = FieldDecl::Create( 13116 Context, CapRecord, ExprLoc, ExprLoc, 13117 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 13118 /*BW*/ nullptr, /*Mutable*/ false, 13119 /*InitStyle*/ ICIS_NoInit); 13120 Field->setImplicit(true); 13121 Field->setAccess(AS_private); 13122 Field->setCapturedVLAType(VAT); 13123 CapRecord->addDecl(Field); 13124 13125 CSI->addVLATypeCapture(ExprLoc, SizeType); 13126 } 13127 } 13128 } 13129 QTy = VAT->getElementType(); 13130 break; 13131 } 13132 case Type::FunctionProto: 13133 case Type::FunctionNoProto: 13134 QTy = cast<FunctionType>(Ty)->getReturnType(); 13135 break; 13136 case Type::Paren: 13137 case Type::TypeOf: 13138 case Type::UnaryTransform: 13139 case Type::Attributed: 13140 case Type::SubstTemplateTypeParm: 13141 case Type::PackExpansion: 13142 // Keep walking after single level desugaring. 13143 QTy = QTy.getSingleStepDesugaredType(getASTContext()); 13144 break; 13145 case Type::Typedef: 13146 QTy = cast<TypedefType>(Ty)->desugar(); 13147 break; 13148 case Type::Decltype: 13149 QTy = cast<DecltypeType>(Ty)->desugar(); 13150 break; 13151 case Type::Auto: 13152 QTy = cast<AutoType>(Ty)->getDeducedType(); 13153 break; 13154 case Type::TypeOfExpr: 13155 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 13156 break; 13157 case Type::Atomic: 13158 QTy = cast<AtomicType>(Ty)->getValueType(); 13159 break; 13160 } 13161 } while (!QTy.isNull() && QTy->isVariablyModifiedType()); 13162 } 13163 13164 if (getLangOpts().OpenMP) { 13165 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13166 // OpenMP private variables should not be captured in outer scope, so 13167 // just break here. Similarly, global variables that are captured in a 13168 // target region should not be captured outside the scope of the region. 13169 if (RSI->CapRegionKind == CR_OpenMP) { 13170 auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel); 13171 // When we detect target captures we are looking from inside the 13172 // target region, therefore we need to propagate the capture from the 13173 // enclosing region. Therefore, the capture is not initially nested. 13174 if (isTargetCap) 13175 FunctionScopesIndex--; 13176 13177 if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) { 13178 Nested = !isTargetCap; 13179 DeclRefType = DeclRefType.getUnqualifiedType(); 13180 CaptureType = Context.getLValueReferenceType(DeclRefType); 13181 break; 13182 } 13183 ++OpenMPLevel; 13184 } 13185 } 13186 } 13187 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13188 // No capture-default, and this is not an explicit capture 13189 // so cannot capture this variable. 13190 if (BuildAndDiagnose) { 13191 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13192 Diag(Var->getLocation(), diag::note_previous_decl) 13193 << Var->getDeclName(); 13194 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13195 diag::note_lambda_decl); 13196 // FIXME: If we error out because an outer lambda can not implicitly 13197 // capture a variable that an inner lambda explicitly captures, we 13198 // should have the inner lambda do the explicit capture - because 13199 // it makes for cleaner diagnostics later. This would purely be done 13200 // so that the diagnostic does not misleadingly claim that a variable 13201 // can not be captured by a lambda implicitly even though it is captured 13202 // explicitly. Suggestion: 13203 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13204 // at the function head 13205 // - cache the StartingDeclContext - this must be a lambda 13206 // - captureInLambda in the innermost lambda the variable. 13207 } 13208 return true; 13209 } 13210 13211 FunctionScopesIndex--; 13212 DC = ParentDC; 13213 Explicit = false; 13214 } while (!VarDC->Equals(DC)); 13215 13216 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13217 // computing the type of the capture at each step, checking type-specific 13218 // requirements, and adding captures if requested. 13219 // If the variable had already been captured previously, we start capturing 13220 // at the lambda nested within that one. 13221 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13222 ++I) { 13223 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13224 13225 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13226 if (!captureInBlock(BSI, Var, ExprLoc, 13227 BuildAndDiagnose, CaptureType, 13228 DeclRefType, Nested, *this)) 13229 return true; 13230 Nested = true; 13231 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13232 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13233 BuildAndDiagnose, CaptureType, 13234 DeclRefType, Nested, *this)) 13235 return true; 13236 Nested = true; 13237 } else { 13238 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13239 if (!captureInLambda(LSI, Var, ExprLoc, 13240 BuildAndDiagnose, CaptureType, 13241 DeclRefType, Nested, Kind, EllipsisLoc, 13242 /*IsTopScope*/I == N - 1, *this)) 13243 return true; 13244 Nested = true; 13245 } 13246 } 13247 return false; 13248 } 13249 13250 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13251 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13252 QualType CaptureType; 13253 QualType DeclRefType; 13254 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13255 /*BuildAndDiagnose=*/true, CaptureType, 13256 DeclRefType, nullptr); 13257 } 13258 13259 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13260 QualType CaptureType; 13261 QualType DeclRefType; 13262 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13263 /*BuildAndDiagnose=*/false, CaptureType, 13264 DeclRefType, nullptr); 13265 } 13266 13267 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13268 QualType CaptureType; 13269 QualType DeclRefType; 13270 13271 // Determine whether we can capture this variable. 13272 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13273 /*BuildAndDiagnose=*/false, CaptureType, 13274 DeclRefType, nullptr)) 13275 return QualType(); 13276 13277 return DeclRefType; 13278 } 13279 13280 13281 13282 // If either the type of the variable or the initializer is dependent, 13283 // return false. Otherwise, determine whether the variable is a constant 13284 // expression. Use this if you need to know if a variable that might or 13285 // might not be dependent is truly a constant expression. 13286 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13287 ASTContext &Context) { 13288 13289 if (Var->getType()->isDependentType()) 13290 return false; 13291 const VarDecl *DefVD = nullptr; 13292 Var->getAnyInitializer(DefVD); 13293 if (!DefVD) 13294 return false; 13295 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13296 Expr *Init = cast<Expr>(Eval->Value); 13297 if (Init->isValueDependent()) 13298 return false; 13299 return IsVariableAConstantExpression(Var, Context); 13300 } 13301 13302 13303 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13304 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13305 // an object that satisfies the requirements for appearing in a 13306 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13307 // is immediately applied." This function handles the lvalue-to-rvalue 13308 // conversion part. 13309 MaybeODRUseExprs.erase(E->IgnoreParens()); 13310 13311 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13312 // to a variable that is a constant expression, and if so, identify it as 13313 // a reference to a variable that does not involve an odr-use of that 13314 // variable. 13315 if (LambdaScopeInfo *LSI = getCurLambda()) { 13316 Expr *SansParensExpr = E->IgnoreParens(); 13317 VarDecl *Var = nullptr; 13318 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13319 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13320 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13321 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13322 13323 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13324 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13325 } 13326 } 13327 13328 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13329 Res = CorrectDelayedTyposInExpr(Res); 13330 13331 if (!Res.isUsable()) 13332 return Res; 13333 13334 // If a constant-expression is a reference to a variable where we delay 13335 // deciding whether it is an odr-use, just assume we will apply the 13336 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13337 // (a non-type template argument), we have special handling anyway. 13338 UpdateMarkingForLValueToRValue(Res.get()); 13339 return Res; 13340 } 13341 13342 void Sema::CleanupVarDeclMarking() { 13343 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 13344 e = MaybeODRUseExprs.end(); 13345 i != e; ++i) { 13346 VarDecl *Var; 13347 SourceLocation Loc; 13348 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 13349 Var = cast<VarDecl>(DRE->getDecl()); 13350 Loc = DRE->getLocation(); 13351 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 13352 Var = cast<VarDecl>(ME->getMemberDecl()); 13353 Loc = ME->getMemberLoc(); 13354 } else { 13355 llvm_unreachable("Unexpected expression"); 13356 } 13357 13358 MarkVarDeclODRUsed(Var, Loc, *this, 13359 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13360 } 13361 13362 MaybeODRUseExprs.clear(); 13363 } 13364 13365 13366 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13367 VarDecl *Var, Expr *E) { 13368 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13369 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13370 Var->setReferenced(); 13371 13372 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13373 bool MarkODRUsed = true; 13374 13375 // If the context is not potentially evaluated, this is not an odr-use and 13376 // does not trigger instantiation. 13377 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13378 if (SemaRef.isUnevaluatedContext()) 13379 return; 13380 13381 // If we don't yet know whether this context is going to end up being an 13382 // evaluated context, and we're referencing a variable from an enclosing 13383 // scope, add a potential capture. 13384 // 13385 // FIXME: Is this necessary? These contexts are only used for default 13386 // arguments, where local variables can't be used. 13387 const bool RefersToEnclosingScope = 13388 (SemaRef.CurContext != Var->getDeclContext() && 13389 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13390 if (RefersToEnclosingScope) { 13391 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13392 // If a variable could potentially be odr-used, defer marking it so 13393 // until we finish analyzing the full expression for any 13394 // lvalue-to-rvalue 13395 // or discarded value conversions that would obviate odr-use. 13396 // Add it to the list of potential captures that will be analyzed 13397 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13398 // unless the variable is a reference that was initialized by a constant 13399 // expression (this will never need to be captured or odr-used). 13400 assert(E && "Capture variable should be used in an expression."); 13401 if (!Var->getType()->isReferenceType() || 13402 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13403 LSI->addPotentialCapture(E->IgnoreParens()); 13404 } 13405 } 13406 13407 if (!isTemplateInstantiation(TSK)) 13408 return; 13409 13410 // Instantiate, but do not mark as odr-used, variable templates. 13411 MarkODRUsed = false; 13412 } 13413 13414 VarTemplateSpecializationDecl *VarSpec = 13415 dyn_cast<VarTemplateSpecializationDecl>(Var); 13416 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13417 "Can't instantiate a partial template specialization."); 13418 13419 // Perform implicit instantiation of static data members, static data member 13420 // templates of class templates, and variable template specializations. Delay 13421 // instantiations of variable templates, except for those that could be used 13422 // in a constant expression. 13423 if (isTemplateInstantiation(TSK)) { 13424 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13425 13426 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13427 if (Var->getPointOfInstantiation().isInvalid()) { 13428 // This is a modification of an existing AST node. Notify listeners. 13429 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13430 L->StaticDataMemberInstantiated(Var); 13431 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13432 // Don't bother trying to instantiate it again, unless we might need 13433 // its initializer before we get to the end of the TU. 13434 TryInstantiating = false; 13435 } 13436 13437 if (Var->getPointOfInstantiation().isInvalid()) 13438 Var->setTemplateSpecializationKind(TSK, Loc); 13439 13440 if (TryInstantiating) { 13441 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13442 bool InstantiationDependent = false; 13443 bool IsNonDependent = 13444 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13445 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13446 : true; 13447 13448 // Do not instantiate specializations that are still type-dependent. 13449 if (IsNonDependent) { 13450 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13451 // Do not defer instantiations of variables which could be used in a 13452 // constant expression. 13453 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13454 } else { 13455 SemaRef.PendingInstantiations 13456 .push_back(std::make_pair(Var, PointOfInstantiation)); 13457 } 13458 } 13459 } 13460 } 13461 13462 if(!MarkODRUsed) return; 13463 13464 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13465 // the requirements for appearing in a constant expression (5.19) and, if 13466 // it is an object, the lvalue-to-rvalue conversion (4.1) 13467 // is immediately applied." We check the first part here, and 13468 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13469 // Note that we use the C++11 definition everywhere because nothing in 13470 // C++03 depends on whether we get the C++03 version correct. The second 13471 // part does not apply to references, since they are not objects. 13472 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13473 // A reference initialized by a constant expression can never be 13474 // odr-used, so simply ignore it. 13475 if (!Var->getType()->isReferenceType()) 13476 SemaRef.MaybeODRUseExprs.insert(E); 13477 } else 13478 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13479 /*MaxFunctionScopeIndex ptr*/ nullptr); 13480 } 13481 13482 /// \brief Mark a variable referenced, and check whether it is odr-used 13483 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13484 /// used directly for normal expressions referring to VarDecl. 13485 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13486 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13487 } 13488 13489 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13490 Decl *D, Expr *E, bool OdrUse) { 13491 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13492 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13493 return; 13494 } 13495 13496 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13497 13498 // If this is a call to a method via a cast, also mark the method in the 13499 // derived class used in case codegen can devirtualize the call. 13500 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13501 if (!ME) 13502 return; 13503 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13504 if (!MD) 13505 return; 13506 // Only attempt to devirtualize if this is truly a virtual call. 13507 bool IsVirtualCall = MD->isVirtual() && 13508 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13509 if (!IsVirtualCall) 13510 return; 13511 const Expr *Base = ME->getBase(); 13512 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13513 if (!MostDerivedClassDecl) 13514 return; 13515 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13516 if (!DM || DM->isPure()) 13517 return; 13518 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13519 } 13520 13521 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13522 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13523 // TODO: update this with DR# once a defect report is filed. 13524 // C++11 defect. The address of a pure member should not be an ODR use, even 13525 // if it's a qualified reference. 13526 bool OdrUse = true; 13527 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13528 if (Method->isVirtual()) 13529 OdrUse = false; 13530 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13531 } 13532 13533 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13534 void Sema::MarkMemberReferenced(MemberExpr *E) { 13535 // C++11 [basic.def.odr]p2: 13536 // A non-overloaded function whose name appears as a potentially-evaluated 13537 // expression or a member of a set of candidate functions, if selected by 13538 // overload resolution when referred to from a potentially-evaluated 13539 // expression, is odr-used, unless it is a pure virtual function and its 13540 // name is not explicitly qualified. 13541 bool OdrUse = true; 13542 if (E->performsVirtualDispatch(getLangOpts())) { 13543 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13544 if (Method->isPure()) 13545 OdrUse = false; 13546 } 13547 SourceLocation Loc = E->getMemberLoc().isValid() ? 13548 E->getMemberLoc() : E->getLocStart(); 13549 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13550 } 13551 13552 /// \brief Perform marking for a reference to an arbitrary declaration. It 13553 /// marks the declaration referenced, and performs odr-use checking for 13554 /// functions and variables. This method should not be used when building a 13555 /// normal expression which refers to a variable. 13556 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13557 if (OdrUse) { 13558 if (auto *VD = dyn_cast<VarDecl>(D)) { 13559 MarkVariableReferenced(Loc, VD); 13560 return; 13561 } 13562 } 13563 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13564 MarkFunctionReferenced(Loc, FD, OdrUse); 13565 return; 13566 } 13567 D->setReferenced(); 13568 } 13569 13570 namespace { 13571 // Mark all of the declarations referenced 13572 // FIXME: Not fully implemented yet! We need to have a better understanding 13573 // of when we're entering 13574 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13575 Sema &S; 13576 SourceLocation Loc; 13577 13578 public: 13579 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13580 13581 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13582 13583 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13584 bool TraverseRecordType(RecordType *T); 13585 }; 13586 } 13587 13588 bool MarkReferencedDecls::TraverseTemplateArgument( 13589 const TemplateArgument &Arg) { 13590 if (Arg.getKind() == TemplateArgument::Declaration) { 13591 if (Decl *D = Arg.getAsDecl()) 13592 S.MarkAnyDeclReferenced(Loc, D, true); 13593 } 13594 13595 return Inherited::TraverseTemplateArgument(Arg); 13596 } 13597 13598 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13599 if (ClassTemplateSpecializationDecl *Spec 13600 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13601 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13602 return TraverseTemplateArguments(Args.data(), Args.size()); 13603 } 13604 13605 return true; 13606 } 13607 13608 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13609 MarkReferencedDecls Marker(*this, Loc); 13610 Marker.TraverseType(Context.getCanonicalType(T)); 13611 } 13612 13613 namespace { 13614 /// \brief Helper class that marks all of the declarations referenced by 13615 /// potentially-evaluated subexpressions as "referenced". 13616 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13617 Sema &S; 13618 bool SkipLocalVariables; 13619 13620 public: 13621 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13622 13623 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13624 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13625 13626 void VisitDeclRefExpr(DeclRefExpr *E) { 13627 // If we were asked not to visit local variables, don't. 13628 if (SkipLocalVariables) { 13629 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13630 if (VD->hasLocalStorage()) 13631 return; 13632 } 13633 13634 S.MarkDeclRefReferenced(E); 13635 } 13636 13637 void VisitMemberExpr(MemberExpr *E) { 13638 S.MarkMemberReferenced(E); 13639 Inherited::VisitMemberExpr(E); 13640 } 13641 13642 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13643 S.MarkFunctionReferenced(E->getLocStart(), 13644 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13645 Visit(E->getSubExpr()); 13646 } 13647 13648 void VisitCXXNewExpr(CXXNewExpr *E) { 13649 if (E->getOperatorNew()) 13650 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13651 if (E->getOperatorDelete()) 13652 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13653 Inherited::VisitCXXNewExpr(E); 13654 } 13655 13656 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13657 if (E->getOperatorDelete()) 13658 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13659 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13660 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13661 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13662 S.MarkFunctionReferenced(E->getLocStart(), 13663 S.LookupDestructor(Record)); 13664 } 13665 13666 Inherited::VisitCXXDeleteExpr(E); 13667 } 13668 13669 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13670 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13671 Inherited::VisitCXXConstructExpr(E); 13672 } 13673 13674 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13675 Visit(E->getExpr()); 13676 } 13677 13678 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13679 Inherited::VisitImplicitCastExpr(E); 13680 13681 if (E->getCastKind() == CK_LValueToRValue) 13682 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13683 } 13684 }; 13685 } 13686 13687 /// \brief Mark any declarations that appear within this expression or any 13688 /// potentially-evaluated subexpressions as "referenced". 13689 /// 13690 /// \param SkipLocalVariables If true, don't mark local variables as 13691 /// 'referenced'. 13692 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13693 bool SkipLocalVariables) { 13694 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13695 } 13696 13697 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 13698 /// of the program being compiled. 13699 /// 13700 /// This routine emits the given diagnostic when the code currently being 13701 /// type-checked is "potentially evaluated", meaning that there is a 13702 /// possibility that the code will actually be executable. Code in sizeof() 13703 /// expressions, code used only during overload resolution, etc., are not 13704 /// potentially evaluated. This routine will suppress such diagnostics or, 13705 /// in the absolutely nutty case of potentially potentially evaluated 13706 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 13707 /// later. 13708 /// 13709 /// This routine should be used for all diagnostics that describe the run-time 13710 /// behavior of a program, such as passing a non-POD value through an ellipsis. 13711 /// Failure to do so will likely result in spurious diagnostics or failures 13712 /// during overload resolution or within sizeof/alignof/typeof/typeid. 13713 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 13714 const PartialDiagnostic &PD) { 13715 switch (ExprEvalContexts.back().Context) { 13716 case Unevaluated: 13717 case UnevaluatedAbstract: 13718 // The argument will never be evaluated, so don't complain. 13719 break; 13720 13721 case ConstantEvaluated: 13722 // Relevant diagnostics should be produced by constant evaluation. 13723 break; 13724 13725 case PotentiallyEvaluated: 13726 case PotentiallyEvaluatedIfUsed: 13727 if (Statement && getCurFunctionOrMethodDecl()) { 13728 FunctionScopes.back()->PossiblyUnreachableDiags. 13729 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 13730 } 13731 else 13732 Diag(Loc, PD); 13733 13734 return true; 13735 } 13736 13737 return false; 13738 } 13739 13740 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 13741 CallExpr *CE, FunctionDecl *FD) { 13742 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 13743 return false; 13744 13745 // If we're inside a decltype's expression, don't check for a valid return 13746 // type or construct temporaries until we know whether this is the last call. 13747 if (ExprEvalContexts.back().IsDecltype) { 13748 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 13749 return false; 13750 } 13751 13752 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 13753 FunctionDecl *FD; 13754 CallExpr *CE; 13755 13756 public: 13757 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 13758 : FD(FD), CE(CE) { } 13759 13760 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 13761 if (!FD) { 13762 S.Diag(Loc, diag::err_call_incomplete_return) 13763 << T << CE->getSourceRange(); 13764 return; 13765 } 13766 13767 S.Diag(Loc, diag::err_call_function_incomplete_return) 13768 << CE->getSourceRange() << FD->getDeclName() << T; 13769 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 13770 << FD->getDeclName(); 13771 } 13772 } Diagnoser(FD, CE); 13773 13774 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 13775 return true; 13776 13777 return false; 13778 } 13779 13780 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 13781 // will prevent this condition from triggering, which is what we want. 13782 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 13783 SourceLocation Loc; 13784 13785 unsigned diagnostic = diag::warn_condition_is_assignment; 13786 bool IsOrAssign = false; 13787 13788 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 13789 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 13790 return; 13791 13792 IsOrAssign = Op->getOpcode() == BO_OrAssign; 13793 13794 // Greylist some idioms by putting them into a warning subcategory. 13795 if (ObjCMessageExpr *ME 13796 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 13797 Selector Sel = ME->getSelector(); 13798 13799 // self = [<foo> init...] 13800 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 13801 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13802 13803 // <foo> = [<bar> nextObject] 13804 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 13805 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13806 } 13807 13808 Loc = Op->getOperatorLoc(); 13809 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 13810 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 13811 return; 13812 13813 IsOrAssign = Op->getOperator() == OO_PipeEqual; 13814 Loc = Op->getOperatorLoc(); 13815 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 13816 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 13817 else { 13818 // Not an assignment. 13819 return; 13820 } 13821 13822 Diag(Loc, diagnostic) << E->getSourceRange(); 13823 13824 SourceLocation Open = E->getLocStart(); 13825 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 13826 Diag(Loc, diag::note_condition_assign_silence) 13827 << FixItHint::CreateInsertion(Open, "(") 13828 << FixItHint::CreateInsertion(Close, ")"); 13829 13830 if (IsOrAssign) 13831 Diag(Loc, diag::note_condition_or_assign_to_comparison) 13832 << FixItHint::CreateReplacement(Loc, "!="); 13833 else 13834 Diag(Loc, diag::note_condition_assign_to_comparison) 13835 << FixItHint::CreateReplacement(Loc, "=="); 13836 } 13837 13838 /// \brief Redundant parentheses over an equality comparison can indicate 13839 /// that the user intended an assignment used as condition. 13840 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 13841 // Don't warn if the parens came from a macro. 13842 SourceLocation parenLoc = ParenE->getLocStart(); 13843 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 13844 return; 13845 // Don't warn for dependent expressions. 13846 if (ParenE->isTypeDependent()) 13847 return; 13848 13849 Expr *E = ParenE->IgnoreParens(); 13850 13851 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 13852 if (opE->getOpcode() == BO_EQ && 13853 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 13854 == Expr::MLV_Valid) { 13855 SourceLocation Loc = opE->getOperatorLoc(); 13856 13857 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 13858 SourceRange ParenERange = ParenE->getSourceRange(); 13859 Diag(Loc, diag::note_equality_comparison_silence) 13860 << FixItHint::CreateRemoval(ParenERange.getBegin()) 13861 << FixItHint::CreateRemoval(ParenERange.getEnd()); 13862 Diag(Loc, diag::note_equality_comparison_to_assign) 13863 << FixItHint::CreateReplacement(Loc, "="); 13864 } 13865 } 13866 13867 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 13868 DiagnoseAssignmentAsCondition(E); 13869 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 13870 DiagnoseEqualityWithExtraParens(parenE); 13871 13872 ExprResult result = CheckPlaceholderExpr(E); 13873 if (result.isInvalid()) return ExprError(); 13874 E = result.get(); 13875 13876 if (!E->isTypeDependent()) { 13877 if (getLangOpts().CPlusPlus) 13878 return CheckCXXBooleanCondition(E); // C++ 6.4p4 13879 13880 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 13881 if (ERes.isInvalid()) 13882 return ExprError(); 13883 E = ERes.get(); 13884 13885 QualType T = E->getType(); 13886 if (!T->isScalarType()) { // C99 6.8.4.1p1 13887 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 13888 << T << E->getSourceRange(); 13889 return ExprError(); 13890 } 13891 CheckBoolLikeConversion(E, Loc); 13892 } 13893 13894 return E; 13895 } 13896 13897 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 13898 Expr *SubExpr) { 13899 if (!SubExpr) 13900 return ExprError(); 13901 13902 return CheckBooleanCondition(SubExpr, Loc); 13903 } 13904 13905 namespace { 13906 /// A visitor for rebuilding a call to an __unknown_any expression 13907 /// to have an appropriate type. 13908 struct RebuildUnknownAnyFunction 13909 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 13910 13911 Sema &S; 13912 13913 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 13914 13915 ExprResult VisitStmt(Stmt *S) { 13916 llvm_unreachable("unexpected statement!"); 13917 } 13918 13919 ExprResult VisitExpr(Expr *E) { 13920 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 13921 << E->getSourceRange(); 13922 return ExprError(); 13923 } 13924 13925 /// Rebuild an expression which simply semantically wraps another 13926 /// expression which it shares the type and value kind of. 13927 template <class T> ExprResult rebuildSugarExpr(T *E) { 13928 ExprResult SubResult = Visit(E->getSubExpr()); 13929 if (SubResult.isInvalid()) return ExprError(); 13930 13931 Expr *SubExpr = SubResult.get(); 13932 E->setSubExpr(SubExpr); 13933 E->setType(SubExpr->getType()); 13934 E->setValueKind(SubExpr->getValueKind()); 13935 assert(E->getObjectKind() == OK_Ordinary); 13936 return E; 13937 } 13938 13939 ExprResult VisitParenExpr(ParenExpr *E) { 13940 return rebuildSugarExpr(E); 13941 } 13942 13943 ExprResult VisitUnaryExtension(UnaryOperator *E) { 13944 return rebuildSugarExpr(E); 13945 } 13946 13947 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 13948 ExprResult SubResult = Visit(E->getSubExpr()); 13949 if (SubResult.isInvalid()) return ExprError(); 13950 13951 Expr *SubExpr = SubResult.get(); 13952 E->setSubExpr(SubExpr); 13953 E->setType(S.Context.getPointerType(SubExpr->getType())); 13954 assert(E->getValueKind() == VK_RValue); 13955 assert(E->getObjectKind() == OK_Ordinary); 13956 return E; 13957 } 13958 13959 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 13960 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 13961 13962 E->setType(VD->getType()); 13963 13964 assert(E->getValueKind() == VK_RValue); 13965 if (S.getLangOpts().CPlusPlus && 13966 !(isa<CXXMethodDecl>(VD) && 13967 cast<CXXMethodDecl>(VD)->isInstance())) 13968 E->setValueKind(VK_LValue); 13969 13970 return E; 13971 } 13972 13973 ExprResult VisitMemberExpr(MemberExpr *E) { 13974 return resolveDecl(E, E->getMemberDecl()); 13975 } 13976 13977 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 13978 return resolveDecl(E, E->getDecl()); 13979 } 13980 }; 13981 } 13982 13983 /// Given a function expression of unknown-any type, try to rebuild it 13984 /// to have a function type. 13985 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 13986 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 13987 if (Result.isInvalid()) return ExprError(); 13988 return S.DefaultFunctionArrayConversion(Result.get()); 13989 } 13990 13991 namespace { 13992 /// A visitor for rebuilding an expression of type __unknown_anytype 13993 /// into one which resolves the type directly on the referring 13994 /// expression. Strict preservation of the original source 13995 /// structure is not a goal. 13996 struct RebuildUnknownAnyExpr 13997 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 13998 13999 Sema &S; 14000 14001 /// The current destination type. 14002 QualType DestType; 14003 14004 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14005 : S(S), DestType(CastType) {} 14006 14007 ExprResult VisitStmt(Stmt *S) { 14008 llvm_unreachable("unexpected statement!"); 14009 } 14010 14011 ExprResult VisitExpr(Expr *E) { 14012 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14013 << E->getSourceRange(); 14014 return ExprError(); 14015 } 14016 14017 ExprResult VisitCallExpr(CallExpr *E); 14018 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14019 14020 /// Rebuild an expression which simply semantically wraps another 14021 /// expression which it shares the type and value kind of. 14022 template <class T> ExprResult rebuildSugarExpr(T *E) { 14023 ExprResult SubResult = Visit(E->getSubExpr()); 14024 if (SubResult.isInvalid()) return ExprError(); 14025 Expr *SubExpr = SubResult.get(); 14026 E->setSubExpr(SubExpr); 14027 E->setType(SubExpr->getType()); 14028 E->setValueKind(SubExpr->getValueKind()); 14029 assert(E->getObjectKind() == OK_Ordinary); 14030 return E; 14031 } 14032 14033 ExprResult VisitParenExpr(ParenExpr *E) { 14034 return rebuildSugarExpr(E); 14035 } 14036 14037 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14038 return rebuildSugarExpr(E); 14039 } 14040 14041 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14042 const PointerType *Ptr = DestType->getAs<PointerType>(); 14043 if (!Ptr) { 14044 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14045 << E->getSourceRange(); 14046 return ExprError(); 14047 } 14048 assert(E->getValueKind() == VK_RValue); 14049 assert(E->getObjectKind() == OK_Ordinary); 14050 E->setType(DestType); 14051 14052 // Build the sub-expression as if it were an object of the pointee type. 14053 DestType = Ptr->getPointeeType(); 14054 ExprResult SubResult = Visit(E->getSubExpr()); 14055 if (SubResult.isInvalid()) return ExprError(); 14056 E->setSubExpr(SubResult.get()); 14057 return E; 14058 } 14059 14060 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14061 14062 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14063 14064 ExprResult VisitMemberExpr(MemberExpr *E) { 14065 return resolveDecl(E, E->getMemberDecl()); 14066 } 14067 14068 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14069 return resolveDecl(E, E->getDecl()); 14070 } 14071 }; 14072 } 14073 14074 /// Rebuilds a call expression which yielded __unknown_anytype. 14075 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14076 Expr *CalleeExpr = E->getCallee(); 14077 14078 enum FnKind { 14079 FK_MemberFunction, 14080 FK_FunctionPointer, 14081 FK_BlockPointer 14082 }; 14083 14084 FnKind Kind; 14085 QualType CalleeType = CalleeExpr->getType(); 14086 if (CalleeType == S.Context.BoundMemberTy) { 14087 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14088 Kind = FK_MemberFunction; 14089 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14090 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14091 CalleeType = Ptr->getPointeeType(); 14092 Kind = FK_FunctionPointer; 14093 } else { 14094 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14095 Kind = FK_BlockPointer; 14096 } 14097 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14098 14099 // Verify that this is a legal result type of a function. 14100 if (DestType->isArrayType() || DestType->isFunctionType()) { 14101 unsigned diagID = diag::err_func_returning_array_function; 14102 if (Kind == FK_BlockPointer) 14103 diagID = diag::err_block_returning_array_function; 14104 14105 S.Diag(E->getExprLoc(), diagID) 14106 << DestType->isFunctionType() << DestType; 14107 return ExprError(); 14108 } 14109 14110 // Otherwise, go ahead and set DestType as the call's result. 14111 E->setType(DestType.getNonLValueExprType(S.Context)); 14112 E->setValueKind(Expr::getValueKindForType(DestType)); 14113 assert(E->getObjectKind() == OK_Ordinary); 14114 14115 // Rebuild the function type, replacing the result type with DestType. 14116 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14117 if (Proto) { 14118 // __unknown_anytype(...) is a special case used by the debugger when 14119 // it has no idea what a function's signature is. 14120 // 14121 // We want to build this call essentially under the K&R 14122 // unprototyped rules, but making a FunctionNoProtoType in C++ 14123 // would foul up all sorts of assumptions. However, we cannot 14124 // simply pass all arguments as variadic arguments, nor can we 14125 // portably just call the function under a non-variadic type; see 14126 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14127 // However, it turns out that in practice it is generally safe to 14128 // call a function declared as "A foo(B,C,D);" under the prototype 14129 // "A foo(B,C,D,...);". The only known exception is with the 14130 // Windows ABI, where any variadic function is implicitly cdecl 14131 // regardless of its normal CC. Therefore we change the parameter 14132 // types to match the types of the arguments. 14133 // 14134 // This is a hack, but it is far superior to moving the 14135 // corresponding target-specific code from IR-gen to Sema/AST. 14136 14137 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14138 SmallVector<QualType, 8> ArgTypes; 14139 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14140 ArgTypes.reserve(E->getNumArgs()); 14141 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14142 Expr *Arg = E->getArg(i); 14143 QualType ArgType = Arg->getType(); 14144 if (E->isLValue()) { 14145 ArgType = S.Context.getLValueReferenceType(ArgType); 14146 } else if (E->isXValue()) { 14147 ArgType = S.Context.getRValueReferenceType(ArgType); 14148 } 14149 ArgTypes.push_back(ArgType); 14150 } 14151 ParamTypes = ArgTypes; 14152 } 14153 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14154 Proto->getExtProtoInfo()); 14155 } else { 14156 DestType = S.Context.getFunctionNoProtoType(DestType, 14157 FnType->getExtInfo()); 14158 } 14159 14160 // Rebuild the appropriate pointer-to-function type. 14161 switch (Kind) { 14162 case FK_MemberFunction: 14163 // Nothing to do. 14164 break; 14165 14166 case FK_FunctionPointer: 14167 DestType = S.Context.getPointerType(DestType); 14168 break; 14169 14170 case FK_BlockPointer: 14171 DestType = S.Context.getBlockPointerType(DestType); 14172 break; 14173 } 14174 14175 // Finally, we can recurse. 14176 ExprResult CalleeResult = Visit(CalleeExpr); 14177 if (!CalleeResult.isUsable()) return ExprError(); 14178 E->setCallee(CalleeResult.get()); 14179 14180 // Bind a temporary if necessary. 14181 return S.MaybeBindToTemporary(E); 14182 } 14183 14184 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14185 // Verify that this is a legal result type of a call. 14186 if (DestType->isArrayType() || DestType->isFunctionType()) { 14187 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14188 << DestType->isFunctionType() << DestType; 14189 return ExprError(); 14190 } 14191 14192 // Rewrite the method result type if available. 14193 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14194 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14195 Method->setReturnType(DestType); 14196 } 14197 14198 // Change the type of the message. 14199 E->setType(DestType.getNonReferenceType()); 14200 E->setValueKind(Expr::getValueKindForType(DestType)); 14201 14202 return S.MaybeBindToTemporary(E); 14203 } 14204 14205 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14206 // The only case we should ever see here is a function-to-pointer decay. 14207 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14208 assert(E->getValueKind() == VK_RValue); 14209 assert(E->getObjectKind() == OK_Ordinary); 14210 14211 E->setType(DestType); 14212 14213 // Rebuild the sub-expression as the pointee (function) type. 14214 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14215 14216 ExprResult Result = Visit(E->getSubExpr()); 14217 if (!Result.isUsable()) return ExprError(); 14218 14219 E->setSubExpr(Result.get()); 14220 return E; 14221 } else if (E->getCastKind() == CK_LValueToRValue) { 14222 assert(E->getValueKind() == VK_RValue); 14223 assert(E->getObjectKind() == OK_Ordinary); 14224 14225 assert(isa<BlockPointerType>(E->getType())); 14226 14227 E->setType(DestType); 14228 14229 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14230 DestType = S.Context.getLValueReferenceType(DestType); 14231 14232 ExprResult Result = Visit(E->getSubExpr()); 14233 if (!Result.isUsable()) return ExprError(); 14234 14235 E->setSubExpr(Result.get()); 14236 return E; 14237 } else { 14238 llvm_unreachable("Unhandled cast type!"); 14239 } 14240 } 14241 14242 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14243 ExprValueKind ValueKind = VK_LValue; 14244 QualType Type = DestType; 14245 14246 // We know how to make this work for certain kinds of decls: 14247 14248 // - functions 14249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14250 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14251 DestType = Ptr->getPointeeType(); 14252 ExprResult Result = resolveDecl(E, VD); 14253 if (Result.isInvalid()) return ExprError(); 14254 return S.ImpCastExprToType(Result.get(), Type, 14255 CK_FunctionToPointerDecay, VK_RValue); 14256 } 14257 14258 if (!Type->isFunctionType()) { 14259 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14260 << VD << E->getSourceRange(); 14261 return ExprError(); 14262 } 14263 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14264 // We must match the FunctionDecl's type to the hack introduced in 14265 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14266 // type. See the lengthy commentary in that routine. 14267 QualType FDT = FD->getType(); 14268 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14269 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14270 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14271 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14272 SourceLocation Loc = FD->getLocation(); 14273 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14274 FD->getDeclContext(), 14275 Loc, Loc, FD->getNameInfo().getName(), 14276 DestType, FD->getTypeSourceInfo(), 14277 SC_None, false/*isInlineSpecified*/, 14278 FD->hasPrototype(), 14279 false/*isConstexprSpecified*/); 14280 14281 if (FD->getQualifier()) 14282 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14283 14284 SmallVector<ParmVarDecl*, 16> Params; 14285 for (const auto &AI : FT->param_types()) { 14286 ParmVarDecl *Param = 14287 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14288 Param->setScopeInfo(0, Params.size()); 14289 Params.push_back(Param); 14290 } 14291 NewFD->setParams(Params); 14292 DRE->setDecl(NewFD); 14293 VD = DRE->getDecl(); 14294 } 14295 } 14296 14297 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14298 if (MD->isInstance()) { 14299 ValueKind = VK_RValue; 14300 Type = S.Context.BoundMemberTy; 14301 } 14302 14303 // Function references aren't l-values in C. 14304 if (!S.getLangOpts().CPlusPlus) 14305 ValueKind = VK_RValue; 14306 14307 // - variables 14308 } else if (isa<VarDecl>(VD)) { 14309 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14310 Type = RefTy->getPointeeType(); 14311 } else if (Type->isFunctionType()) { 14312 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14313 << VD << E->getSourceRange(); 14314 return ExprError(); 14315 } 14316 14317 // - nothing else 14318 } else { 14319 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14320 << VD << E->getSourceRange(); 14321 return ExprError(); 14322 } 14323 14324 // Modifying the declaration like this is friendly to IR-gen but 14325 // also really dangerous. 14326 VD->setType(DestType); 14327 E->setType(Type); 14328 E->setValueKind(ValueKind); 14329 return E; 14330 } 14331 14332 /// Check a cast of an unknown-any type. We intentionally only 14333 /// trigger this for C-style casts. 14334 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14335 Expr *CastExpr, CastKind &CastKind, 14336 ExprValueKind &VK, CXXCastPath &Path) { 14337 // Rewrite the casted expression from scratch. 14338 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14339 if (!result.isUsable()) return ExprError(); 14340 14341 CastExpr = result.get(); 14342 VK = CastExpr->getValueKind(); 14343 CastKind = CK_NoOp; 14344 14345 return CastExpr; 14346 } 14347 14348 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14349 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14350 } 14351 14352 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14353 Expr *arg, QualType ¶mType) { 14354 // If the syntactic form of the argument is not an explicit cast of 14355 // any sort, just do default argument promotion. 14356 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14357 if (!castArg) { 14358 ExprResult result = DefaultArgumentPromotion(arg); 14359 if (result.isInvalid()) return ExprError(); 14360 paramType = result.get()->getType(); 14361 return result; 14362 } 14363 14364 // Otherwise, use the type that was written in the explicit cast. 14365 assert(!arg->hasPlaceholderType()); 14366 paramType = castArg->getTypeAsWritten(); 14367 14368 // Copy-initialize a parameter of that type. 14369 InitializedEntity entity = 14370 InitializedEntity::InitializeParameter(Context, paramType, 14371 /*consumed*/ false); 14372 return PerformCopyInitialization(entity, callLoc, arg); 14373 } 14374 14375 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14376 Expr *orig = E; 14377 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14378 while (true) { 14379 E = E->IgnoreParenImpCasts(); 14380 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14381 E = call->getCallee(); 14382 diagID = diag::err_uncasted_call_of_unknown_any; 14383 } else { 14384 break; 14385 } 14386 } 14387 14388 SourceLocation loc; 14389 NamedDecl *d; 14390 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14391 loc = ref->getLocation(); 14392 d = ref->getDecl(); 14393 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14394 loc = mem->getMemberLoc(); 14395 d = mem->getMemberDecl(); 14396 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14397 diagID = diag::err_uncasted_call_of_unknown_any; 14398 loc = msg->getSelectorStartLoc(); 14399 d = msg->getMethodDecl(); 14400 if (!d) { 14401 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14402 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14403 << orig->getSourceRange(); 14404 return ExprError(); 14405 } 14406 } else { 14407 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14408 << E->getSourceRange(); 14409 return ExprError(); 14410 } 14411 14412 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14413 14414 // Never recoverable. 14415 return ExprError(); 14416 } 14417 14418 /// Check for operands with placeholder types and complain if found. 14419 /// Returns true if there was an error and no recovery was possible. 14420 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14421 if (!getLangOpts().CPlusPlus) { 14422 // C cannot handle TypoExpr nodes on either side of a binop because it 14423 // doesn't handle dependent types properly, so make sure any TypoExprs have 14424 // been dealt with before checking the operands. 14425 ExprResult Result = CorrectDelayedTyposInExpr(E); 14426 if (!Result.isUsable()) return ExprError(); 14427 E = Result.get(); 14428 } 14429 14430 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14431 if (!placeholderType) return E; 14432 14433 switch (placeholderType->getKind()) { 14434 14435 // Overloaded expressions. 14436 case BuiltinType::Overload: { 14437 // Try to resolve a single function template specialization. 14438 // This is obligatory. 14439 ExprResult result = E; 14440 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14441 return result; 14442 14443 // If that failed, try to recover with a call. 14444 } else { 14445 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14446 /*complain*/ true); 14447 return result; 14448 } 14449 } 14450 14451 // Bound member functions. 14452 case BuiltinType::BoundMember: { 14453 ExprResult result = E; 14454 const Expr *BME = E->IgnoreParens(); 14455 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14456 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14457 if (isa<CXXPseudoDestructorExpr>(BME)) { 14458 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14459 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14460 if (ME->getMemberNameInfo().getName().getNameKind() == 14461 DeclarationName::CXXDestructorName) 14462 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14463 } 14464 tryToRecoverWithCall(result, PD, 14465 /*complain*/ true); 14466 return result; 14467 } 14468 14469 // ARC unbridged casts. 14470 case BuiltinType::ARCUnbridgedCast: { 14471 Expr *realCast = stripARCUnbridgedCast(E); 14472 diagnoseARCUnbridgedCast(realCast); 14473 return realCast; 14474 } 14475 14476 // Expressions of unknown type. 14477 case BuiltinType::UnknownAny: 14478 return diagnoseUnknownAnyExpr(*this, E); 14479 14480 // Pseudo-objects. 14481 case BuiltinType::PseudoObject: 14482 return checkPseudoObjectRValue(E); 14483 14484 case BuiltinType::BuiltinFn: { 14485 // Accept __noop without parens by implicitly converting it to a call expr. 14486 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14487 if (DRE) { 14488 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14489 if (FD->getBuiltinID() == Builtin::BI__noop) { 14490 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14491 CK_BuiltinFnToFnPtr).get(); 14492 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14493 VK_RValue, SourceLocation()); 14494 } 14495 } 14496 14497 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14498 return ExprError(); 14499 } 14500 14501 // Expressions of unknown type. 14502 case BuiltinType::OMPArraySection: 14503 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14504 return ExprError(); 14505 14506 // Everything else should be impossible. 14507 #define BUILTIN_TYPE(Id, SingletonId) \ 14508 case BuiltinType::Id: 14509 #define PLACEHOLDER_TYPE(Id, SingletonId) 14510 #include "clang/AST/BuiltinTypes.def" 14511 break; 14512 } 14513 14514 llvm_unreachable("invalid placeholder type!"); 14515 } 14516 14517 bool Sema::CheckCaseExpression(Expr *E) { 14518 if (E->isTypeDependent()) 14519 return true; 14520 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14521 return E->getType()->isIntegralOrEnumerationType(); 14522 return false; 14523 } 14524 14525 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14526 ExprResult 14527 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14528 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14529 "Unknown Objective-C Boolean value!"); 14530 QualType BoolT = Context.ObjCBuiltinBoolTy; 14531 if (!Context.getBOOLDecl()) { 14532 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14533 Sema::LookupOrdinaryName); 14534 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14535 NamedDecl *ND = Result.getFoundDecl(); 14536 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14537 Context.setBOOLDecl(TD); 14538 } 14539 } 14540 if (Context.getBOOLDecl()) 14541 BoolT = Context.getBOOLType(); 14542 return new (Context) 14543 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14544 } 14545