1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/ExprOpenMP.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (D->hasAttr<UnusedAttr>()) { 80 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 81 if (DC && !DC->hasAttr<UnusedAttr>()) 82 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 83 } 84 } 85 86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 87 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 88 if (!OMD) 89 return false; 90 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 91 if (!OID) 92 return false; 93 94 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 95 if (ObjCMethodDecl *CatMeth = 96 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 97 if (!CatMeth->hasAttr<AvailabilityAttr>()) 98 return true; 99 return false; 100 } 101 102 static AvailabilityResult 103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 104 const ObjCInterfaceDecl *UnknownObjCClass, 105 bool ObjCPropertyAccess) { 106 // See if this declaration is unavailable or deprecated. 107 std::string Message; 108 AvailabilityResult Result = D->getAvailability(&Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(&Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(&Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(&Message); 136 } 137 138 const ObjCPropertyDecl *ObjCPDecl = nullptr; 139 if (Result == AR_Deprecated || Result == AR_Unavailable || 140 AR_NotYetIntroduced) { 141 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 142 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 143 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 144 if (PDeclResult == Result) 145 ObjCPDecl = PD; 146 } 147 } 148 } 149 150 switch (Result) { 151 case AR_Available: 152 break; 153 154 case AR_Deprecated: 155 if (S.getCurContextAvailability() != AR_Deprecated) 156 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 157 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 158 ObjCPropertyAccess); 159 break; 160 161 case AR_NotYetIntroduced: { 162 // Don't do this for enums, they can't be redeclared. 163 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 164 break; 165 166 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 167 // Objective-C method declarations in categories are not modelled as 168 // redeclarations, so manually look for a redeclaration in a category 169 // if necessary. 170 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 171 Warn = false; 172 // In general, D will point to the most recent redeclaration. However, 173 // for `@class A;` decls, this isn't true -- manually go through the 174 // redecl chain in that case. 175 if (Warn && isa<ObjCInterfaceDecl>(D)) 176 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 177 Redecl = Redecl->getPreviousDecl()) 178 if (!Redecl->hasAttr<AvailabilityAttr>() || 179 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 180 Warn = false; 181 182 if (Warn) 183 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 184 UnknownObjCClass, ObjCPDecl, 185 ObjCPropertyAccess); 186 break; 187 } 188 189 case AR_Unavailable: 190 if (S.getCurContextAvailability() != AR_Unavailable) 191 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 192 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 193 ObjCPropertyAccess); 194 break; 195 196 } 197 return Result; 198 } 199 200 /// \brief Emit a note explaining that this function is deleted. 201 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 202 assert(Decl->isDeleted()); 203 204 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 205 206 if (Method && Method->isDeleted() && Method->isDefaulted()) { 207 // If the method was explicitly defaulted, point at that declaration. 208 if (!Method->isImplicit()) 209 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 210 211 // Try to diagnose why this special member function was implicitly 212 // deleted. This might fail, if that reason no longer applies. 213 CXXSpecialMember CSM = getSpecialMember(Method); 214 if (CSM != CXXInvalid) 215 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 216 217 return; 218 } 219 220 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 221 if (CXXConstructorDecl *BaseCD = 222 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 223 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 224 if (BaseCD->isDeleted()) { 225 NoteDeletedFunction(BaseCD); 226 } else { 227 // FIXME: An explanation of why exactly it can't be inherited 228 // would be nice. 229 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 230 } 231 return; 232 } 233 } 234 235 Diag(Decl->getLocation(), diag::note_availability_specified_here) 236 << Decl << true; 237 } 238 239 /// \brief Determine whether a FunctionDecl was ever declared with an 240 /// explicit storage class. 241 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 242 for (auto I : D->redecls()) { 243 if (I->getStorageClass() != SC_None) 244 return true; 245 } 246 return false; 247 } 248 249 /// \brief Check whether we're in an extern inline function and referring to a 250 /// variable or function with internal linkage (C11 6.7.4p3). 251 /// 252 /// This is only a warning because we used to silently accept this code, but 253 /// in many cases it will not behave correctly. This is not enabled in C++ mode 254 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 255 /// and so while there may still be user mistakes, most of the time we can't 256 /// prove that there are errors. 257 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 258 const NamedDecl *D, 259 SourceLocation Loc) { 260 // This is disabled under C++; there are too many ways for this to fire in 261 // contexts where the warning is a false positive, or where it is technically 262 // correct but benign. 263 if (S.getLangOpts().CPlusPlus) 264 return; 265 266 // Check if this is an inlined function or method. 267 FunctionDecl *Current = S.getCurFunctionDecl(); 268 if (!Current) 269 return; 270 if (!Current->isInlined()) 271 return; 272 if (!Current->isExternallyVisible()) 273 return; 274 275 // Check if the decl has internal linkage. 276 if (D->getFormalLinkage() != InternalLinkage) 277 return; 278 279 // Downgrade from ExtWarn to Extension if 280 // (1) the supposedly external inline function is in the main file, 281 // and probably won't be included anywhere else. 282 // (2) the thing we're referencing is a pure function. 283 // (3) the thing we're referencing is another inline function. 284 // This last can give us false negatives, but it's better than warning on 285 // wrappers for simple C library functions. 286 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 287 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 288 if (!DowngradeWarning && UsedFn) 289 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 290 291 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 292 : diag::ext_internal_in_extern_inline) 293 << /*IsVar=*/!UsedFn << D; 294 295 S.MaybeSuggestAddingStaticToDecl(Current); 296 297 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 298 << D; 299 } 300 301 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 302 const FunctionDecl *First = Cur->getFirstDecl(); 303 304 // Suggest "static" on the function, if possible. 305 if (!hasAnyExplicitStorageClass(First)) { 306 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 307 Diag(DeclBegin, diag::note_convert_inline_to_static) 308 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 309 } 310 } 311 312 /// \brief Determine whether the use of this declaration is valid, and 313 /// emit any corresponding diagnostics. 314 /// 315 /// This routine diagnoses various problems with referencing 316 /// declarations that can occur when using a declaration. For example, 317 /// it might warn if a deprecated or unavailable declaration is being 318 /// used, or produce an error (and return true) if a C++0x deleted 319 /// function is being used. 320 /// 321 /// \returns true if there was an error (this declaration cannot be 322 /// referenced), false otherwise. 323 /// 324 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 325 const ObjCInterfaceDecl *UnknownObjCClass, 326 bool ObjCPropertyAccess) { 327 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 328 // If there were any diagnostics suppressed by template argument deduction, 329 // emit them now. 330 SuppressedDiagnosticsMap::iterator 331 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 332 if (Pos != SuppressedDiagnostics.end()) { 333 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 334 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 335 Diag(Suppressed[I].first, Suppressed[I].second); 336 337 // Clear out the list of suppressed diagnostics, so that we don't emit 338 // them again for this specialization. However, we don't obsolete this 339 // entry from the table, because we want to avoid ever emitting these 340 // diagnostics again. 341 Suppressed.clear(); 342 } 343 344 // C++ [basic.start.main]p3: 345 // The function 'main' shall not be used within a program. 346 if (cast<FunctionDecl>(D)->isMain()) 347 Diag(Loc, diag::ext_main_used); 348 } 349 350 // See if this is an auto-typed variable whose initializer we are parsing. 351 if (ParsingInitForAutoVars.count(D)) { 352 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName(); 354 return true; 355 } 356 357 // See if this is a deleted function. 358 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 359 if (FD->isDeleted()) { 360 Diag(Loc, diag::err_deleted_function_use); 361 NoteDeletedFunction(FD); 362 return true; 363 } 364 365 // If the function has a deduced return type, and we can't deduce it, 366 // then we can't use it either. 367 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 368 DeduceReturnType(FD, Loc)) 369 return true; 370 } 371 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 372 ObjCPropertyAccess); 373 374 DiagnoseUnusedOfDecl(*this, D, Loc); 375 376 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 377 378 return false; 379 } 380 381 /// \brief Retrieve the message suffix that should be added to a 382 /// diagnostic complaining about the given function being deleted or 383 /// unavailable. 384 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 385 std::string Message; 386 if (FD->getAvailability(&Message)) 387 return ": " + Message; 388 389 return std::string(); 390 } 391 392 /// DiagnoseSentinelCalls - This routine checks whether a call or 393 /// message-send is to a declaration with the sentinel attribute, and 394 /// if so, it checks that the requirements of the sentinel are 395 /// satisfied. 396 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 397 ArrayRef<Expr *> Args) { 398 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 399 if (!attr) 400 return; 401 402 // The number of formal parameters of the declaration. 403 unsigned numFormalParams; 404 405 // The kind of declaration. This is also an index into a %select in 406 // the diagnostic. 407 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 408 409 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 410 numFormalParams = MD->param_size(); 411 calleeType = CT_Method; 412 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 413 numFormalParams = FD->param_size(); 414 calleeType = CT_Function; 415 } else if (isa<VarDecl>(D)) { 416 QualType type = cast<ValueDecl>(D)->getType(); 417 const FunctionType *fn = nullptr; 418 if (const PointerType *ptr = type->getAs<PointerType>()) { 419 fn = ptr->getPointeeType()->getAs<FunctionType>(); 420 if (!fn) return; 421 calleeType = CT_Function; 422 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 423 fn = ptr->getPointeeType()->castAs<FunctionType>(); 424 calleeType = CT_Block; 425 } else { 426 return; 427 } 428 429 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 430 numFormalParams = proto->getNumParams(); 431 } else { 432 numFormalParams = 0; 433 } 434 } else { 435 return; 436 } 437 438 // "nullPos" is the number of formal parameters at the end which 439 // effectively count as part of the variadic arguments. This is 440 // useful if you would prefer to not have *any* formal parameters, 441 // but the language forces you to have at least one. 442 unsigned nullPos = attr->getNullPos(); 443 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 444 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 445 446 // The number of arguments which should follow the sentinel. 447 unsigned numArgsAfterSentinel = attr->getSentinel(); 448 449 // If there aren't enough arguments for all the formal parameters, 450 // the sentinel, and the args after the sentinel, complain. 451 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 452 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 453 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 454 return; 455 } 456 457 // Otherwise, find the sentinel expression. 458 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 459 if (!sentinelExpr) return; 460 if (sentinelExpr->isValueDependent()) return; 461 if (Context.isSentinelNullExpr(sentinelExpr)) return; 462 463 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 464 // or 'NULL' if those are actually defined in the context. Only use 465 // 'nil' for ObjC methods, where it's much more likely that the 466 // variadic arguments form a list of object pointers. 467 SourceLocation MissingNilLoc 468 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 // If we are here, we are not calling a function but taking 510 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 511 if (getLangOpts().OpenCL) { 512 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 513 return ExprError(); 514 } 515 E = ImpCastExprToType(E, Context.getPointerType(Ty), 516 CK_FunctionToPointerDecay).get(); 517 } else if (Ty->isArrayType()) { 518 // In C90 mode, arrays only promote to pointers if the array expression is 519 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 520 // type 'array of type' is converted to an expression that has type 'pointer 521 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 522 // that has type 'array of type' ...". The relevant change is "an lvalue" 523 // (C90) to "an expression" (C99). 524 // 525 // C++ 4.2p1: 526 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 527 // T" can be converted to an rvalue of type "pointer to T". 528 // 529 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 530 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 531 CK_ArrayToPointerDecay).get(); 532 } 533 return E; 534 } 535 536 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 537 // Check to see if we are dereferencing a null pointer. If so, 538 // and if not volatile-qualified, this is undefined behavior that the 539 // optimizer will delete, so warn about it. People sometimes try to use this 540 // to get a deterministic trap and are surprised by clang's behavior. This 541 // only handles the pattern "*null", which is a very syntactic check. 542 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 543 if (UO->getOpcode() == UO_Deref && 544 UO->getSubExpr()->IgnoreParenCasts()-> 545 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 546 !UO->getType().isVolatileQualified()) { 547 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 548 S.PDiag(diag::warn_indirection_through_null) 549 << UO->getSubExpr()->getSourceRange()); 550 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 551 S.PDiag(diag::note_indirection_through_null)); 552 } 553 } 554 555 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 556 SourceLocation AssignLoc, 557 const Expr* RHS) { 558 const ObjCIvarDecl *IV = OIRE->getDecl(); 559 if (!IV) 560 return; 561 562 DeclarationName MemberName = IV->getDeclName(); 563 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 564 if (!Member || !Member->isStr("isa")) 565 return; 566 567 const Expr *Base = OIRE->getBase(); 568 QualType BaseType = Base->getType(); 569 if (OIRE->isArrow()) 570 BaseType = BaseType->getPointeeType(); 571 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 572 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 573 ObjCInterfaceDecl *ClassDeclared = nullptr; 574 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 575 if (!ClassDeclared->getSuperClass() 576 && (*ClassDeclared->ivar_begin()) == IV) { 577 if (RHS) { 578 NamedDecl *ObjectSetClass = 579 S.LookupSingleName(S.TUScope, 580 &S.Context.Idents.get("object_setClass"), 581 SourceLocation(), S.LookupOrdinaryName); 582 if (ObjectSetClass) { 583 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 584 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 585 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 586 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 587 AssignLoc), ",") << 588 FixItHint::CreateInsertion(RHSLocEnd, ")"); 589 } 590 else 591 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 592 } else { 593 NamedDecl *ObjectGetClass = 594 S.LookupSingleName(S.TUScope, 595 &S.Context.Idents.get("object_getClass"), 596 SourceLocation(), S.LookupOrdinaryName); 597 if (ObjectGetClass) 598 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 599 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 600 FixItHint::CreateReplacement( 601 SourceRange(OIRE->getOpLoc(), 602 OIRE->getLocEnd()), ")"); 603 else 604 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 605 } 606 S.Diag(IV->getLocation(), diag::note_ivar_decl); 607 } 608 } 609 } 610 611 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 612 // Handle any placeholder expressions which made it here. 613 if (E->getType()->isPlaceholderType()) { 614 ExprResult result = CheckPlaceholderExpr(E); 615 if (result.isInvalid()) return ExprError(); 616 E = result.get(); 617 } 618 619 // C++ [conv.lval]p1: 620 // A glvalue of a non-function, non-array type T can be 621 // converted to a prvalue. 622 if (!E->isGLValue()) return E; 623 624 QualType T = E->getType(); 625 assert(!T.isNull() && "r-value conversion on typeless expression?"); 626 627 // We don't want to throw lvalue-to-rvalue casts on top of 628 // expressions of certain types in C++. 629 if (getLangOpts().CPlusPlus && 630 (E->getType() == Context.OverloadTy || 631 T->isDependentType() || 632 T->isRecordType())) 633 return E; 634 635 // The C standard is actually really unclear on this point, and 636 // DR106 tells us what the result should be but not why. It's 637 // generally best to say that void types just doesn't undergo 638 // lvalue-to-rvalue at all. Note that expressions of unqualified 639 // 'void' type are never l-values, but qualified void can be. 640 if (T->isVoidType()) 641 return E; 642 643 // OpenCL usually rejects direct accesses to values of 'half' type. 644 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 645 T->isHalfType()) { 646 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 647 << 0 << T; 648 return ExprError(); 649 } 650 651 CheckForNullPointerDereference(*this, E); 652 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 653 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 654 &Context.Idents.get("object_getClass"), 655 SourceLocation(), LookupOrdinaryName); 656 if (ObjectGetClass) 657 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 658 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 659 FixItHint::CreateReplacement( 660 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 661 else 662 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 663 } 664 else if (const ObjCIvarRefExpr *OIRE = 665 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 666 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 667 668 // C++ [conv.lval]p1: 669 // [...] If T is a non-class type, the type of the prvalue is the 670 // cv-unqualified version of T. Otherwise, the type of the 671 // rvalue is T. 672 // 673 // C99 6.3.2.1p2: 674 // If the lvalue has qualified type, the value has the unqualified 675 // version of the type of the lvalue; otherwise, the value has the 676 // type of the lvalue. 677 if (T.hasQualifiers()) 678 T = T.getUnqualifiedType(); 679 680 if (T->isMemberPointerType() && 681 Context.getTargetInfo().getCXXABI().isMicrosoft()) 682 RequireCompleteType(E->getExprLoc(), T, 0); 683 684 UpdateMarkingForLValueToRValue(E); 685 686 // Loading a __weak object implicitly retains the value, so we need a cleanup to 687 // balance that. 688 if (getLangOpts().ObjCAutoRefCount && 689 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 690 ExprNeedsCleanups = true; 691 692 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 693 nullptr, VK_RValue); 694 695 // C11 6.3.2.1p2: 696 // ... if the lvalue has atomic type, the value has the non-atomic version 697 // of the type of the lvalue ... 698 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 699 T = Atomic->getValueType().getUnqualifiedType(); 700 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 701 nullptr, VK_RValue); 702 } 703 704 return Res; 705 } 706 707 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 708 ExprResult Res = DefaultFunctionArrayConversion(E); 709 if (Res.isInvalid()) 710 return ExprError(); 711 Res = DefaultLvalueConversion(Res.get()); 712 if (Res.isInvalid()) 713 return ExprError(); 714 return Res; 715 } 716 717 /// CallExprUnaryConversions - a special case of an unary conversion 718 /// performed on a function designator of a call expression. 719 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 720 QualType Ty = E->getType(); 721 ExprResult Res = E; 722 // Only do implicit cast for a function type, but not for a pointer 723 // to function type. 724 if (Ty->isFunctionType()) { 725 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 726 CK_FunctionToPointerDecay).get(); 727 if (Res.isInvalid()) 728 return ExprError(); 729 } 730 Res = DefaultLvalueConversion(Res.get()); 731 if (Res.isInvalid()) 732 return ExprError(); 733 return Res.get(); 734 } 735 736 /// UsualUnaryConversions - Performs various conversions that are common to most 737 /// operators (C99 6.3). The conversions of array and function types are 738 /// sometimes suppressed. For example, the array->pointer conversion doesn't 739 /// apply if the array is an argument to the sizeof or address (&) operators. 740 /// In these instances, this routine should *not* be called. 741 ExprResult Sema::UsualUnaryConversions(Expr *E) { 742 // First, convert to an r-value. 743 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 744 if (Res.isInvalid()) 745 return ExprError(); 746 E = Res.get(); 747 748 QualType Ty = E->getType(); 749 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 750 751 // Half FP have to be promoted to float unless it is natively supported 752 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 753 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 754 755 // Try to perform integral promotions if the object has a theoretically 756 // promotable type. 757 if (Ty->isIntegralOrUnscopedEnumerationType()) { 758 // C99 6.3.1.1p2: 759 // 760 // The following may be used in an expression wherever an int or 761 // unsigned int may be used: 762 // - an object or expression with an integer type whose integer 763 // conversion rank is less than or equal to the rank of int 764 // and unsigned int. 765 // - A bit-field of type _Bool, int, signed int, or unsigned int. 766 // 767 // If an int can represent all values of the original type, the 768 // value is converted to an int; otherwise, it is converted to an 769 // unsigned int. These are called the integer promotions. All 770 // other types are unchanged by the integer promotions. 771 772 QualType PTy = Context.isPromotableBitField(E); 773 if (!PTy.isNull()) { 774 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 775 return E; 776 } 777 if (Ty->isPromotableIntegerType()) { 778 QualType PT = Context.getPromotedIntegerType(Ty); 779 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 780 return E; 781 } 782 } 783 return E; 784 } 785 786 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 787 /// do not have a prototype. Arguments that have type float or __fp16 788 /// are promoted to double. All other argument types are converted by 789 /// UsualUnaryConversions(). 790 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 791 QualType Ty = E->getType(); 792 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 793 794 ExprResult Res = UsualUnaryConversions(E); 795 if (Res.isInvalid()) 796 return ExprError(); 797 E = Res.get(); 798 799 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 800 // double. 801 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 802 if (BTy && (BTy->getKind() == BuiltinType::Half || 803 BTy->getKind() == BuiltinType::Float)) 804 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 805 806 // C++ performs lvalue-to-rvalue conversion as a default argument 807 // promotion, even on class types, but note: 808 // C++11 [conv.lval]p2: 809 // When an lvalue-to-rvalue conversion occurs in an unevaluated 810 // operand or a subexpression thereof the value contained in the 811 // referenced object is not accessed. Otherwise, if the glvalue 812 // has a class type, the conversion copy-initializes a temporary 813 // of type T from the glvalue and the result of the conversion 814 // is a prvalue for the temporary. 815 // FIXME: add some way to gate this entire thing for correctness in 816 // potentially potentially evaluated contexts. 817 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 818 ExprResult Temp = PerformCopyInitialization( 819 InitializedEntity::InitializeTemporary(E->getType()), 820 E->getExprLoc(), E); 821 if (Temp.isInvalid()) 822 return ExprError(); 823 E = Temp.get(); 824 } 825 826 return E; 827 } 828 829 /// Determine the degree of POD-ness for an expression. 830 /// Incomplete types are considered POD, since this check can be performed 831 /// when we're in an unevaluated context. 832 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 833 if (Ty->isIncompleteType()) { 834 // C++11 [expr.call]p7: 835 // After these conversions, if the argument does not have arithmetic, 836 // enumeration, pointer, pointer to member, or class type, the program 837 // is ill-formed. 838 // 839 // Since we've already performed array-to-pointer and function-to-pointer 840 // decay, the only such type in C++ is cv void. This also handles 841 // initializer lists as variadic arguments. 842 if (Ty->isVoidType()) 843 return VAK_Invalid; 844 845 if (Ty->isObjCObjectType()) 846 return VAK_Invalid; 847 return VAK_Valid; 848 } 849 850 if (Ty.isCXX98PODType(Context)) 851 return VAK_Valid; 852 853 // C++11 [expr.call]p7: 854 // Passing a potentially-evaluated argument of class type (Clause 9) 855 // having a non-trivial copy constructor, a non-trivial move constructor, 856 // or a non-trivial destructor, with no corresponding parameter, 857 // is conditionally-supported with implementation-defined semantics. 858 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 859 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 860 if (!Record->hasNonTrivialCopyConstructor() && 861 !Record->hasNonTrivialMoveConstructor() && 862 !Record->hasNonTrivialDestructor()) 863 return VAK_ValidInCXX11; 864 865 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 866 return VAK_Valid; 867 868 if (Ty->isObjCObjectType()) 869 return VAK_Invalid; 870 871 if (getLangOpts().MSVCCompat) 872 return VAK_MSVCUndefined; 873 874 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 875 // permitted to reject them. We should consider doing so. 876 return VAK_Undefined; 877 } 878 879 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 880 // Don't allow one to pass an Objective-C interface to a vararg. 881 const QualType &Ty = E->getType(); 882 VarArgKind VAK = isValidVarArgType(Ty); 883 884 // Complain about passing non-POD types through varargs. 885 switch (VAK) { 886 case VAK_ValidInCXX11: 887 DiagRuntimeBehavior( 888 E->getLocStart(), nullptr, 889 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 890 << Ty << CT); 891 // Fall through. 892 case VAK_Valid: 893 if (Ty->isRecordType()) { 894 // This is unlikely to be what the user intended. If the class has a 895 // 'c_str' member function, the user probably meant to call that. 896 DiagRuntimeBehavior(E->getLocStart(), nullptr, 897 PDiag(diag::warn_pass_class_arg_to_vararg) 898 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 899 } 900 break; 901 902 case VAK_Undefined: 903 case VAK_MSVCUndefined: 904 DiagRuntimeBehavior( 905 E->getLocStart(), nullptr, 906 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 907 << getLangOpts().CPlusPlus11 << Ty << CT); 908 break; 909 910 case VAK_Invalid: 911 if (Ty->isObjCObjectType()) 912 DiagRuntimeBehavior( 913 E->getLocStart(), nullptr, 914 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 915 << Ty << CT); 916 else 917 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 918 << isa<InitListExpr>(E) << Ty << CT; 919 break; 920 } 921 } 922 923 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 924 /// will create a trap if the resulting type is not a POD type. 925 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 926 FunctionDecl *FDecl) { 927 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 928 // Strip the unbridged-cast placeholder expression off, if applicable. 929 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 930 (CT == VariadicMethod || 931 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 932 E = stripARCUnbridgedCast(E); 933 934 // Otherwise, do normal placeholder checking. 935 } else { 936 ExprResult ExprRes = CheckPlaceholderExpr(E); 937 if (ExprRes.isInvalid()) 938 return ExprError(); 939 E = ExprRes.get(); 940 } 941 } 942 943 ExprResult ExprRes = DefaultArgumentPromotion(E); 944 if (ExprRes.isInvalid()) 945 return ExprError(); 946 E = ExprRes.get(); 947 948 // Diagnostics regarding non-POD argument types are 949 // emitted along with format string checking in Sema::CheckFunctionCall(). 950 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 951 // Turn this into a trap. 952 CXXScopeSpec SS; 953 SourceLocation TemplateKWLoc; 954 UnqualifiedId Name; 955 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 956 E->getLocStart()); 957 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 958 Name, true, false); 959 if (TrapFn.isInvalid()) 960 return ExprError(); 961 962 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 963 E->getLocStart(), None, 964 E->getLocEnd()); 965 if (Call.isInvalid()) 966 return ExprError(); 967 968 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 969 Call.get(), E); 970 if (Comma.isInvalid()) 971 return ExprError(); 972 return Comma.get(); 973 } 974 975 if (!getLangOpts().CPlusPlus && 976 RequireCompleteType(E->getExprLoc(), E->getType(), 977 diag::err_call_incomplete_argument)) 978 return ExprError(); 979 980 return E; 981 } 982 983 /// \brief Converts an integer to complex float type. Helper function of 984 /// UsualArithmeticConversions() 985 /// 986 /// \return false if the integer expression is an integer type and is 987 /// successfully converted to the complex type. 988 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 989 ExprResult &ComplexExpr, 990 QualType IntTy, 991 QualType ComplexTy, 992 bool SkipCast) { 993 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 994 if (SkipCast) return false; 995 if (IntTy->isIntegerType()) { 996 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 997 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 998 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 999 CK_FloatingRealToComplex); 1000 } else { 1001 assert(IntTy->isComplexIntegerType()); 1002 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1003 CK_IntegralComplexToFloatingComplex); 1004 } 1005 return false; 1006 } 1007 1008 /// \brief Handle arithmetic conversion with complex types. Helper function of 1009 /// UsualArithmeticConversions() 1010 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1011 ExprResult &RHS, QualType LHSType, 1012 QualType RHSType, 1013 bool IsCompAssign) { 1014 // if we have an integer operand, the result is the complex type. 1015 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1016 /*skipCast*/false)) 1017 return LHSType; 1018 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1019 /*skipCast*/IsCompAssign)) 1020 return RHSType; 1021 1022 // This handles complex/complex, complex/float, or float/complex. 1023 // When both operands are complex, the shorter operand is converted to the 1024 // type of the longer, and that is the type of the result. This corresponds 1025 // to what is done when combining two real floating-point operands. 1026 // The fun begins when size promotion occur across type domains. 1027 // From H&S 6.3.4: When one operand is complex and the other is a real 1028 // floating-point type, the less precise type is converted, within it's 1029 // real or complex domain, to the precision of the other type. For example, 1030 // when combining a "long double" with a "double _Complex", the 1031 // "double _Complex" is promoted to "long double _Complex". 1032 1033 // Compute the rank of the two types, regardless of whether they are complex. 1034 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1035 1036 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1037 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1038 QualType LHSElementType = 1039 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1040 QualType RHSElementType = 1041 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1042 1043 QualType ResultType = S.Context.getComplexType(LHSElementType); 1044 if (Order < 0) { 1045 // Promote the precision of the LHS if not an assignment. 1046 ResultType = S.Context.getComplexType(RHSElementType); 1047 if (!IsCompAssign) { 1048 if (LHSComplexType) 1049 LHS = 1050 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1051 else 1052 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1053 } 1054 } else if (Order > 0) { 1055 // Promote the precision of the RHS. 1056 if (RHSComplexType) 1057 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1058 else 1059 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1060 } 1061 return ResultType; 1062 } 1063 1064 /// \brief Hande arithmetic conversion from integer to float. Helper function 1065 /// of UsualArithmeticConversions() 1066 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1067 ExprResult &IntExpr, 1068 QualType FloatTy, QualType IntTy, 1069 bool ConvertFloat, bool ConvertInt) { 1070 if (IntTy->isIntegerType()) { 1071 if (ConvertInt) 1072 // Convert intExpr to the lhs floating point type. 1073 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1074 CK_IntegralToFloating); 1075 return FloatTy; 1076 } 1077 1078 // Convert both sides to the appropriate complex float. 1079 assert(IntTy->isComplexIntegerType()); 1080 QualType result = S.Context.getComplexType(FloatTy); 1081 1082 // _Complex int -> _Complex float 1083 if (ConvertInt) 1084 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1085 CK_IntegralComplexToFloatingComplex); 1086 1087 // float -> _Complex float 1088 if (ConvertFloat) 1089 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1090 CK_FloatingRealToComplex); 1091 1092 return result; 1093 } 1094 1095 /// \brief Handle arithmethic conversion with floating point types. Helper 1096 /// function of UsualArithmeticConversions() 1097 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1098 ExprResult &RHS, QualType LHSType, 1099 QualType RHSType, bool IsCompAssign) { 1100 bool LHSFloat = LHSType->isRealFloatingType(); 1101 bool RHSFloat = RHSType->isRealFloatingType(); 1102 1103 // If we have two real floating types, convert the smaller operand 1104 // to the bigger result. 1105 if (LHSFloat && RHSFloat) { 1106 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1107 if (order > 0) { 1108 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1109 return LHSType; 1110 } 1111 1112 assert(order < 0 && "illegal float comparison"); 1113 if (!IsCompAssign) 1114 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1115 return RHSType; 1116 } 1117 1118 if (LHSFloat) { 1119 // Half FP has to be promoted to float unless it is natively supported 1120 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1121 LHSType = S.Context.FloatTy; 1122 1123 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1124 /*convertFloat=*/!IsCompAssign, 1125 /*convertInt=*/ true); 1126 } 1127 assert(RHSFloat); 1128 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1129 /*convertInt=*/ true, 1130 /*convertFloat=*/!IsCompAssign); 1131 } 1132 1133 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1134 1135 namespace { 1136 /// These helper callbacks are placed in an anonymous namespace to 1137 /// permit their use as function template parameters. 1138 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1139 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1140 } 1141 1142 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1143 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1144 CK_IntegralComplexCast); 1145 } 1146 } 1147 1148 /// \brief Handle integer arithmetic conversions. Helper function of 1149 /// UsualArithmeticConversions() 1150 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1151 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1152 ExprResult &RHS, QualType LHSType, 1153 QualType RHSType, bool IsCompAssign) { 1154 // The rules for this case are in C99 6.3.1.8 1155 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1156 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1157 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1158 if (LHSSigned == RHSSigned) { 1159 // Same signedness; use the higher-ranked type 1160 if (order >= 0) { 1161 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1162 return LHSType; 1163 } else if (!IsCompAssign) 1164 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1165 return RHSType; 1166 } else if (order != (LHSSigned ? 1 : -1)) { 1167 // The unsigned type has greater than or equal rank to the 1168 // signed type, so use the unsigned type 1169 if (RHSSigned) { 1170 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1171 return LHSType; 1172 } else if (!IsCompAssign) 1173 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1174 return RHSType; 1175 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1176 // The two types are different widths; if we are here, that 1177 // means the signed type is larger than the unsigned type, so 1178 // use the signed type. 1179 if (LHSSigned) { 1180 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1181 return LHSType; 1182 } else if (!IsCompAssign) 1183 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1184 return RHSType; 1185 } else { 1186 // The signed type is higher-ranked than the unsigned type, 1187 // but isn't actually any bigger (like unsigned int and long 1188 // on most 32-bit systems). Use the unsigned type corresponding 1189 // to the signed type. 1190 QualType result = 1191 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1192 RHS = (*doRHSCast)(S, RHS.get(), result); 1193 if (!IsCompAssign) 1194 LHS = (*doLHSCast)(S, LHS.get(), result); 1195 return result; 1196 } 1197 } 1198 1199 /// \brief Handle conversions with GCC complex int extension. Helper function 1200 /// of UsualArithmeticConversions() 1201 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1202 ExprResult &RHS, QualType LHSType, 1203 QualType RHSType, 1204 bool IsCompAssign) { 1205 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1206 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1207 1208 if (LHSComplexInt && RHSComplexInt) { 1209 QualType LHSEltType = LHSComplexInt->getElementType(); 1210 QualType RHSEltType = RHSComplexInt->getElementType(); 1211 QualType ScalarType = 1212 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1213 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1214 1215 return S.Context.getComplexType(ScalarType); 1216 } 1217 1218 if (LHSComplexInt) { 1219 QualType LHSEltType = LHSComplexInt->getElementType(); 1220 QualType ScalarType = 1221 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1222 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1223 QualType ComplexType = S.Context.getComplexType(ScalarType); 1224 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1225 CK_IntegralRealToComplex); 1226 1227 return ComplexType; 1228 } 1229 1230 assert(RHSComplexInt); 1231 1232 QualType RHSEltType = RHSComplexInt->getElementType(); 1233 QualType ScalarType = 1234 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1235 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1236 QualType ComplexType = S.Context.getComplexType(ScalarType); 1237 1238 if (!IsCompAssign) 1239 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1240 CK_IntegralRealToComplex); 1241 return ComplexType; 1242 } 1243 1244 /// UsualArithmeticConversions - Performs various conversions that are common to 1245 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1246 /// routine returns the first non-arithmetic type found. The client is 1247 /// responsible for emitting appropriate error diagnostics. 1248 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1249 bool IsCompAssign) { 1250 if (!IsCompAssign) { 1251 LHS = UsualUnaryConversions(LHS.get()); 1252 if (LHS.isInvalid()) 1253 return QualType(); 1254 } 1255 1256 RHS = UsualUnaryConversions(RHS.get()); 1257 if (RHS.isInvalid()) 1258 return QualType(); 1259 1260 // For conversion purposes, we ignore any qualifiers. 1261 // For example, "const float" and "float" are equivalent. 1262 QualType LHSType = 1263 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1264 QualType RHSType = 1265 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1266 1267 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1268 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1269 LHSType = AtomicLHS->getValueType(); 1270 1271 // If both types are identical, no conversion is needed. 1272 if (LHSType == RHSType) 1273 return LHSType; 1274 1275 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1276 // The caller can deal with this (e.g. pointer + int). 1277 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1278 return QualType(); 1279 1280 // Apply unary and bitfield promotions to the LHS's type. 1281 QualType LHSUnpromotedType = LHSType; 1282 if (LHSType->isPromotableIntegerType()) 1283 LHSType = Context.getPromotedIntegerType(LHSType); 1284 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1285 if (!LHSBitfieldPromoteTy.isNull()) 1286 LHSType = LHSBitfieldPromoteTy; 1287 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1288 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1289 1290 // If both types are identical, no conversion is needed. 1291 if (LHSType == RHSType) 1292 return LHSType; 1293 1294 // At this point, we have two different arithmetic types. 1295 1296 // Handle complex types first (C99 6.3.1.8p1). 1297 if (LHSType->isComplexType() || RHSType->isComplexType()) 1298 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1299 IsCompAssign); 1300 1301 // Now handle "real" floating types (i.e. float, double, long double). 1302 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1303 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1304 IsCompAssign); 1305 1306 // Handle GCC complex int extension. 1307 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1308 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1309 IsCompAssign); 1310 1311 // Finally, we have two differing integer types. 1312 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1313 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1314 } 1315 1316 1317 //===----------------------------------------------------------------------===// 1318 // Semantic Analysis for various Expression Types 1319 //===----------------------------------------------------------------------===// 1320 1321 1322 ExprResult 1323 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1324 SourceLocation DefaultLoc, 1325 SourceLocation RParenLoc, 1326 Expr *ControllingExpr, 1327 ArrayRef<ParsedType> ArgTypes, 1328 ArrayRef<Expr *> ArgExprs) { 1329 unsigned NumAssocs = ArgTypes.size(); 1330 assert(NumAssocs == ArgExprs.size()); 1331 1332 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1333 for (unsigned i = 0; i < NumAssocs; ++i) { 1334 if (ArgTypes[i]) 1335 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1336 else 1337 Types[i] = nullptr; 1338 } 1339 1340 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1341 ControllingExpr, 1342 llvm::makeArrayRef(Types, NumAssocs), 1343 ArgExprs); 1344 delete [] Types; 1345 return ER; 1346 } 1347 1348 ExprResult 1349 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1350 SourceLocation DefaultLoc, 1351 SourceLocation RParenLoc, 1352 Expr *ControllingExpr, 1353 ArrayRef<TypeSourceInfo *> Types, 1354 ArrayRef<Expr *> Exprs) { 1355 unsigned NumAssocs = Types.size(); 1356 assert(NumAssocs == Exprs.size()); 1357 if (ControllingExpr->getType()->isPlaceholderType()) { 1358 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1359 if (result.isInvalid()) return ExprError(); 1360 ControllingExpr = result.get(); 1361 } 1362 1363 // The controlling expression is an unevaluated operand, so side effects are 1364 // likely unintended. 1365 if (ActiveTemplateInstantiations.empty() && 1366 ControllingExpr->HasSideEffects(Context, false)) 1367 Diag(ControllingExpr->getExprLoc(), 1368 diag::warn_side_effects_unevaluated_context); 1369 1370 bool TypeErrorFound = false, 1371 IsResultDependent = ControllingExpr->isTypeDependent(), 1372 ContainsUnexpandedParameterPack 1373 = ControllingExpr->containsUnexpandedParameterPack(); 1374 1375 for (unsigned i = 0; i < NumAssocs; ++i) { 1376 if (Exprs[i]->containsUnexpandedParameterPack()) 1377 ContainsUnexpandedParameterPack = true; 1378 1379 if (Types[i]) { 1380 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1381 ContainsUnexpandedParameterPack = true; 1382 1383 if (Types[i]->getType()->isDependentType()) { 1384 IsResultDependent = true; 1385 } else { 1386 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1387 // complete object type other than a variably modified type." 1388 unsigned D = 0; 1389 if (Types[i]->getType()->isIncompleteType()) 1390 D = diag::err_assoc_type_incomplete; 1391 else if (!Types[i]->getType()->isObjectType()) 1392 D = diag::err_assoc_type_nonobject; 1393 else if (Types[i]->getType()->isVariablyModifiedType()) 1394 D = diag::err_assoc_type_variably_modified; 1395 1396 if (D != 0) { 1397 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1398 << Types[i]->getTypeLoc().getSourceRange() 1399 << Types[i]->getType(); 1400 TypeErrorFound = true; 1401 } 1402 1403 // C11 6.5.1.1p2 "No two generic associations in the same generic 1404 // selection shall specify compatible types." 1405 for (unsigned j = i+1; j < NumAssocs; ++j) 1406 if (Types[j] && !Types[j]->getType()->isDependentType() && 1407 Context.typesAreCompatible(Types[i]->getType(), 1408 Types[j]->getType())) { 1409 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1410 diag::err_assoc_compatible_types) 1411 << Types[j]->getTypeLoc().getSourceRange() 1412 << Types[j]->getType() 1413 << Types[i]->getType(); 1414 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1415 diag::note_compat_assoc) 1416 << Types[i]->getTypeLoc().getSourceRange() 1417 << Types[i]->getType(); 1418 TypeErrorFound = true; 1419 } 1420 } 1421 } 1422 } 1423 if (TypeErrorFound) 1424 return ExprError(); 1425 1426 // If we determined that the generic selection is result-dependent, don't 1427 // try to compute the result expression. 1428 if (IsResultDependent) 1429 return new (Context) GenericSelectionExpr( 1430 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1431 ContainsUnexpandedParameterPack); 1432 1433 SmallVector<unsigned, 1> CompatIndices; 1434 unsigned DefaultIndex = -1U; 1435 for (unsigned i = 0; i < NumAssocs; ++i) { 1436 if (!Types[i]) 1437 DefaultIndex = i; 1438 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1439 Types[i]->getType())) 1440 CompatIndices.push_back(i); 1441 } 1442 1443 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1444 // type compatible with at most one of the types named in its generic 1445 // association list." 1446 if (CompatIndices.size() > 1) { 1447 // We strip parens here because the controlling expression is typically 1448 // parenthesized in macro definitions. 1449 ControllingExpr = ControllingExpr->IgnoreParens(); 1450 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1451 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1452 << (unsigned) CompatIndices.size(); 1453 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1454 E = CompatIndices.end(); I != E; ++I) { 1455 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1456 diag::note_compat_assoc) 1457 << Types[*I]->getTypeLoc().getSourceRange() 1458 << Types[*I]->getType(); 1459 } 1460 return ExprError(); 1461 } 1462 1463 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1464 // its controlling expression shall have type compatible with exactly one of 1465 // the types named in its generic association list." 1466 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1467 // We strip parens here because the controlling expression is typically 1468 // parenthesized in macro definitions. 1469 ControllingExpr = ControllingExpr->IgnoreParens(); 1470 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1471 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1472 return ExprError(); 1473 } 1474 1475 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1476 // type name that is compatible with the type of the controlling expression, 1477 // then the result expression of the generic selection is the expression 1478 // in that generic association. Otherwise, the result expression of the 1479 // generic selection is the expression in the default generic association." 1480 unsigned ResultIndex = 1481 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1482 1483 return new (Context) GenericSelectionExpr( 1484 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1485 ContainsUnexpandedParameterPack, ResultIndex); 1486 } 1487 1488 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1489 /// location of the token and the offset of the ud-suffix within it. 1490 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1491 unsigned Offset) { 1492 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1493 S.getLangOpts()); 1494 } 1495 1496 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1497 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1498 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1499 IdentifierInfo *UDSuffix, 1500 SourceLocation UDSuffixLoc, 1501 ArrayRef<Expr*> Args, 1502 SourceLocation LitEndLoc) { 1503 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1504 1505 QualType ArgTy[2]; 1506 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1507 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1508 if (ArgTy[ArgIdx]->isArrayType()) 1509 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1510 } 1511 1512 DeclarationName OpName = 1513 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1514 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1515 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1516 1517 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1518 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1519 /*AllowRaw*/false, /*AllowTemplate*/false, 1520 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1521 return ExprError(); 1522 1523 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1524 } 1525 1526 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1527 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1528 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1529 /// multiple tokens. However, the common case is that StringToks points to one 1530 /// string. 1531 /// 1532 ExprResult 1533 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1534 assert(!StringToks.empty() && "Must have at least one string!"); 1535 1536 StringLiteralParser Literal(StringToks, PP); 1537 if (Literal.hadError) 1538 return ExprError(); 1539 1540 SmallVector<SourceLocation, 4> StringTokLocs; 1541 for (unsigned i = 0; i != StringToks.size(); ++i) 1542 StringTokLocs.push_back(StringToks[i].getLocation()); 1543 1544 QualType CharTy = Context.CharTy; 1545 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1546 if (Literal.isWide()) { 1547 CharTy = Context.getWideCharType(); 1548 Kind = StringLiteral::Wide; 1549 } else if (Literal.isUTF8()) { 1550 Kind = StringLiteral::UTF8; 1551 } else if (Literal.isUTF16()) { 1552 CharTy = Context.Char16Ty; 1553 Kind = StringLiteral::UTF16; 1554 } else if (Literal.isUTF32()) { 1555 CharTy = Context.Char32Ty; 1556 Kind = StringLiteral::UTF32; 1557 } else if (Literal.isPascal()) { 1558 CharTy = Context.UnsignedCharTy; 1559 } 1560 1561 QualType CharTyConst = CharTy; 1562 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1563 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1564 CharTyConst.addConst(); 1565 1566 // Get an array type for the string, according to C99 6.4.5. This includes 1567 // the nul terminator character as well as the string length for pascal 1568 // strings. 1569 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1570 llvm::APInt(32, Literal.GetNumStringChars()+1), 1571 ArrayType::Normal, 0); 1572 1573 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1574 if (getLangOpts().OpenCL) { 1575 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1576 } 1577 1578 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1579 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1580 Kind, Literal.Pascal, StrTy, 1581 &StringTokLocs[0], 1582 StringTokLocs.size()); 1583 if (Literal.getUDSuffix().empty()) 1584 return Lit; 1585 1586 // We're building a user-defined literal. 1587 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1588 SourceLocation UDSuffixLoc = 1589 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1590 Literal.getUDSuffixOffset()); 1591 1592 // Make sure we're allowed user-defined literals here. 1593 if (!UDLScope) 1594 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1595 1596 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1597 // operator "" X (str, len) 1598 QualType SizeType = Context.getSizeType(); 1599 1600 DeclarationName OpName = 1601 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1602 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1603 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1604 1605 QualType ArgTy[] = { 1606 Context.getArrayDecayedType(StrTy), SizeType 1607 }; 1608 1609 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1610 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1611 /*AllowRaw*/false, /*AllowTemplate*/false, 1612 /*AllowStringTemplate*/true)) { 1613 1614 case LOLR_Cooked: { 1615 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1616 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1617 StringTokLocs[0]); 1618 Expr *Args[] = { Lit, LenArg }; 1619 1620 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1621 } 1622 1623 case LOLR_StringTemplate: { 1624 TemplateArgumentListInfo ExplicitArgs; 1625 1626 unsigned CharBits = Context.getIntWidth(CharTy); 1627 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1628 llvm::APSInt Value(CharBits, CharIsUnsigned); 1629 1630 TemplateArgument TypeArg(CharTy); 1631 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1632 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1633 1634 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1635 Value = Lit->getCodeUnit(I); 1636 TemplateArgument Arg(Context, Value, CharTy); 1637 TemplateArgumentLocInfo ArgInfo; 1638 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1639 } 1640 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1641 &ExplicitArgs); 1642 } 1643 case LOLR_Raw: 1644 case LOLR_Template: 1645 llvm_unreachable("unexpected literal operator lookup result"); 1646 case LOLR_Error: 1647 return ExprError(); 1648 } 1649 llvm_unreachable("unexpected literal operator lookup result"); 1650 } 1651 1652 ExprResult 1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1654 SourceLocation Loc, 1655 const CXXScopeSpec *SS) { 1656 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1657 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1658 } 1659 1660 /// BuildDeclRefExpr - Build an expression that references a 1661 /// declaration that does not require a closure capture. 1662 ExprResult 1663 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1664 const DeclarationNameInfo &NameInfo, 1665 const CXXScopeSpec *SS, NamedDecl *FoundD, 1666 const TemplateArgumentListInfo *TemplateArgs) { 1667 if (getLangOpts().CUDA) 1668 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1669 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1670 if (CheckCUDATarget(Caller, Callee)) { 1671 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1672 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1673 << IdentifyCUDATarget(Caller); 1674 Diag(D->getLocation(), diag::note_previous_decl) 1675 << D->getIdentifier(); 1676 return ExprError(); 1677 } 1678 } 1679 1680 bool RefersToCapturedVariable = 1681 isa<VarDecl>(D) && 1682 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1683 1684 DeclRefExpr *E; 1685 if (isa<VarTemplateSpecializationDecl>(D)) { 1686 VarTemplateSpecializationDecl *VarSpec = 1687 cast<VarTemplateSpecializationDecl>(D); 1688 1689 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1690 : NestedNameSpecifierLoc(), 1691 VarSpec->getTemplateKeywordLoc(), D, 1692 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1693 FoundD, TemplateArgs); 1694 } else { 1695 assert(!TemplateArgs && "No template arguments for non-variable" 1696 " template specialization references"); 1697 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1698 : NestedNameSpecifierLoc(), 1699 SourceLocation(), D, RefersToCapturedVariable, 1700 NameInfo, Ty, VK, FoundD); 1701 } 1702 1703 MarkDeclRefReferenced(E); 1704 1705 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1706 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1707 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1708 recordUseOfEvaluatedWeak(E); 1709 1710 // Just in case we're building an illegal pointer-to-member. 1711 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1712 if (FD && FD->isBitField()) 1713 E->setObjectKind(OK_BitField); 1714 1715 return E; 1716 } 1717 1718 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1719 /// possibly a list of template arguments. 1720 /// 1721 /// If this produces template arguments, it is permitted to call 1722 /// DecomposeTemplateName. 1723 /// 1724 /// This actually loses a lot of source location information for 1725 /// non-standard name kinds; we should consider preserving that in 1726 /// some way. 1727 void 1728 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1729 TemplateArgumentListInfo &Buffer, 1730 DeclarationNameInfo &NameInfo, 1731 const TemplateArgumentListInfo *&TemplateArgs) { 1732 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1733 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1734 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1735 1736 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1737 Id.TemplateId->NumArgs); 1738 translateTemplateArguments(TemplateArgsPtr, Buffer); 1739 1740 TemplateName TName = Id.TemplateId->Template.get(); 1741 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1742 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1743 TemplateArgs = &Buffer; 1744 } else { 1745 NameInfo = GetNameFromUnqualifiedId(Id); 1746 TemplateArgs = nullptr; 1747 } 1748 } 1749 1750 static void emitEmptyLookupTypoDiagnostic( 1751 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1752 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1753 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1754 DeclContext *Ctx = 1755 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1756 if (!TC) { 1757 // Emit a special diagnostic for failed member lookups. 1758 // FIXME: computing the declaration context might fail here (?) 1759 if (Ctx) 1760 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1761 << SS.getRange(); 1762 else 1763 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1764 return; 1765 } 1766 1767 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1768 bool DroppedSpecifier = 1769 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1770 unsigned NoteID = 1771 (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl())) 1772 ? diag::note_implicit_param_decl 1773 : diag::note_previous_decl; 1774 if (!Ctx) 1775 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1776 SemaRef.PDiag(NoteID)); 1777 else 1778 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1779 << Typo << Ctx << DroppedSpecifier 1780 << SS.getRange(), 1781 SemaRef.PDiag(NoteID)); 1782 } 1783 1784 /// Diagnose an empty lookup. 1785 /// 1786 /// \return false if new lookup candidates were found 1787 bool 1788 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1789 std::unique_ptr<CorrectionCandidateCallback> CCC, 1790 TemplateArgumentListInfo *ExplicitTemplateArgs, 1791 ArrayRef<Expr *> Args, TypoExpr **Out) { 1792 DeclarationName Name = R.getLookupName(); 1793 1794 unsigned diagnostic = diag::err_undeclared_var_use; 1795 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1796 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1797 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1798 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1799 diagnostic = diag::err_undeclared_use; 1800 diagnostic_suggest = diag::err_undeclared_use_suggest; 1801 } 1802 1803 // If the original lookup was an unqualified lookup, fake an 1804 // unqualified lookup. This is useful when (for example) the 1805 // original lookup would not have found something because it was a 1806 // dependent name. 1807 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1808 while (DC) { 1809 if (isa<CXXRecordDecl>(DC)) { 1810 LookupQualifiedName(R, DC); 1811 1812 if (!R.empty()) { 1813 // Don't give errors about ambiguities in this lookup. 1814 R.suppressDiagnostics(); 1815 1816 // During a default argument instantiation the CurContext points 1817 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1818 // function parameter list, hence add an explicit check. 1819 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1820 ActiveTemplateInstantiations.back().Kind == 1821 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1822 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1823 bool isInstance = CurMethod && 1824 CurMethod->isInstance() && 1825 DC == CurMethod->getParent() && !isDefaultArgument; 1826 1827 // Give a code modification hint to insert 'this->'. 1828 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1829 // Actually quite difficult! 1830 if (getLangOpts().MSVCCompat) 1831 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1832 if (isInstance) { 1833 Diag(R.getNameLoc(), diagnostic) << Name 1834 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1835 CheckCXXThisCapture(R.getNameLoc()); 1836 } else { 1837 Diag(R.getNameLoc(), diagnostic) << Name; 1838 } 1839 1840 // Do we really want to note all of these? 1841 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1842 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1843 1844 // Return true if we are inside a default argument instantiation 1845 // and the found name refers to an instance member function, otherwise 1846 // the function calling DiagnoseEmptyLookup will try to create an 1847 // implicit member call and this is wrong for default argument. 1848 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1849 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1850 return true; 1851 } 1852 1853 // Tell the callee to try to recover. 1854 return false; 1855 } 1856 1857 R.clear(); 1858 } 1859 1860 // In Microsoft mode, if we are performing lookup from within a friend 1861 // function definition declared at class scope then we must set 1862 // DC to the lexical parent to be able to search into the parent 1863 // class. 1864 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1865 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1866 DC->getLexicalParent()->isRecord()) 1867 DC = DC->getLexicalParent(); 1868 else 1869 DC = DC->getParent(); 1870 } 1871 1872 // We didn't find anything, so try to correct for a typo. 1873 TypoCorrection Corrected; 1874 if (S && Out) { 1875 SourceLocation TypoLoc = R.getNameLoc(); 1876 assert(!ExplicitTemplateArgs && 1877 "Diagnosing an empty lookup with explicit template args!"); 1878 *Out = CorrectTypoDelayed( 1879 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1880 [=](const TypoCorrection &TC) { 1881 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1882 diagnostic, diagnostic_suggest); 1883 }, 1884 nullptr, CTK_ErrorRecovery); 1885 if (*Out) 1886 return true; 1887 } else if (S && (Corrected = 1888 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1889 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1890 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1891 bool DroppedSpecifier = 1892 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1893 R.setLookupName(Corrected.getCorrection()); 1894 1895 bool AcceptableWithRecovery = false; 1896 bool AcceptableWithoutRecovery = false; 1897 NamedDecl *ND = Corrected.getCorrectionDecl(); 1898 if (ND) { 1899 if (Corrected.isOverloaded()) { 1900 OverloadCandidateSet OCS(R.getNameLoc(), 1901 OverloadCandidateSet::CSK_Normal); 1902 OverloadCandidateSet::iterator Best; 1903 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1904 CDEnd = Corrected.end(); 1905 CD != CDEnd; ++CD) { 1906 if (FunctionTemplateDecl *FTD = 1907 dyn_cast<FunctionTemplateDecl>(*CD)) 1908 AddTemplateOverloadCandidate( 1909 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1910 Args, OCS); 1911 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1912 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1913 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1914 Args, OCS); 1915 } 1916 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1917 case OR_Success: 1918 ND = Best->Function; 1919 Corrected.setCorrectionDecl(ND); 1920 break; 1921 default: 1922 // FIXME: Arbitrarily pick the first declaration for the note. 1923 Corrected.setCorrectionDecl(ND); 1924 break; 1925 } 1926 } 1927 R.addDecl(ND); 1928 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1929 CXXRecordDecl *Record = nullptr; 1930 if (Corrected.getCorrectionSpecifier()) { 1931 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1932 Record = Ty->getAsCXXRecordDecl(); 1933 } 1934 if (!Record) 1935 Record = cast<CXXRecordDecl>( 1936 ND->getDeclContext()->getRedeclContext()); 1937 R.setNamingClass(Record); 1938 } 1939 1940 AcceptableWithRecovery = 1941 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1942 // FIXME: If we ended up with a typo for a type name or 1943 // Objective-C class name, we're in trouble because the parser 1944 // is in the wrong place to recover. Suggest the typo 1945 // correction, but don't make it a fix-it since we're not going 1946 // to recover well anyway. 1947 AcceptableWithoutRecovery = 1948 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1949 } else { 1950 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1951 // because we aren't able to recover. 1952 AcceptableWithoutRecovery = true; 1953 } 1954 1955 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1956 unsigned NoteID = (Corrected.getCorrectionDecl() && 1957 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1958 ? diag::note_implicit_param_decl 1959 : diag::note_previous_decl; 1960 if (SS.isEmpty()) 1961 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1962 PDiag(NoteID), AcceptableWithRecovery); 1963 else 1964 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1965 << Name << computeDeclContext(SS, false) 1966 << DroppedSpecifier << SS.getRange(), 1967 PDiag(NoteID), AcceptableWithRecovery); 1968 1969 // Tell the callee whether to try to recover. 1970 return !AcceptableWithRecovery; 1971 } 1972 } 1973 R.clear(); 1974 1975 // Emit a special diagnostic for failed member lookups. 1976 // FIXME: computing the declaration context might fail here (?) 1977 if (!SS.isEmpty()) { 1978 Diag(R.getNameLoc(), diag::err_no_member) 1979 << Name << computeDeclContext(SS, false) 1980 << SS.getRange(); 1981 return true; 1982 } 1983 1984 // Give up, we can't recover. 1985 Diag(R.getNameLoc(), diagnostic) << Name; 1986 return true; 1987 } 1988 1989 /// In Microsoft mode, if we are inside a template class whose parent class has 1990 /// dependent base classes, and we can't resolve an unqualified identifier, then 1991 /// assume the identifier is a member of a dependent base class. We can only 1992 /// recover successfully in static methods, instance methods, and other contexts 1993 /// where 'this' is available. This doesn't precisely match MSVC's 1994 /// instantiation model, but it's close enough. 1995 static Expr * 1996 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1997 DeclarationNameInfo &NameInfo, 1998 SourceLocation TemplateKWLoc, 1999 const TemplateArgumentListInfo *TemplateArgs) { 2000 // Only try to recover from lookup into dependent bases in static methods or 2001 // contexts where 'this' is available. 2002 QualType ThisType = S.getCurrentThisType(); 2003 const CXXRecordDecl *RD = nullptr; 2004 if (!ThisType.isNull()) 2005 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2006 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2007 RD = MD->getParent(); 2008 if (!RD || !RD->hasAnyDependentBases()) 2009 return nullptr; 2010 2011 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2012 // is available, suggest inserting 'this->' as a fixit. 2013 SourceLocation Loc = NameInfo.getLoc(); 2014 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2015 DB << NameInfo.getName() << RD; 2016 2017 if (!ThisType.isNull()) { 2018 DB << FixItHint::CreateInsertion(Loc, "this->"); 2019 return CXXDependentScopeMemberExpr::Create( 2020 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2021 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2022 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2023 } 2024 2025 // Synthesize a fake NNS that points to the derived class. This will 2026 // perform name lookup during template instantiation. 2027 CXXScopeSpec SS; 2028 auto *NNS = 2029 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2030 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2031 return DependentScopeDeclRefExpr::Create( 2032 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2033 TemplateArgs); 2034 } 2035 2036 ExprResult 2037 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2038 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2039 bool HasTrailingLParen, bool IsAddressOfOperand, 2040 std::unique_ptr<CorrectionCandidateCallback> CCC, 2041 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2042 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2043 "cannot be direct & operand and have a trailing lparen"); 2044 if (SS.isInvalid()) 2045 return ExprError(); 2046 2047 TemplateArgumentListInfo TemplateArgsBuffer; 2048 2049 // Decompose the UnqualifiedId into the following data. 2050 DeclarationNameInfo NameInfo; 2051 const TemplateArgumentListInfo *TemplateArgs; 2052 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2053 2054 DeclarationName Name = NameInfo.getName(); 2055 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2056 SourceLocation NameLoc = NameInfo.getLoc(); 2057 2058 // C++ [temp.dep.expr]p3: 2059 // An id-expression is type-dependent if it contains: 2060 // -- an identifier that was declared with a dependent type, 2061 // (note: handled after lookup) 2062 // -- a template-id that is dependent, 2063 // (note: handled in BuildTemplateIdExpr) 2064 // -- a conversion-function-id that specifies a dependent type, 2065 // -- a nested-name-specifier that contains a class-name that 2066 // names a dependent type. 2067 // Determine whether this is a member of an unknown specialization; 2068 // we need to handle these differently. 2069 bool DependentID = false; 2070 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2071 Name.getCXXNameType()->isDependentType()) { 2072 DependentID = true; 2073 } else if (SS.isSet()) { 2074 if (DeclContext *DC = computeDeclContext(SS, false)) { 2075 if (RequireCompleteDeclContext(SS, DC)) 2076 return ExprError(); 2077 } else { 2078 DependentID = true; 2079 } 2080 } 2081 2082 if (DependentID) 2083 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2084 IsAddressOfOperand, TemplateArgs); 2085 2086 // Perform the required lookup. 2087 LookupResult R(*this, NameInfo, 2088 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2089 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2090 if (TemplateArgs) { 2091 // Lookup the template name again to correctly establish the context in 2092 // which it was found. This is really unfortunate as we already did the 2093 // lookup to determine that it was a template name in the first place. If 2094 // this becomes a performance hit, we can work harder to preserve those 2095 // results until we get here but it's likely not worth it. 2096 bool MemberOfUnknownSpecialization; 2097 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2098 MemberOfUnknownSpecialization); 2099 2100 if (MemberOfUnknownSpecialization || 2101 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2102 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2103 IsAddressOfOperand, TemplateArgs); 2104 } else { 2105 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2106 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2107 2108 // If the result might be in a dependent base class, this is a dependent 2109 // id-expression. 2110 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2111 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2112 IsAddressOfOperand, TemplateArgs); 2113 2114 // If this reference is in an Objective-C method, then we need to do 2115 // some special Objective-C lookup, too. 2116 if (IvarLookupFollowUp) { 2117 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2118 if (E.isInvalid()) 2119 return ExprError(); 2120 2121 if (Expr *Ex = E.getAs<Expr>()) 2122 return Ex; 2123 } 2124 } 2125 2126 if (R.isAmbiguous()) 2127 return ExprError(); 2128 2129 // This could be an implicitly declared function reference (legal in C90, 2130 // extension in C99, forbidden in C++). 2131 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2132 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2133 if (D) R.addDecl(D); 2134 } 2135 2136 // Determine whether this name might be a candidate for 2137 // argument-dependent lookup. 2138 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2139 2140 if (R.empty() && !ADL) { 2141 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2142 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2143 TemplateKWLoc, TemplateArgs)) 2144 return E; 2145 } 2146 2147 // Don't diagnose an empty lookup for inline assembly. 2148 if (IsInlineAsmIdentifier) 2149 return ExprError(); 2150 2151 // If this name wasn't predeclared and if this is not a function 2152 // call, diagnose the problem. 2153 TypoExpr *TE = nullptr; 2154 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2155 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2156 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2157 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2158 "Typo correction callback misconfigured"); 2159 if (CCC) { 2160 // Make sure the callback knows what the typo being diagnosed is. 2161 CCC->setTypoName(II); 2162 if (SS.isValid()) 2163 CCC->setTypoNNS(SS.getScopeRep()); 2164 } 2165 if (DiagnoseEmptyLookup(S, SS, R, 2166 CCC ? std::move(CCC) : std::move(DefaultValidator), 2167 nullptr, None, &TE)) { 2168 if (TE && KeywordReplacement) { 2169 auto &State = getTypoExprState(TE); 2170 auto BestTC = State.Consumer->getNextCorrection(); 2171 if (BestTC.isKeyword()) { 2172 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2173 if (State.DiagHandler) 2174 State.DiagHandler(BestTC); 2175 KeywordReplacement->startToken(); 2176 KeywordReplacement->setKind(II->getTokenID()); 2177 KeywordReplacement->setIdentifierInfo(II); 2178 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2179 // Clean up the state associated with the TypoExpr, since it has 2180 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2181 clearDelayedTypo(TE); 2182 // Signal that a correction to a keyword was performed by returning a 2183 // valid-but-null ExprResult. 2184 return (Expr*)nullptr; 2185 } 2186 State.Consumer->resetCorrectionStream(); 2187 } 2188 return TE ? TE : ExprError(); 2189 } 2190 2191 assert(!R.empty() && 2192 "DiagnoseEmptyLookup returned false but added no results"); 2193 2194 // If we found an Objective-C instance variable, let 2195 // LookupInObjCMethod build the appropriate expression to 2196 // reference the ivar. 2197 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2198 R.clear(); 2199 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2200 // In a hopelessly buggy code, Objective-C instance variable 2201 // lookup fails and no expression will be built to reference it. 2202 if (!E.isInvalid() && !E.get()) 2203 return ExprError(); 2204 return E; 2205 } 2206 } 2207 2208 // This is guaranteed from this point on. 2209 assert(!R.empty() || ADL); 2210 2211 // Check whether this might be a C++ implicit instance member access. 2212 // C++ [class.mfct.non-static]p3: 2213 // When an id-expression that is not part of a class member access 2214 // syntax and not used to form a pointer to member is used in the 2215 // body of a non-static member function of class X, if name lookup 2216 // resolves the name in the id-expression to a non-static non-type 2217 // member of some class C, the id-expression is transformed into a 2218 // class member access expression using (*this) as the 2219 // postfix-expression to the left of the . operator. 2220 // 2221 // But we don't actually need to do this for '&' operands if R 2222 // resolved to a function or overloaded function set, because the 2223 // expression is ill-formed if it actually works out to be a 2224 // non-static member function: 2225 // 2226 // C++ [expr.ref]p4: 2227 // Otherwise, if E1.E2 refers to a non-static member function. . . 2228 // [t]he expression can be used only as the left-hand operand of a 2229 // member function call. 2230 // 2231 // There are other safeguards against such uses, but it's important 2232 // to get this right here so that we don't end up making a 2233 // spuriously dependent expression if we're inside a dependent 2234 // instance method. 2235 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2236 bool MightBeImplicitMember; 2237 if (!IsAddressOfOperand) 2238 MightBeImplicitMember = true; 2239 else if (!SS.isEmpty()) 2240 MightBeImplicitMember = false; 2241 else if (R.isOverloadedResult()) 2242 MightBeImplicitMember = false; 2243 else if (R.isUnresolvableResult()) 2244 MightBeImplicitMember = true; 2245 else 2246 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2247 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2248 isa<MSPropertyDecl>(R.getFoundDecl()); 2249 2250 if (MightBeImplicitMember) 2251 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2252 R, TemplateArgs, S); 2253 } 2254 2255 if (TemplateArgs || TemplateKWLoc.isValid()) { 2256 2257 // In C++1y, if this is a variable template id, then check it 2258 // in BuildTemplateIdExpr(). 2259 // The single lookup result must be a variable template declaration. 2260 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2261 Id.TemplateId->Kind == TNK_Var_template) { 2262 assert(R.getAsSingle<VarTemplateDecl>() && 2263 "There should only be one declaration found."); 2264 } 2265 2266 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2267 } 2268 2269 return BuildDeclarationNameExpr(SS, R, ADL); 2270 } 2271 2272 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2273 /// declaration name, generally during template instantiation. 2274 /// There's a large number of things which don't need to be done along 2275 /// this path. 2276 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2277 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2278 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2279 DeclContext *DC = computeDeclContext(SS, false); 2280 if (!DC) 2281 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2282 NameInfo, /*TemplateArgs=*/nullptr); 2283 2284 if (RequireCompleteDeclContext(SS, DC)) 2285 return ExprError(); 2286 2287 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2288 LookupQualifiedName(R, DC); 2289 2290 if (R.isAmbiguous()) 2291 return ExprError(); 2292 2293 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2294 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2295 NameInfo, /*TemplateArgs=*/nullptr); 2296 2297 if (R.empty()) { 2298 Diag(NameInfo.getLoc(), diag::err_no_member) 2299 << NameInfo.getName() << DC << SS.getRange(); 2300 return ExprError(); 2301 } 2302 2303 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2304 // Diagnose a missing typename if this resolved unambiguously to a type in 2305 // a dependent context. If we can recover with a type, downgrade this to 2306 // a warning in Microsoft compatibility mode. 2307 unsigned DiagID = diag::err_typename_missing; 2308 if (RecoveryTSI && getLangOpts().MSVCCompat) 2309 DiagID = diag::ext_typename_missing; 2310 SourceLocation Loc = SS.getBeginLoc(); 2311 auto D = Diag(Loc, DiagID); 2312 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2313 << SourceRange(Loc, NameInfo.getEndLoc()); 2314 2315 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2316 // context. 2317 if (!RecoveryTSI) 2318 return ExprError(); 2319 2320 // Only issue the fixit if we're prepared to recover. 2321 D << FixItHint::CreateInsertion(Loc, "typename "); 2322 2323 // Recover by pretending this was an elaborated type. 2324 QualType Ty = Context.getTypeDeclType(TD); 2325 TypeLocBuilder TLB; 2326 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2327 2328 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2329 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2330 QTL.setElaboratedKeywordLoc(SourceLocation()); 2331 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2332 2333 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2334 2335 return ExprEmpty(); 2336 } 2337 2338 // Defend against this resolving to an implicit member access. We usually 2339 // won't get here if this might be a legitimate a class member (we end up in 2340 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2341 // a pointer-to-member or in an unevaluated context in C++11. 2342 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2343 return BuildPossibleImplicitMemberExpr(SS, 2344 /*TemplateKWLoc=*/SourceLocation(), 2345 R, /*TemplateArgs=*/nullptr, S); 2346 2347 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2348 } 2349 2350 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2351 /// detected that we're currently inside an ObjC method. Perform some 2352 /// additional lookup. 2353 /// 2354 /// Ideally, most of this would be done by lookup, but there's 2355 /// actually quite a lot of extra work involved. 2356 /// 2357 /// Returns a null sentinel to indicate trivial success. 2358 ExprResult 2359 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2360 IdentifierInfo *II, bool AllowBuiltinCreation) { 2361 SourceLocation Loc = Lookup.getNameLoc(); 2362 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2363 2364 // Check for error condition which is already reported. 2365 if (!CurMethod) 2366 return ExprError(); 2367 2368 // There are two cases to handle here. 1) scoped lookup could have failed, 2369 // in which case we should look for an ivar. 2) scoped lookup could have 2370 // found a decl, but that decl is outside the current instance method (i.e. 2371 // a global variable). In these two cases, we do a lookup for an ivar with 2372 // this name, if the lookup sucedes, we replace it our current decl. 2373 2374 // If we're in a class method, we don't normally want to look for 2375 // ivars. But if we don't find anything else, and there's an 2376 // ivar, that's an error. 2377 bool IsClassMethod = CurMethod->isClassMethod(); 2378 2379 bool LookForIvars; 2380 if (Lookup.empty()) 2381 LookForIvars = true; 2382 else if (IsClassMethod) 2383 LookForIvars = false; 2384 else 2385 LookForIvars = (Lookup.isSingleResult() && 2386 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2387 ObjCInterfaceDecl *IFace = nullptr; 2388 if (LookForIvars) { 2389 IFace = CurMethod->getClassInterface(); 2390 ObjCInterfaceDecl *ClassDeclared; 2391 ObjCIvarDecl *IV = nullptr; 2392 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2393 // Diagnose using an ivar in a class method. 2394 if (IsClassMethod) 2395 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2396 << IV->getDeclName()); 2397 2398 // If we're referencing an invalid decl, just return this as a silent 2399 // error node. The error diagnostic was already emitted on the decl. 2400 if (IV->isInvalidDecl()) 2401 return ExprError(); 2402 2403 // Check if referencing a field with __attribute__((deprecated)). 2404 if (DiagnoseUseOfDecl(IV, Loc)) 2405 return ExprError(); 2406 2407 // Diagnose the use of an ivar outside of the declaring class. 2408 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2409 !declaresSameEntity(ClassDeclared, IFace) && 2410 !getLangOpts().DebuggerSupport) 2411 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2412 2413 // FIXME: This should use a new expr for a direct reference, don't 2414 // turn this into Self->ivar, just return a BareIVarExpr or something. 2415 IdentifierInfo &II = Context.Idents.get("self"); 2416 UnqualifiedId SelfName; 2417 SelfName.setIdentifier(&II, SourceLocation()); 2418 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2419 CXXScopeSpec SelfScopeSpec; 2420 SourceLocation TemplateKWLoc; 2421 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2422 SelfName, false, false); 2423 if (SelfExpr.isInvalid()) 2424 return ExprError(); 2425 2426 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2427 if (SelfExpr.isInvalid()) 2428 return ExprError(); 2429 2430 MarkAnyDeclReferenced(Loc, IV, true); 2431 2432 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2433 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2434 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2435 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2436 2437 ObjCIvarRefExpr *Result = new (Context) 2438 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2439 IV->getLocation(), SelfExpr.get(), true, true); 2440 2441 if (getLangOpts().ObjCAutoRefCount) { 2442 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2443 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2444 recordUseOfEvaluatedWeak(Result); 2445 } 2446 if (CurContext->isClosure()) 2447 Diag(Loc, diag::warn_implicitly_retains_self) 2448 << FixItHint::CreateInsertion(Loc, "self->"); 2449 } 2450 2451 return Result; 2452 } 2453 } else if (CurMethod->isInstanceMethod()) { 2454 // We should warn if a local variable hides an ivar. 2455 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2456 ObjCInterfaceDecl *ClassDeclared; 2457 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2458 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2459 declaresSameEntity(IFace, ClassDeclared)) 2460 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2461 } 2462 } 2463 } else if (Lookup.isSingleResult() && 2464 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2465 // If accessing a stand-alone ivar in a class method, this is an error. 2466 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2467 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2468 << IV->getDeclName()); 2469 } 2470 2471 if (Lookup.empty() && II && AllowBuiltinCreation) { 2472 // FIXME. Consolidate this with similar code in LookupName. 2473 if (unsigned BuiltinID = II->getBuiltinID()) { 2474 if (!(getLangOpts().CPlusPlus && 2475 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2476 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2477 S, Lookup.isForRedeclaration(), 2478 Lookup.getNameLoc()); 2479 if (D) Lookup.addDecl(D); 2480 } 2481 } 2482 } 2483 // Sentinel value saying that we didn't do anything special. 2484 return ExprResult((Expr *)nullptr); 2485 } 2486 2487 /// \brief Cast a base object to a member's actual type. 2488 /// 2489 /// Logically this happens in three phases: 2490 /// 2491 /// * First we cast from the base type to the naming class. 2492 /// The naming class is the class into which we were looking 2493 /// when we found the member; it's the qualifier type if a 2494 /// qualifier was provided, and otherwise it's the base type. 2495 /// 2496 /// * Next we cast from the naming class to the declaring class. 2497 /// If the member we found was brought into a class's scope by 2498 /// a using declaration, this is that class; otherwise it's 2499 /// the class declaring the member. 2500 /// 2501 /// * Finally we cast from the declaring class to the "true" 2502 /// declaring class of the member. This conversion does not 2503 /// obey access control. 2504 ExprResult 2505 Sema::PerformObjectMemberConversion(Expr *From, 2506 NestedNameSpecifier *Qualifier, 2507 NamedDecl *FoundDecl, 2508 NamedDecl *Member) { 2509 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2510 if (!RD) 2511 return From; 2512 2513 QualType DestRecordType; 2514 QualType DestType; 2515 QualType FromRecordType; 2516 QualType FromType = From->getType(); 2517 bool PointerConversions = false; 2518 if (isa<FieldDecl>(Member)) { 2519 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2520 2521 if (FromType->getAs<PointerType>()) { 2522 DestType = Context.getPointerType(DestRecordType); 2523 FromRecordType = FromType->getPointeeType(); 2524 PointerConversions = true; 2525 } else { 2526 DestType = DestRecordType; 2527 FromRecordType = FromType; 2528 } 2529 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2530 if (Method->isStatic()) 2531 return From; 2532 2533 DestType = Method->getThisType(Context); 2534 DestRecordType = DestType->getPointeeType(); 2535 2536 if (FromType->getAs<PointerType>()) { 2537 FromRecordType = FromType->getPointeeType(); 2538 PointerConversions = true; 2539 } else { 2540 FromRecordType = FromType; 2541 DestType = DestRecordType; 2542 } 2543 } else { 2544 // No conversion necessary. 2545 return From; 2546 } 2547 2548 if (DestType->isDependentType() || FromType->isDependentType()) 2549 return From; 2550 2551 // If the unqualified types are the same, no conversion is necessary. 2552 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2553 return From; 2554 2555 SourceRange FromRange = From->getSourceRange(); 2556 SourceLocation FromLoc = FromRange.getBegin(); 2557 2558 ExprValueKind VK = From->getValueKind(); 2559 2560 // C++ [class.member.lookup]p8: 2561 // [...] Ambiguities can often be resolved by qualifying a name with its 2562 // class name. 2563 // 2564 // If the member was a qualified name and the qualified referred to a 2565 // specific base subobject type, we'll cast to that intermediate type 2566 // first and then to the object in which the member is declared. That allows 2567 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2568 // 2569 // class Base { public: int x; }; 2570 // class Derived1 : public Base { }; 2571 // class Derived2 : public Base { }; 2572 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2573 // 2574 // void VeryDerived::f() { 2575 // x = 17; // error: ambiguous base subobjects 2576 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2577 // } 2578 if (Qualifier && Qualifier->getAsType()) { 2579 QualType QType = QualType(Qualifier->getAsType(), 0); 2580 assert(QType->isRecordType() && "lookup done with non-record type"); 2581 2582 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2583 2584 // In C++98, the qualifier type doesn't actually have to be a base 2585 // type of the object type, in which case we just ignore it. 2586 // Otherwise build the appropriate casts. 2587 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2588 CXXCastPath BasePath; 2589 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2590 FromLoc, FromRange, &BasePath)) 2591 return ExprError(); 2592 2593 if (PointerConversions) 2594 QType = Context.getPointerType(QType); 2595 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2596 VK, &BasePath).get(); 2597 2598 FromType = QType; 2599 FromRecordType = QRecordType; 2600 2601 // If the qualifier type was the same as the destination type, 2602 // we're done. 2603 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2604 return From; 2605 } 2606 } 2607 2608 bool IgnoreAccess = false; 2609 2610 // If we actually found the member through a using declaration, cast 2611 // down to the using declaration's type. 2612 // 2613 // Pointer equality is fine here because only one declaration of a 2614 // class ever has member declarations. 2615 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2616 assert(isa<UsingShadowDecl>(FoundDecl)); 2617 QualType URecordType = Context.getTypeDeclType( 2618 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2619 2620 // We only need to do this if the naming-class to declaring-class 2621 // conversion is non-trivial. 2622 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2623 assert(IsDerivedFrom(FromRecordType, URecordType)); 2624 CXXCastPath BasePath; 2625 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2626 FromLoc, FromRange, &BasePath)) 2627 return ExprError(); 2628 2629 QualType UType = URecordType; 2630 if (PointerConversions) 2631 UType = Context.getPointerType(UType); 2632 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2633 VK, &BasePath).get(); 2634 FromType = UType; 2635 FromRecordType = URecordType; 2636 } 2637 2638 // We don't do access control for the conversion from the 2639 // declaring class to the true declaring class. 2640 IgnoreAccess = true; 2641 } 2642 2643 CXXCastPath BasePath; 2644 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2645 FromLoc, FromRange, &BasePath, 2646 IgnoreAccess)) 2647 return ExprError(); 2648 2649 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2650 VK, &BasePath); 2651 } 2652 2653 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2654 const LookupResult &R, 2655 bool HasTrailingLParen) { 2656 // Only when used directly as the postfix-expression of a call. 2657 if (!HasTrailingLParen) 2658 return false; 2659 2660 // Never if a scope specifier was provided. 2661 if (SS.isSet()) 2662 return false; 2663 2664 // Only in C++ or ObjC++. 2665 if (!getLangOpts().CPlusPlus) 2666 return false; 2667 2668 // Turn off ADL when we find certain kinds of declarations during 2669 // normal lookup: 2670 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2671 NamedDecl *D = *I; 2672 2673 // C++0x [basic.lookup.argdep]p3: 2674 // -- a declaration of a class member 2675 // Since using decls preserve this property, we check this on the 2676 // original decl. 2677 if (D->isCXXClassMember()) 2678 return false; 2679 2680 // C++0x [basic.lookup.argdep]p3: 2681 // -- a block-scope function declaration that is not a 2682 // using-declaration 2683 // NOTE: we also trigger this for function templates (in fact, we 2684 // don't check the decl type at all, since all other decl types 2685 // turn off ADL anyway). 2686 if (isa<UsingShadowDecl>(D)) 2687 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2688 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2689 return false; 2690 2691 // C++0x [basic.lookup.argdep]p3: 2692 // -- a declaration that is neither a function or a function 2693 // template 2694 // And also for builtin functions. 2695 if (isa<FunctionDecl>(D)) { 2696 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2697 2698 // But also builtin functions. 2699 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2700 return false; 2701 } else if (!isa<FunctionTemplateDecl>(D)) 2702 return false; 2703 } 2704 2705 return true; 2706 } 2707 2708 2709 /// Diagnoses obvious problems with the use of the given declaration 2710 /// as an expression. This is only actually called for lookups that 2711 /// were not overloaded, and it doesn't promise that the declaration 2712 /// will in fact be used. 2713 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2714 if (isa<TypedefNameDecl>(D)) { 2715 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2716 return true; 2717 } 2718 2719 if (isa<ObjCInterfaceDecl>(D)) { 2720 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2721 return true; 2722 } 2723 2724 if (isa<NamespaceDecl>(D)) { 2725 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2726 return true; 2727 } 2728 2729 return false; 2730 } 2731 2732 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2733 LookupResult &R, bool NeedsADL, 2734 bool AcceptInvalidDecl) { 2735 // If this is a single, fully-resolved result and we don't need ADL, 2736 // just build an ordinary singleton decl ref. 2737 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2738 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2739 R.getRepresentativeDecl(), nullptr, 2740 AcceptInvalidDecl); 2741 2742 // We only need to check the declaration if there's exactly one 2743 // result, because in the overloaded case the results can only be 2744 // functions and function templates. 2745 if (R.isSingleResult() && 2746 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2747 return ExprError(); 2748 2749 // Otherwise, just build an unresolved lookup expression. Suppress 2750 // any lookup-related diagnostics; we'll hash these out later, when 2751 // we've picked a target. 2752 R.suppressDiagnostics(); 2753 2754 UnresolvedLookupExpr *ULE 2755 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2756 SS.getWithLocInContext(Context), 2757 R.getLookupNameInfo(), 2758 NeedsADL, R.isOverloadedResult(), 2759 R.begin(), R.end()); 2760 2761 return ULE; 2762 } 2763 2764 /// \brief Complete semantic analysis for a reference to the given declaration. 2765 ExprResult Sema::BuildDeclarationNameExpr( 2766 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2767 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2768 bool AcceptInvalidDecl) { 2769 assert(D && "Cannot refer to a NULL declaration"); 2770 assert(!isa<FunctionTemplateDecl>(D) && 2771 "Cannot refer unambiguously to a function template"); 2772 2773 SourceLocation Loc = NameInfo.getLoc(); 2774 if (CheckDeclInExpr(*this, Loc, D)) 2775 return ExprError(); 2776 2777 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2778 // Specifically diagnose references to class templates that are missing 2779 // a template argument list. 2780 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2781 << Template << SS.getRange(); 2782 Diag(Template->getLocation(), diag::note_template_decl_here); 2783 return ExprError(); 2784 } 2785 2786 // Make sure that we're referring to a value. 2787 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2788 if (!VD) { 2789 Diag(Loc, diag::err_ref_non_value) 2790 << D << SS.getRange(); 2791 Diag(D->getLocation(), diag::note_declared_at); 2792 return ExprError(); 2793 } 2794 2795 // Check whether this declaration can be used. Note that we suppress 2796 // this check when we're going to perform argument-dependent lookup 2797 // on this function name, because this might not be the function 2798 // that overload resolution actually selects. 2799 if (DiagnoseUseOfDecl(VD, Loc)) 2800 return ExprError(); 2801 2802 // Only create DeclRefExpr's for valid Decl's. 2803 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2804 return ExprError(); 2805 2806 // Handle members of anonymous structs and unions. If we got here, 2807 // and the reference is to a class member indirect field, then this 2808 // must be the subject of a pointer-to-member expression. 2809 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2810 if (!indirectField->isCXXClassMember()) 2811 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2812 indirectField); 2813 2814 { 2815 QualType type = VD->getType(); 2816 ExprValueKind valueKind = VK_RValue; 2817 2818 switch (D->getKind()) { 2819 // Ignore all the non-ValueDecl kinds. 2820 #define ABSTRACT_DECL(kind) 2821 #define VALUE(type, base) 2822 #define DECL(type, base) \ 2823 case Decl::type: 2824 #include "clang/AST/DeclNodes.inc" 2825 llvm_unreachable("invalid value decl kind"); 2826 2827 // These shouldn't make it here. 2828 case Decl::ObjCAtDefsField: 2829 case Decl::ObjCIvar: 2830 llvm_unreachable("forming non-member reference to ivar?"); 2831 2832 // Enum constants are always r-values and never references. 2833 // Unresolved using declarations are dependent. 2834 case Decl::EnumConstant: 2835 case Decl::UnresolvedUsingValue: 2836 valueKind = VK_RValue; 2837 break; 2838 2839 // Fields and indirect fields that got here must be for 2840 // pointer-to-member expressions; we just call them l-values for 2841 // internal consistency, because this subexpression doesn't really 2842 // exist in the high-level semantics. 2843 case Decl::Field: 2844 case Decl::IndirectField: 2845 assert(getLangOpts().CPlusPlus && 2846 "building reference to field in C?"); 2847 2848 // These can't have reference type in well-formed programs, but 2849 // for internal consistency we do this anyway. 2850 type = type.getNonReferenceType(); 2851 valueKind = VK_LValue; 2852 break; 2853 2854 // Non-type template parameters are either l-values or r-values 2855 // depending on the type. 2856 case Decl::NonTypeTemplateParm: { 2857 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2858 type = reftype->getPointeeType(); 2859 valueKind = VK_LValue; // even if the parameter is an r-value reference 2860 break; 2861 } 2862 2863 // For non-references, we need to strip qualifiers just in case 2864 // the template parameter was declared as 'const int' or whatever. 2865 valueKind = VK_RValue; 2866 type = type.getUnqualifiedType(); 2867 break; 2868 } 2869 2870 case Decl::Var: 2871 case Decl::VarTemplateSpecialization: 2872 case Decl::VarTemplatePartialSpecialization: 2873 // In C, "extern void blah;" is valid and is an r-value. 2874 if (!getLangOpts().CPlusPlus && 2875 !type.hasQualifiers() && 2876 type->isVoidType()) { 2877 valueKind = VK_RValue; 2878 break; 2879 } 2880 // fallthrough 2881 2882 case Decl::ImplicitParam: 2883 case Decl::ParmVar: { 2884 // These are always l-values. 2885 valueKind = VK_LValue; 2886 type = type.getNonReferenceType(); 2887 2888 // FIXME: Does the addition of const really only apply in 2889 // potentially-evaluated contexts? Since the variable isn't actually 2890 // captured in an unevaluated context, it seems that the answer is no. 2891 if (!isUnevaluatedContext()) { 2892 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2893 if (!CapturedType.isNull()) 2894 type = CapturedType; 2895 } 2896 2897 break; 2898 } 2899 2900 case Decl::Function: { 2901 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2902 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2903 type = Context.BuiltinFnTy; 2904 valueKind = VK_RValue; 2905 break; 2906 } 2907 } 2908 2909 const FunctionType *fty = type->castAs<FunctionType>(); 2910 2911 // If we're referring to a function with an __unknown_anytype 2912 // result type, make the entire expression __unknown_anytype. 2913 if (fty->getReturnType() == Context.UnknownAnyTy) { 2914 type = Context.UnknownAnyTy; 2915 valueKind = VK_RValue; 2916 break; 2917 } 2918 2919 // Functions are l-values in C++. 2920 if (getLangOpts().CPlusPlus) { 2921 valueKind = VK_LValue; 2922 break; 2923 } 2924 2925 // C99 DR 316 says that, if a function type comes from a 2926 // function definition (without a prototype), that type is only 2927 // used for checking compatibility. Therefore, when referencing 2928 // the function, we pretend that we don't have the full function 2929 // type. 2930 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2931 isa<FunctionProtoType>(fty)) 2932 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2933 fty->getExtInfo()); 2934 2935 // Functions are r-values in C. 2936 valueKind = VK_RValue; 2937 break; 2938 } 2939 2940 case Decl::MSProperty: 2941 valueKind = VK_LValue; 2942 break; 2943 2944 case Decl::CXXMethod: 2945 // If we're referring to a method with an __unknown_anytype 2946 // result type, make the entire expression __unknown_anytype. 2947 // This should only be possible with a type written directly. 2948 if (const FunctionProtoType *proto 2949 = dyn_cast<FunctionProtoType>(VD->getType())) 2950 if (proto->getReturnType() == Context.UnknownAnyTy) { 2951 type = Context.UnknownAnyTy; 2952 valueKind = VK_RValue; 2953 break; 2954 } 2955 2956 // C++ methods are l-values if static, r-values if non-static. 2957 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2958 valueKind = VK_LValue; 2959 break; 2960 } 2961 // fallthrough 2962 2963 case Decl::CXXConversion: 2964 case Decl::CXXDestructor: 2965 case Decl::CXXConstructor: 2966 valueKind = VK_RValue; 2967 break; 2968 } 2969 2970 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2971 TemplateArgs); 2972 } 2973 } 2974 2975 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2976 SmallString<32> &Target) { 2977 Target.resize(CharByteWidth * (Source.size() + 1)); 2978 char *ResultPtr = &Target[0]; 2979 const UTF8 *ErrorPtr; 2980 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2981 (void)success; 2982 assert(success); 2983 Target.resize(ResultPtr - &Target[0]); 2984 } 2985 2986 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2987 PredefinedExpr::IdentType IT) { 2988 // Pick the current block, lambda, captured statement or function. 2989 Decl *currentDecl = nullptr; 2990 if (const BlockScopeInfo *BSI = getCurBlock()) 2991 currentDecl = BSI->TheDecl; 2992 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2993 currentDecl = LSI->CallOperator; 2994 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2995 currentDecl = CSI->TheCapturedDecl; 2996 else 2997 currentDecl = getCurFunctionOrMethodDecl(); 2998 2999 if (!currentDecl) { 3000 Diag(Loc, diag::ext_predef_outside_function); 3001 currentDecl = Context.getTranslationUnitDecl(); 3002 } 3003 3004 QualType ResTy; 3005 StringLiteral *SL = nullptr; 3006 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3007 ResTy = Context.DependentTy; 3008 else { 3009 // Pre-defined identifiers are of type char[x], where x is the length of 3010 // the string. 3011 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3012 unsigned Length = Str.length(); 3013 3014 llvm::APInt LengthI(32, Length + 1); 3015 if (IT == PredefinedExpr::LFunction) { 3016 ResTy = Context.WideCharTy.withConst(); 3017 SmallString<32> RawChars; 3018 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3019 Str, RawChars); 3020 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3021 /*IndexTypeQuals*/ 0); 3022 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3023 /*Pascal*/ false, ResTy, Loc); 3024 } else { 3025 ResTy = Context.CharTy.withConst(); 3026 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3027 /*IndexTypeQuals*/ 0); 3028 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3029 /*Pascal*/ false, ResTy, Loc); 3030 } 3031 } 3032 3033 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3034 } 3035 3036 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3037 PredefinedExpr::IdentType IT; 3038 3039 switch (Kind) { 3040 default: llvm_unreachable("Unknown simple primary expr!"); 3041 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3042 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3043 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3044 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3045 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3046 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3047 } 3048 3049 return BuildPredefinedExpr(Loc, IT); 3050 } 3051 3052 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3053 SmallString<16> CharBuffer; 3054 bool Invalid = false; 3055 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3056 if (Invalid) 3057 return ExprError(); 3058 3059 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3060 PP, Tok.getKind()); 3061 if (Literal.hadError()) 3062 return ExprError(); 3063 3064 QualType Ty; 3065 if (Literal.isWide()) 3066 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3067 else if (Literal.isUTF16()) 3068 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3069 else if (Literal.isUTF32()) 3070 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3071 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3072 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3073 else 3074 Ty = Context.CharTy; // 'x' -> char in C++ 3075 3076 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3077 if (Literal.isWide()) 3078 Kind = CharacterLiteral::Wide; 3079 else if (Literal.isUTF16()) 3080 Kind = CharacterLiteral::UTF16; 3081 else if (Literal.isUTF32()) 3082 Kind = CharacterLiteral::UTF32; 3083 3084 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3085 Tok.getLocation()); 3086 3087 if (Literal.getUDSuffix().empty()) 3088 return Lit; 3089 3090 // We're building a user-defined literal. 3091 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3092 SourceLocation UDSuffixLoc = 3093 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3094 3095 // Make sure we're allowed user-defined literals here. 3096 if (!UDLScope) 3097 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3098 3099 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3100 // operator "" X (ch) 3101 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3102 Lit, Tok.getLocation()); 3103 } 3104 3105 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3106 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3107 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3108 Context.IntTy, Loc); 3109 } 3110 3111 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3112 QualType Ty, SourceLocation Loc) { 3113 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3114 3115 using llvm::APFloat; 3116 APFloat Val(Format); 3117 3118 APFloat::opStatus result = Literal.GetFloatValue(Val); 3119 3120 // Overflow is always an error, but underflow is only an error if 3121 // we underflowed to zero (APFloat reports denormals as underflow). 3122 if ((result & APFloat::opOverflow) || 3123 ((result & APFloat::opUnderflow) && Val.isZero())) { 3124 unsigned diagnostic; 3125 SmallString<20> buffer; 3126 if (result & APFloat::opOverflow) { 3127 diagnostic = diag::warn_float_overflow; 3128 APFloat::getLargest(Format).toString(buffer); 3129 } else { 3130 diagnostic = diag::warn_float_underflow; 3131 APFloat::getSmallest(Format).toString(buffer); 3132 } 3133 3134 S.Diag(Loc, diagnostic) 3135 << Ty 3136 << StringRef(buffer.data(), buffer.size()); 3137 } 3138 3139 bool isExact = (result == APFloat::opOK); 3140 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3141 } 3142 3143 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3144 assert(E && "Invalid expression"); 3145 3146 if (E->isValueDependent()) 3147 return false; 3148 3149 QualType QT = E->getType(); 3150 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3151 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3152 return true; 3153 } 3154 3155 llvm::APSInt ValueAPS; 3156 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3157 3158 if (R.isInvalid()) 3159 return true; 3160 3161 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3162 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3163 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3164 << ValueAPS.toString(10) << ValueIsPositive; 3165 return true; 3166 } 3167 3168 return false; 3169 } 3170 3171 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3172 // Fast path for a single digit (which is quite common). A single digit 3173 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3174 if (Tok.getLength() == 1) { 3175 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3176 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3177 } 3178 3179 SmallString<128> SpellingBuffer; 3180 // NumericLiteralParser wants to overread by one character. Add padding to 3181 // the buffer in case the token is copied to the buffer. If getSpelling() 3182 // returns a StringRef to the memory buffer, it should have a null char at 3183 // the EOF, so it is also safe. 3184 SpellingBuffer.resize(Tok.getLength() + 1); 3185 3186 // Get the spelling of the token, which eliminates trigraphs, etc. 3187 bool Invalid = false; 3188 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3189 if (Invalid) 3190 return ExprError(); 3191 3192 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3193 if (Literal.hadError) 3194 return ExprError(); 3195 3196 if (Literal.hasUDSuffix()) { 3197 // We're building a user-defined literal. 3198 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3199 SourceLocation UDSuffixLoc = 3200 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3201 3202 // Make sure we're allowed user-defined literals here. 3203 if (!UDLScope) 3204 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3205 3206 QualType CookedTy; 3207 if (Literal.isFloatingLiteral()) { 3208 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3209 // long double, the literal is treated as a call of the form 3210 // operator "" X (f L) 3211 CookedTy = Context.LongDoubleTy; 3212 } else { 3213 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3214 // unsigned long long, the literal is treated as a call of the form 3215 // operator "" X (n ULL) 3216 CookedTy = Context.UnsignedLongLongTy; 3217 } 3218 3219 DeclarationName OpName = 3220 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3221 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3222 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3223 3224 SourceLocation TokLoc = Tok.getLocation(); 3225 3226 // Perform literal operator lookup to determine if we're building a raw 3227 // literal or a cooked one. 3228 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3229 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3230 /*AllowRaw*/true, /*AllowTemplate*/true, 3231 /*AllowStringTemplate*/false)) { 3232 case LOLR_Error: 3233 return ExprError(); 3234 3235 case LOLR_Cooked: { 3236 Expr *Lit; 3237 if (Literal.isFloatingLiteral()) { 3238 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3239 } else { 3240 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3241 if (Literal.GetIntegerValue(ResultVal)) 3242 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3243 << /* Unsigned */ 1; 3244 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3245 Tok.getLocation()); 3246 } 3247 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3248 } 3249 3250 case LOLR_Raw: { 3251 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3252 // literal is treated as a call of the form 3253 // operator "" X ("n") 3254 unsigned Length = Literal.getUDSuffixOffset(); 3255 QualType StrTy = Context.getConstantArrayType( 3256 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3257 ArrayType::Normal, 0); 3258 Expr *Lit = StringLiteral::Create( 3259 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3260 /*Pascal*/false, StrTy, &TokLoc, 1); 3261 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3262 } 3263 3264 case LOLR_Template: { 3265 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3266 // template), L is treated as a call fo the form 3267 // operator "" X <'c1', 'c2', ... 'ck'>() 3268 // where n is the source character sequence c1 c2 ... ck. 3269 TemplateArgumentListInfo ExplicitArgs; 3270 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3271 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3272 llvm::APSInt Value(CharBits, CharIsUnsigned); 3273 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3274 Value = TokSpelling[I]; 3275 TemplateArgument Arg(Context, Value, Context.CharTy); 3276 TemplateArgumentLocInfo ArgInfo; 3277 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3278 } 3279 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3280 &ExplicitArgs); 3281 } 3282 case LOLR_StringTemplate: 3283 llvm_unreachable("unexpected literal operator lookup result"); 3284 } 3285 } 3286 3287 Expr *Res; 3288 3289 if (Literal.isFloatingLiteral()) { 3290 QualType Ty; 3291 if (Literal.isFloat) 3292 Ty = Context.FloatTy; 3293 else if (!Literal.isLong) 3294 Ty = Context.DoubleTy; 3295 else 3296 Ty = Context.LongDoubleTy; 3297 3298 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3299 3300 if (Ty == Context.DoubleTy) { 3301 if (getLangOpts().SinglePrecisionConstants) { 3302 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3303 } else if (getLangOpts().OpenCL && 3304 !((getLangOpts().OpenCLVersion >= 120) || 3305 getOpenCLOptions().cl_khr_fp64)) { 3306 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3307 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3308 } 3309 } 3310 } else if (!Literal.isIntegerLiteral()) { 3311 return ExprError(); 3312 } else { 3313 QualType Ty; 3314 3315 // 'long long' is a C99 or C++11 feature. 3316 if (!getLangOpts().C99 && Literal.isLongLong) { 3317 if (getLangOpts().CPlusPlus) 3318 Diag(Tok.getLocation(), 3319 getLangOpts().CPlusPlus11 ? 3320 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3321 else 3322 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3323 } 3324 3325 // Get the value in the widest-possible width. 3326 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3327 llvm::APInt ResultVal(MaxWidth, 0); 3328 3329 if (Literal.GetIntegerValue(ResultVal)) { 3330 // If this value didn't fit into uintmax_t, error and force to ull. 3331 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3332 << /* Unsigned */ 1; 3333 Ty = Context.UnsignedLongLongTy; 3334 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3335 "long long is not intmax_t?"); 3336 } else { 3337 // If this value fits into a ULL, try to figure out what else it fits into 3338 // according to the rules of C99 6.4.4.1p5. 3339 3340 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3341 // be an unsigned int. 3342 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3343 3344 // Check from smallest to largest, picking the smallest type we can. 3345 unsigned Width = 0; 3346 3347 // Microsoft specific integer suffixes are explicitly sized. 3348 if (Literal.MicrosoftInteger) { 3349 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3350 Width = 8; 3351 Ty = Context.CharTy; 3352 } else { 3353 Width = Literal.MicrosoftInteger; 3354 Ty = Context.getIntTypeForBitwidth(Width, 3355 /*Signed=*/!Literal.isUnsigned); 3356 } 3357 } 3358 3359 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3360 // Are int/unsigned possibilities? 3361 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3362 3363 // Does it fit in a unsigned int? 3364 if (ResultVal.isIntN(IntSize)) { 3365 // Does it fit in a signed int? 3366 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3367 Ty = Context.IntTy; 3368 else if (AllowUnsigned) 3369 Ty = Context.UnsignedIntTy; 3370 Width = IntSize; 3371 } 3372 } 3373 3374 // Are long/unsigned long possibilities? 3375 if (Ty.isNull() && !Literal.isLongLong) { 3376 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3377 3378 // Does it fit in a unsigned long? 3379 if (ResultVal.isIntN(LongSize)) { 3380 // Does it fit in a signed long? 3381 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3382 Ty = Context.LongTy; 3383 else if (AllowUnsigned) 3384 Ty = Context.UnsignedLongTy; 3385 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3386 // is compatible. 3387 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3388 const unsigned LongLongSize = 3389 Context.getTargetInfo().getLongLongWidth(); 3390 Diag(Tok.getLocation(), 3391 getLangOpts().CPlusPlus 3392 ? Literal.isLong 3393 ? diag::warn_old_implicitly_unsigned_long_cxx 3394 : /*C++98 UB*/ diag:: 3395 ext_old_implicitly_unsigned_long_cxx 3396 : diag::warn_old_implicitly_unsigned_long) 3397 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3398 : /*will be ill-formed*/ 1); 3399 Ty = Context.UnsignedLongTy; 3400 } 3401 Width = LongSize; 3402 } 3403 } 3404 3405 // Check long long if needed. 3406 if (Ty.isNull()) { 3407 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3408 3409 // Does it fit in a unsigned long long? 3410 if (ResultVal.isIntN(LongLongSize)) { 3411 // Does it fit in a signed long long? 3412 // To be compatible with MSVC, hex integer literals ending with the 3413 // LL or i64 suffix are always signed in Microsoft mode. 3414 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3415 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3416 Ty = Context.LongLongTy; 3417 else if (AllowUnsigned) 3418 Ty = Context.UnsignedLongLongTy; 3419 Width = LongLongSize; 3420 } 3421 } 3422 3423 // If we still couldn't decide a type, we probably have something that 3424 // does not fit in a signed long long, but has no U suffix. 3425 if (Ty.isNull()) { 3426 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3427 Ty = Context.UnsignedLongLongTy; 3428 Width = Context.getTargetInfo().getLongLongWidth(); 3429 } 3430 3431 if (ResultVal.getBitWidth() != Width) 3432 ResultVal = ResultVal.trunc(Width); 3433 } 3434 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3435 } 3436 3437 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3438 if (Literal.isImaginary) 3439 Res = new (Context) ImaginaryLiteral(Res, 3440 Context.getComplexType(Res->getType())); 3441 3442 return Res; 3443 } 3444 3445 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3446 assert(E && "ActOnParenExpr() missing expr"); 3447 return new (Context) ParenExpr(L, R, E); 3448 } 3449 3450 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3451 SourceLocation Loc, 3452 SourceRange ArgRange) { 3453 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3454 // scalar or vector data type argument..." 3455 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3456 // type (C99 6.2.5p18) or void. 3457 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3458 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3459 << T << ArgRange; 3460 return true; 3461 } 3462 3463 assert((T->isVoidType() || !T->isIncompleteType()) && 3464 "Scalar types should always be complete"); 3465 return false; 3466 } 3467 3468 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3469 SourceLocation Loc, 3470 SourceRange ArgRange, 3471 UnaryExprOrTypeTrait TraitKind) { 3472 // Invalid types must be hard errors for SFINAE in C++. 3473 if (S.LangOpts.CPlusPlus) 3474 return true; 3475 3476 // C99 6.5.3.4p1: 3477 if (T->isFunctionType() && 3478 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3479 // sizeof(function)/alignof(function) is allowed as an extension. 3480 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3481 << TraitKind << ArgRange; 3482 return false; 3483 } 3484 3485 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3486 // this is an error (OpenCL v1.1 s6.3.k) 3487 if (T->isVoidType()) { 3488 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3489 : diag::ext_sizeof_alignof_void_type; 3490 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3491 return false; 3492 } 3493 3494 return true; 3495 } 3496 3497 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3498 SourceLocation Loc, 3499 SourceRange ArgRange, 3500 UnaryExprOrTypeTrait TraitKind) { 3501 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3502 // runtime doesn't allow it. 3503 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3504 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3505 << T << (TraitKind == UETT_SizeOf) 3506 << ArgRange; 3507 return true; 3508 } 3509 3510 return false; 3511 } 3512 3513 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3514 /// pointer type is equal to T) and emit a warning if it is. 3515 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3516 Expr *E) { 3517 // Don't warn if the operation changed the type. 3518 if (T != E->getType()) 3519 return; 3520 3521 // Now look for array decays. 3522 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3523 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3524 return; 3525 3526 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3527 << ICE->getType() 3528 << ICE->getSubExpr()->getType(); 3529 } 3530 3531 /// \brief Check the constraints on expression operands to unary type expression 3532 /// and type traits. 3533 /// 3534 /// Completes any types necessary and validates the constraints on the operand 3535 /// expression. The logic mostly mirrors the type-based overload, but may modify 3536 /// the expression as it completes the type for that expression through template 3537 /// instantiation, etc. 3538 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3539 UnaryExprOrTypeTrait ExprKind) { 3540 QualType ExprTy = E->getType(); 3541 assert(!ExprTy->isReferenceType()); 3542 3543 if (ExprKind == UETT_VecStep) 3544 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3545 E->getSourceRange()); 3546 3547 // Whitelist some types as extensions 3548 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3549 E->getSourceRange(), ExprKind)) 3550 return false; 3551 3552 // 'alignof' applied to an expression only requires the base element type of 3553 // the expression to be complete. 'sizeof' requires the expression's type to 3554 // be complete (and will attempt to complete it if it's an array of unknown 3555 // bound). 3556 if (ExprKind == UETT_AlignOf) { 3557 if (RequireCompleteType(E->getExprLoc(), 3558 Context.getBaseElementType(E->getType()), 3559 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3560 E->getSourceRange())) 3561 return true; 3562 } else { 3563 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3564 ExprKind, E->getSourceRange())) 3565 return true; 3566 } 3567 3568 // Completing the expression's type may have changed it. 3569 ExprTy = E->getType(); 3570 assert(!ExprTy->isReferenceType()); 3571 3572 if (ExprTy->isFunctionType()) { 3573 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3574 << ExprKind << E->getSourceRange(); 3575 return true; 3576 } 3577 3578 // The operand for sizeof and alignof is in an unevaluated expression context, 3579 // so side effects could result in unintended consequences. 3580 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3581 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3582 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3583 3584 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3585 E->getSourceRange(), ExprKind)) 3586 return true; 3587 3588 if (ExprKind == UETT_SizeOf) { 3589 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3590 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3591 QualType OType = PVD->getOriginalType(); 3592 QualType Type = PVD->getType(); 3593 if (Type->isPointerType() && OType->isArrayType()) { 3594 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3595 << Type << OType; 3596 Diag(PVD->getLocation(), diag::note_declared_at); 3597 } 3598 } 3599 } 3600 3601 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3602 // decays into a pointer and returns an unintended result. This is most 3603 // likely a typo for "sizeof(array) op x". 3604 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3605 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3606 BO->getLHS()); 3607 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3608 BO->getRHS()); 3609 } 3610 } 3611 3612 return false; 3613 } 3614 3615 /// \brief Check the constraints on operands to unary expression and type 3616 /// traits. 3617 /// 3618 /// This will complete any types necessary, and validate the various constraints 3619 /// on those operands. 3620 /// 3621 /// The UsualUnaryConversions() function is *not* called by this routine. 3622 /// C99 6.3.2.1p[2-4] all state: 3623 /// Except when it is the operand of the sizeof operator ... 3624 /// 3625 /// C++ [expr.sizeof]p4 3626 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3627 /// standard conversions are not applied to the operand of sizeof. 3628 /// 3629 /// This policy is followed for all of the unary trait expressions. 3630 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3631 SourceLocation OpLoc, 3632 SourceRange ExprRange, 3633 UnaryExprOrTypeTrait ExprKind) { 3634 if (ExprType->isDependentType()) 3635 return false; 3636 3637 // C++ [expr.sizeof]p2: 3638 // When applied to a reference or a reference type, the result 3639 // is the size of the referenced type. 3640 // C++11 [expr.alignof]p3: 3641 // When alignof is applied to a reference type, the result 3642 // shall be the alignment of the referenced type. 3643 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3644 ExprType = Ref->getPointeeType(); 3645 3646 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3647 // When alignof or _Alignof is applied to an array type, the result 3648 // is the alignment of the element type. 3649 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3650 ExprType = Context.getBaseElementType(ExprType); 3651 3652 if (ExprKind == UETT_VecStep) 3653 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3654 3655 // Whitelist some types as extensions 3656 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3657 ExprKind)) 3658 return false; 3659 3660 if (RequireCompleteType(OpLoc, ExprType, 3661 diag::err_sizeof_alignof_incomplete_type, 3662 ExprKind, ExprRange)) 3663 return true; 3664 3665 if (ExprType->isFunctionType()) { 3666 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3667 << ExprKind << ExprRange; 3668 return true; 3669 } 3670 3671 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3672 ExprKind)) 3673 return true; 3674 3675 return false; 3676 } 3677 3678 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3679 E = E->IgnoreParens(); 3680 3681 // Cannot know anything else if the expression is dependent. 3682 if (E->isTypeDependent()) 3683 return false; 3684 3685 if (E->getObjectKind() == OK_BitField) { 3686 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3687 << 1 << E->getSourceRange(); 3688 return true; 3689 } 3690 3691 ValueDecl *D = nullptr; 3692 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3693 D = DRE->getDecl(); 3694 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3695 D = ME->getMemberDecl(); 3696 } 3697 3698 // If it's a field, require the containing struct to have a 3699 // complete definition so that we can compute the layout. 3700 // 3701 // This can happen in C++11 onwards, either by naming the member 3702 // in a way that is not transformed into a member access expression 3703 // (in an unevaluated operand, for instance), or by naming the member 3704 // in a trailing-return-type. 3705 // 3706 // For the record, since __alignof__ on expressions is a GCC 3707 // extension, GCC seems to permit this but always gives the 3708 // nonsensical answer 0. 3709 // 3710 // We don't really need the layout here --- we could instead just 3711 // directly check for all the appropriate alignment-lowing 3712 // attributes --- but that would require duplicating a lot of 3713 // logic that just isn't worth duplicating for such a marginal 3714 // use-case. 3715 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3716 // Fast path this check, since we at least know the record has a 3717 // definition if we can find a member of it. 3718 if (!FD->getParent()->isCompleteDefinition()) { 3719 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3720 << E->getSourceRange(); 3721 return true; 3722 } 3723 3724 // Otherwise, if it's a field, and the field doesn't have 3725 // reference type, then it must have a complete type (or be a 3726 // flexible array member, which we explicitly want to 3727 // white-list anyway), which makes the following checks trivial. 3728 if (!FD->getType()->isReferenceType()) 3729 return false; 3730 } 3731 3732 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3733 } 3734 3735 bool Sema::CheckVecStepExpr(Expr *E) { 3736 E = E->IgnoreParens(); 3737 3738 // Cannot know anything else if the expression is dependent. 3739 if (E->isTypeDependent()) 3740 return false; 3741 3742 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3743 } 3744 3745 /// \brief Build a sizeof or alignof expression given a type operand. 3746 ExprResult 3747 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3748 SourceLocation OpLoc, 3749 UnaryExprOrTypeTrait ExprKind, 3750 SourceRange R) { 3751 if (!TInfo) 3752 return ExprError(); 3753 3754 QualType T = TInfo->getType(); 3755 3756 if (!T->isDependentType() && 3757 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3758 return ExprError(); 3759 3760 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3761 return new (Context) UnaryExprOrTypeTraitExpr( 3762 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3763 } 3764 3765 /// \brief Build a sizeof or alignof expression given an expression 3766 /// operand. 3767 ExprResult 3768 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3769 UnaryExprOrTypeTrait ExprKind) { 3770 ExprResult PE = CheckPlaceholderExpr(E); 3771 if (PE.isInvalid()) 3772 return ExprError(); 3773 3774 E = PE.get(); 3775 3776 // Verify that the operand is valid. 3777 bool isInvalid = false; 3778 if (E->isTypeDependent()) { 3779 // Delay type-checking for type-dependent expressions. 3780 } else if (ExprKind == UETT_AlignOf) { 3781 isInvalid = CheckAlignOfExpr(*this, E); 3782 } else if (ExprKind == UETT_VecStep) { 3783 isInvalid = CheckVecStepExpr(E); 3784 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3785 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3786 isInvalid = true; 3787 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3788 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3789 isInvalid = true; 3790 } else { 3791 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3792 } 3793 3794 if (isInvalid) 3795 return ExprError(); 3796 3797 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3798 PE = TransformToPotentiallyEvaluated(E); 3799 if (PE.isInvalid()) return ExprError(); 3800 E = PE.get(); 3801 } 3802 3803 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3804 return new (Context) UnaryExprOrTypeTraitExpr( 3805 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3806 } 3807 3808 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3809 /// expr and the same for @c alignof and @c __alignof 3810 /// Note that the ArgRange is invalid if isType is false. 3811 ExprResult 3812 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3813 UnaryExprOrTypeTrait ExprKind, bool IsType, 3814 void *TyOrEx, SourceRange ArgRange) { 3815 // If error parsing type, ignore. 3816 if (!TyOrEx) return ExprError(); 3817 3818 if (IsType) { 3819 TypeSourceInfo *TInfo; 3820 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3821 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3822 } 3823 3824 Expr *ArgEx = (Expr *)TyOrEx; 3825 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3826 return Result; 3827 } 3828 3829 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3830 bool IsReal) { 3831 if (V.get()->isTypeDependent()) 3832 return S.Context.DependentTy; 3833 3834 // _Real and _Imag are only l-values for normal l-values. 3835 if (V.get()->getObjectKind() != OK_Ordinary) { 3836 V = S.DefaultLvalueConversion(V.get()); 3837 if (V.isInvalid()) 3838 return QualType(); 3839 } 3840 3841 // These operators return the element type of a complex type. 3842 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3843 return CT->getElementType(); 3844 3845 // Otherwise they pass through real integer and floating point types here. 3846 if (V.get()->getType()->isArithmeticType()) 3847 return V.get()->getType(); 3848 3849 // Test for placeholders. 3850 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3851 if (PR.isInvalid()) return QualType(); 3852 if (PR.get() != V.get()) { 3853 V = PR; 3854 return CheckRealImagOperand(S, V, Loc, IsReal); 3855 } 3856 3857 // Reject anything else. 3858 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3859 << (IsReal ? "__real" : "__imag"); 3860 return QualType(); 3861 } 3862 3863 3864 3865 ExprResult 3866 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3867 tok::TokenKind Kind, Expr *Input) { 3868 UnaryOperatorKind Opc; 3869 switch (Kind) { 3870 default: llvm_unreachable("Unknown unary op!"); 3871 case tok::plusplus: Opc = UO_PostInc; break; 3872 case tok::minusminus: Opc = UO_PostDec; break; 3873 } 3874 3875 // Since this might is a postfix expression, get rid of ParenListExprs. 3876 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3877 if (Result.isInvalid()) return ExprError(); 3878 Input = Result.get(); 3879 3880 return BuildUnaryOp(S, OpLoc, Opc, Input); 3881 } 3882 3883 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3884 /// 3885 /// \return true on error 3886 static bool checkArithmeticOnObjCPointer(Sema &S, 3887 SourceLocation opLoc, 3888 Expr *op) { 3889 assert(op->getType()->isObjCObjectPointerType()); 3890 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3891 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3892 return false; 3893 3894 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3895 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3896 << op->getSourceRange(); 3897 return true; 3898 } 3899 3900 ExprResult 3901 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3902 Expr *idx, SourceLocation rbLoc) { 3903 if (base && !base->getType().isNull() && 3904 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 3905 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 3906 /*Length=*/nullptr, rbLoc); 3907 3908 // Since this might be a postfix expression, get rid of ParenListExprs. 3909 if (isa<ParenListExpr>(base)) { 3910 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3911 if (result.isInvalid()) return ExprError(); 3912 base = result.get(); 3913 } 3914 3915 // Handle any non-overload placeholder types in the base and index 3916 // expressions. We can't handle overloads here because the other 3917 // operand might be an overloadable type, in which case the overload 3918 // resolution for the operator overload should get the first crack 3919 // at the overload. 3920 if (base->getType()->isNonOverloadPlaceholderType()) { 3921 ExprResult result = CheckPlaceholderExpr(base); 3922 if (result.isInvalid()) return ExprError(); 3923 base = result.get(); 3924 } 3925 if (idx->getType()->isNonOverloadPlaceholderType()) { 3926 ExprResult result = CheckPlaceholderExpr(idx); 3927 if (result.isInvalid()) return ExprError(); 3928 idx = result.get(); 3929 } 3930 3931 // Build an unanalyzed expression if either operand is type-dependent. 3932 if (getLangOpts().CPlusPlus && 3933 (base->isTypeDependent() || idx->isTypeDependent())) { 3934 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3935 VK_LValue, OK_Ordinary, rbLoc); 3936 } 3937 3938 // Use C++ overloaded-operator rules if either operand has record 3939 // type. The spec says to do this if either type is *overloadable*, 3940 // but enum types can't declare subscript operators or conversion 3941 // operators, so there's nothing interesting for overload resolution 3942 // to do if there aren't any record types involved. 3943 // 3944 // ObjC pointers have their own subscripting logic that is not tied 3945 // to overload resolution and so should not take this path. 3946 if (getLangOpts().CPlusPlus && 3947 (base->getType()->isRecordType() || 3948 (!base->getType()->isObjCObjectPointerType() && 3949 idx->getType()->isRecordType()))) { 3950 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3951 } 3952 3953 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3954 } 3955 3956 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 3957 Expr *LowerBound, 3958 SourceLocation ColonLoc, Expr *Length, 3959 SourceLocation RBLoc) { 3960 if (Base->getType()->isPlaceholderType() && 3961 !Base->getType()->isSpecificPlaceholderType( 3962 BuiltinType::OMPArraySection)) { 3963 ExprResult Result = CheckPlaceholderExpr(Base); 3964 if (Result.isInvalid()) 3965 return ExprError(); 3966 Base = Result.get(); 3967 } 3968 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 3969 ExprResult Result = CheckPlaceholderExpr(LowerBound); 3970 if (Result.isInvalid()) 3971 return ExprError(); 3972 LowerBound = Result.get(); 3973 } 3974 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 3975 ExprResult Result = CheckPlaceholderExpr(Length); 3976 if (Result.isInvalid()) 3977 return ExprError(); 3978 Length = Result.get(); 3979 } 3980 3981 // Build an unanalyzed expression if either operand is type-dependent. 3982 if (Base->isTypeDependent() || 3983 (LowerBound && 3984 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 3985 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 3986 return new (Context) 3987 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 3988 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 3989 } 3990 3991 // Perform default conversions. 3992 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 3993 QualType ResultTy; 3994 if (OriginalTy->isAnyPointerType()) { 3995 ResultTy = OriginalTy->getPointeeType(); 3996 } else if (OriginalTy->isArrayType()) { 3997 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 3998 } else { 3999 return ExprError( 4000 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4001 << Base->getSourceRange()); 4002 } 4003 // C99 6.5.2.1p1 4004 if (LowerBound) { 4005 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4006 LowerBound); 4007 if (Res.isInvalid()) 4008 return ExprError(Diag(LowerBound->getExprLoc(), 4009 diag::err_omp_typecheck_section_not_integer) 4010 << 0 << LowerBound->getSourceRange()); 4011 LowerBound = Res.get(); 4012 4013 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4014 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4015 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4016 << 0 << LowerBound->getSourceRange(); 4017 } 4018 if (Length) { 4019 auto Res = 4020 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4021 if (Res.isInvalid()) 4022 return ExprError(Diag(Length->getExprLoc(), 4023 diag::err_omp_typecheck_section_not_integer) 4024 << 1 << Length->getSourceRange()); 4025 Length = Res.get(); 4026 4027 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4028 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4029 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4030 << 1 << Length->getSourceRange(); 4031 } 4032 4033 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4034 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4035 // type. Note that functions are not objects, and that (in C99 parlance) 4036 // incomplete types are not object types. 4037 if (ResultTy->isFunctionType()) { 4038 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4039 << ResultTy << Base->getSourceRange(); 4040 return ExprError(); 4041 } 4042 4043 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4044 diag::err_omp_section_incomplete_type, Base)) 4045 return ExprError(); 4046 4047 if (LowerBound) { 4048 llvm::APSInt LowerBoundValue; 4049 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4050 // OpenMP 4.0, [2.4 Array Sections] 4051 // The lower-bound and length must evaluate to non-negative integers. 4052 if (LowerBoundValue.isNegative()) { 4053 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4054 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4055 << LowerBound->getSourceRange(); 4056 return ExprError(); 4057 } 4058 } 4059 } 4060 4061 if (Length) { 4062 llvm::APSInt LengthValue; 4063 if (Length->EvaluateAsInt(LengthValue, Context)) { 4064 // OpenMP 4.0, [2.4 Array Sections] 4065 // The lower-bound and length must evaluate to non-negative integers. 4066 if (LengthValue.isNegative()) { 4067 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4068 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4069 << Length->getSourceRange(); 4070 return ExprError(); 4071 } 4072 } 4073 } else if (ColonLoc.isValid() && 4074 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4075 !OriginalTy->isVariableArrayType()))) { 4076 // OpenMP 4.0, [2.4 Array Sections] 4077 // When the size of the array dimension is not known, the length must be 4078 // specified explicitly. 4079 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4080 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4081 return ExprError(); 4082 } 4083 4084 return new (Context) 4085 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4086 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4087 } 4088 4089 ExprResult 4090 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4091 Expr *Idx, SourceLocation RLoc) { 4092 Expr *LHSExp = Base; 4093 Expr *RHSExp = Idx; 4094 4095 // Perform default conversions. 4096 if (!LHSExp->getType()->getAs<VectorType>()) { 4097 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4098 if (Result.isInvalid()) 4099 return ExprError(); 4100 LHSExp = Result.get(); 4101 } 4102 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4103 if (Result.isInvalid()) 4104 return ExprError(); 4105 RHSExp = Result.get(); 4106 4107 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4108 ExprValueKind VK = VK_LValue; 4109 ExprObjectKind OK = OK_Ordinary; 4110 4111 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4112 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4113 // in the subscript position. As a result, we need to derive the array base 4114 // and index from the expression types. 4115 Expr *BaseExpr, *IndexExpr; 4116 QualType ResultType; 4117 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4118 BaseExpr = LHSExp; 4119 IndexExpr = RHSExp; 4120 ResultType = Context.DependentTy; 4121 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4122 BaseExpr = LHSExp; 4123 IndexExpr = RHSExp; 4124 ResultType = PTy->getPointeeType(); 4125 } else if (const ObjCObjectPointerType *PTy = 4126 LHSTy->getAs<ObjCObjectPointerType>()) { 4127 BaseExpr = LHSExp; 4128 IndexExpr = RHSExp; 4129 4130 // Use custom logic if this should be the pseudo-object subscript 4131 // expression. 4132 if (!LangOpts.isSubscriptPointerArithmetic()) 4133 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4134 nullptr); 4135 4136 ResultType = PTy->getPointeeType(); 4137 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4138 // Handle the uncommon case of "123[Ptr]". 4139 BaseExpr = RHSExp; 4140 IndexExpr = LHSExp; 4141 ResultType = PTy->getPointeeType(); 4142 } else if (const ObjCObjectPointerType *PTy = 4143 RHSTy->getAs<ObjCObjectPointerType>()) { 4144 // Handle the uncommon case of "123[Ptr]". 4145 BaseExpr = RHSExp; 4146 IndexExpr = LHSExp; 4147 ResultType = PTy->getPointeeType(); 4148 if (!LangOpts.isSubscriptPointerArithmetic()) { 4149 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4150 << ResultType << BaseExpr->getSourceRange(); 4151 return ExprError(); 4152 } 4153 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4154 BaseExpr = LHSExp; // vectors: V[123] 4155 IndexExpr = RHSExp; 4156 VK = LHSExp->getValueKind(); 4157 if (VK != VK_RValue) 4158 OK = OK_VectorComponent; 4159 4160 // FIXME: need to deal with const... 4161 ResultType = VTy->getElementType(); 4162 } else if (LHSTy->isArrayType()) { 4163 // If we see an array that wasn't promoted by 4164 // DefaultFunctionArrayLvalueConversion, it must be an array that 4165 // wasn't promoted because of the C90 rule that doesn't 4166 // allow promoting non-lvalue arrays. Warn, then 4167 // force the promotion here. 4168 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4169 LHSExp->getSourceRange(); 4170 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4171 CK_ArrayToPointerDecay).get(); 4172 LHSTy = LHSExp->getType(); 4173 4174 BaseExpr = LHSExp; 4175 IndexExpr = RHSExp; 4176 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4177 } else if (RHSTy->isArrayType()) { 4178 // Same as previous, except for 123[f().a] case 4179 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4180 RHSExp->getSourceRange(); 4181 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4182 CK_ArrayToPointerDecay).get(); 4183 RHSTy = RHSExp->getType(); 4184 4185 BaseExpr = RHSExp; 4186 IndexExpr = LHSExp; 4187 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4188 } else { 4189 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4190 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4191 } 4192 // C99 6.5.2.1p1 4193 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4194 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4195 << IndexExpr->getSourceRange()); 4196 4197 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4198 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4199 && !IndexExpr->isTypeDependent()) 4200 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4201 4202 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4203 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4204 // type. Note that Functions are not objects, and that (in C99 parlance) 4205 // incomplete types are not object types. 4206 if (ResultType->isFunctionType()) { 4207 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4208 << ResultType << BaseExpr->getSourceRange(); 4209 return ExprError(); 4210 } 4211 4212 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4213 // GNU extension: subscripting on pointer to void 4214 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4215 << BaseExpr->getSourceRange(); 4216 4217 // C forbids expressions of unqualified void type from being l-values. 4218 // See IsCForbiddenLValueType. 4219 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4220 } else if (!ResultType->isDependentType() && 4221 RequireCompleteType(LLoc, ResultType, 4222 diag::err_subscript_incomplete_type, BaseExpr)) 4223 return ExprError(); 4224 4225 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4226 !ResultType.isCForbiddenLValueType()); 4227 4228 return new (Context) 4229 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4230 } 4231 4232 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4233 FunctionDecl *FD, 4234 ParmVarDecl *Param) { 4235 if (Param->hasUnparsedDefaultArg()) { 4236 Diag(CallLoc, 4237 diag::err_use_of_default_argument_to_function_declared_later) << 4238 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4239 Diag(UnparsedDefaultArgLocs[Param], 4240 diag::note_default_argument_declared_here); 4241 return ExprError(); 4242 } 4243 4244 if (Param->hasUninstantiatedDefaultArg()) { 4245 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4246 4247 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4248 Param); 4249 4250 // Instantiate the expression. 4251 MultiLevelTemplateArgumentList MutiLevelArgList 4252 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4253 4254 InstantiatingTemplate Inst(*this, CallLoc, Param, 4255 MutiLevelArgList.getInnermost()); 4256 if (Inst.isInvalid()) 4257 return ExprError(); 4258 4259 ExprResult Result; 4260 { 4261 // C++ [dcl.fct.default]p5: 4262 // The names in the [default argument] expression are bound, and 4263 // the semantic constraints are checked, at the point where the 4264 // default argument expression appears. 4265 ContextRAII SavedContext(*this, FD); 4266 LocalInstantiationScope Local(*this); 4267 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4268 } 4269 if (Result.isInvalid()) 4270 return ExprError(); 4271 4272 // Check the expression as an initializer for the parameter. 4273 InitializedEntity Entity 4274 = InitializedEntity::InitializeParameter(Context, Param); 4275 InitializationKind Kind 4276 = InitializationKind::CreateCopy(Param->getLocation(), 4277 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4278 Expr *ResultE = Result.getAs<Expr>(); 4279 4280 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4281 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4282 if (Result.isInvalid()) 4283 return ExprError(); 4284 4285 Expr *Arg = Result.getAs<Expr>(); 4286 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4287 // Build the default argument expression. 4288 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4289 } 4290 4291 // If the default expression creates temporaries, we need to 4292 // push them to the current stack of expression temporaries so they'll 4293 // be properly destroyed. 4294 // FIXME: We should really be rebuilding the default argument with new 4295 // bound temporaries; see the comment in PR5810. 4296 // We don't need to do that with block decls, though, because 4297 // blocks in default argument expression can never capture anything. 4298 if (isa<ExprWithCleanups>(Param->getInit())) { 4299 // Set the "needs cleanups" bit regardless of whether there are 4300 // any explicit objects. 4301 ExprNeedsCleanups = true; 4302 4303 // Append all the objects to the cleanup list. Right now, this 4304 // should always be a no-op, because blocks in default argument 4305 // expressions should never be able to capture anything. 4306 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4307 "default argument expression has capturing blocks?"); 4308 } 4309 4310 // We already type-checked the argument, so we know it works. 4311 // Just mark all of the declarations in this potentially-evaluated expression 4312 // as being "referenced". 4313 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4314 /*SkipLocalVariables=*/true); 4315 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4316 } 4317 4318 4319 Sema::VariadicCallType 4320 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4321 Expr *Fn) { 4322 if (Proto && Proto->isVariadic()) { 4323 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4324 return VariadicConstructor; 4325 else if (Fn && Fn->getType()->isBlockPointerType()) 4326 return VariadicBlock; 4327 else if (FDecl) { 4328 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4329 if (Method->isInstance()) 4330 return VariadicMethod; 4331 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4332 return VariadicMethod; 4333 return VariadicFunction; 4334 } 4335 return VariadicDoesNotApply; 4336 } 4337 4338 namespace { 4339 class FunctionCallCCC : public FunctionCallFilterCCC { 4340 public: 4341 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4342 unsigned NumArgs, MemberExpr *ME) 4343 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4344 FunctionName(FuncName) {} 4345 4346 bool ValidateCandidate(const TypoCorrection &candidate) override { 4347 if (!candidate.getCorrectionSpecifier() || 4348 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4349 return false; 4350 } 4351 4352 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4353 } 4354 4355 private: 4356 const IdentifierInfo *const FunctionName; 4357 }; 4358 } 4359 4360 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4361 FunctionDecl *FDecl, 4362 ArrayRef<Expr *> Args) { 4363 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4364 DeclarationName FuncName = FDecl->getDeclName(); 4365 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4366 4367 if (TypoCorrection Corrected = S.CorrectTypo( 4368 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4369 S.getScopeForContext(S.CurContext), nullptr, 4370 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4371 Args.size(), ME), 4372 Sema::CTK_ErrorRecovery)) { 4373 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4374 if (Corrected.isOverloaded()) { 4375 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4376 OverloadCandidateSet::iterator Best; 4377 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4378 CDEnd = Corrected.end(); 4379 CD != CDEnd; ++CD) { 4380 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4381 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4382 OCS); 4383 } 4384 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4385 case OR_Success: 4386 ND = Best->Function; 4387 Corrected.setCorrectionDecl(ND); 4388 break; 4389 default: 4390 break; 4391 } 4392 } 4393 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4394 return Corrected; 4395 } 4396 } 4397 } 4398 return TypoCorrection(); 4399 } 4400 4401 /// ConvertArgumentsForCall - Converts the arguments specified in 4402 /// Args/NumArgs to the parameter types of the function FDecl with 4403 /// function prototype Proto. Call is the call expression itself, and 4404 /// Fn is the function expression. For a C++ member function, this 4405 /// routine does not attempt to convert the object argument. Returns 4406 /// true if the call is ill-formed. 4407 bool 4408 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4409 FunctionDecl *FDecl, 4410 const FunctionProtoType *Proto, 4411 ArrayRef<Expr *> Args, 4412 SourceLocation RParenLoc, 4413 bool IsExecConfig) { 4414 // Bail out early if calling a builtin with custom typechecking. 4415 if (FDecl) 4416 if (unsigned ID = FDecl->getBuiltinID()) 4417 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4418 return false; 4419 4420 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4421 // assignment, to the types of the corresponding parameter, ... 4422 unsigned NumParams = Proto->getNumParams(); 4423 bool Invalid = false; 4424 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4425 unsigned FnKind = Fn->getType()->isBlockPointerType() 4426 ? 1 /* block */ 4427 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4428 : 0 /* function */); 4429 4430 // If too few arguments are available (and we don't have default 4431 // arguments for the remaining parameters), don't make the call. 4432 if (Args.size() < NumParams) { 4433 if (Args.size() < MinArgs) { 4434 TypoCorrection TC; 4435 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4436 unsigned diag_id = 4437 MinArgs == NumParams && !Proto->isVariadic() 4438 ? diag::err_typecheck_call_too_few_args_suggest 4439 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4440 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4441 << static_cast<unsigned>(Args.size()) 4442 << TC.getCorrectionRange()); 4443 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4444 Diag(RParenLoc, 4445 MinArgs == NumParams && !Proto->isVariadic() 4446 ? diag::err_typecheck_call_too_few_args_one 4447 : diag::err_typecheck_call_too_few_args_at_least_one) 4448 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4449 else 4450 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4451 ? diag::err_typecheck_call_too_few_args 4452 : diag::err_typecheck_call_too_few_args_at_least) 4453 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4454 << Fn->getSourceRange(); 4455 4456 // Emit the location of the prototype. 4457 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4458 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4459 << FDecl; 4460 4461 return true; 4462 } 4463 Call->setNumArgs(Context, NumParams); 4464 } 4465 4466 // If too many are passed and not variadic, error on the extras and drop 4467 // them. 4468 if (Args.size() > NumParams) { 4469 if (!Proto->isVariadic()) { 4470 TypoCorrection TC; 4471 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4472 unsigned diag_id = 4473 MinArgs == NumParams && !Proto->isVariadic() 4474 ? diag::err_typecheck_call_too_many_args_suggest 4475 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4476 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4477 << static_cast<unsigned>(Args.size()) 4478 << TC.getCorrectionRange()); 4479 } else if (NumParams == 1 && FDecl && 4480 FDecl->getParamDecl(0)->getDeclName()) 4481 Diag(Args[NumParams]->getLocStart(), 4482 MinArgs == NumParams 4483 ? diag::err_typecheck_call_too_many_args_one 4484 : diag::err_typecheck_call_too_many_args_at_most_one) 4485 << FnKind << FDecl->getParamDecl(0) 4486 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4487 << SourceRange(Args[NumParams]->getLocStart(), 4488 Args.back()->getLocEnd()); 4489 else 4490 Diag(Args[NumParams]->getLocStart(), 4491 MinArgs == NumParams 4492 ? diag::err_typecheck_call_too_many_args 4493 : diag::err_typecheck_call_too_many_args_at_most) 4494 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4495 << Fn->getSourceRange() 4496 << SourceRange(Args[NumParams]->getLocStart(), 4497 Args.back()->getLocEnd()); 4498 4499 // Emit the location of the prototype. 4500 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4501 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4502 << FDecl; 4503 4504 // This deletes the extra arguments. 4505 Call->setNumArgs(Context, NumParams); 4506 return true; 4507 } 4508 } 4509 SmallVector<Expr *, 8> AllArgs; 4510 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4511 4512 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4513 Proto, 0, Args, AllArgs, CallType); 4514 if (Invalid) 4515 return true; 4516 unsigned TotalNumArgs = AllArgs.size(); 4517 for (unsigned i = 0; i < TotalNumArgs; ++i) 4518 Call->setArg(i, AllArgs[i]); 4519 4520 return false; 4521 } 4522 4523 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4524 const FunctionProtoType *Proto, 4525 unsigned FirstParam, ArrayRef<Expr *> Args, 4526 SmallVectorImpl<Expr *> &AllArgs, 4527 VariadicCallType CallType, bool AllowExplicit, 4528 bool IsListInitialization) { 4529 unsigned NumParams = Proto->getNumParams(); 4530 bool Invalid = false; 4531 unsigned ArgIx = 0; 4532 // Continue to check argument types (even if we have too few/many args). 4533 for (unsigned i = FirstParam; i < NumParams; i++) { 4534 QualType ProtoArgType = Proto->getParamType(i); 4535 4536 Expr *Arg; 4537 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4538 if (ArgIx < Args.size()) { 4539 Arg = Args[ArgIx++]; 4540 4541 if (RequireCompleteType(Arg->getLocStart(), 4542 ProtoArgType, 4543 diag::err_call_incomplete_argument, Arg)) 4544 return true; 4545 4546 // Strip the unbridged-cast placeholder expression off, if applicable. 4547 bool CFAudited = false; 4548 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4549 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4550 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4551 Arg = stripARCUnbridgedCast(Arg); 4552 else if (getLangOpts().ObjCAutoRefCount && 4553 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4554 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4555 CFAudited = true; 4556 4557 InitializedEntity Entity = 4558 Param ? InitializedEntity::InitializeParameter(Context, Param, 4559 ProtoArgType) 4560 : InitializedEntity::InitializeParameter( 4561 Context, ProtoArgType, Proto->isParamConsumed(i)); 4562 4563 // Remember that parameter belongs to a CF audited API. 4564 if (CFAudited) 4565 Entity.setParameterCFAudited(); 4566 4567 ExprResult ArgE = PerformCopyInitialization( 4568 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4569 if (ArgE.isInvalid()) 4570 return true; 4571 4572 Arg = ArgE.getAs<Expr>(); 4573 } else { 4574 assert(Param && "can't use default arguments without a known callee"); 4575 4576 ExprResult ArgExpr = 4577 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4578 if (ArgExpr.isInvalid()) 4579 return true; 4580 4581 Arg = ArgExpr.getAs<Expr>(); 4582 } 4583 4584 // Check for array bounds violations for each argument to the call. This 4585 // check only triggers warnings when the argument isn't a more complex Expr 4586 // with its own checking, such as a BinaryOperator. 4587 CheckArrayAccess(Arg); 4588 4589 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4590 CheckStaticArrayArgument(CallLoc, Param, Arg); 4591 4592 AllArgs.push_back(Arg); 4593 } 4594 4595 // If this is a variadic call, handle args passed through "...". 4596 if (CallType != VariadicDoesNotApply) { 4597 // Assume that extern "C" functions with variadic arguments that 4598 // return __unknown_anytype aren't *really* variadic. 4599 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4600 FDecl->isExternC()) { 4601 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4602 QualType paramType; // ignored 4603 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4604 Invalid |= arg.isInvalid(); 4605 AllArgs.push_back(arg.get()); 4606 } 4607 4608 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4609 } else { 4610 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4611 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4612 FDecl); 4613 Invalid |= Arg.isInvalid(); 4614 AllArgs.push_back(Arg.get()); 4615 } 4616 } 4617 4618 // Check for array bounds violations. 4619 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4620 CheckArrayAccess(Args[i]); 4621 } 4622 return Invalid; 4623 } 4624 4625 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4626 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4627 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4628 TL = DTL.getOriginalLoc(); 4629 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4630 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4631 << ATL.getLocalSourceRange(); 4632 } 4633 4634 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4635 /// array parameter, check that it is non-null, and that if it is formed by 4636 /// array-to-pointer decay, the underlying array is sufficiently large. 4637 /// 4638 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4639 /// array type derivation, then for each call to the function, the value of the 4640 /// corresponding actual argument shall provide access to the first element of 4641 /// an array with at least as many elements as specified by the size expression. 4642 void 4643 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4644 ParmVarDecl *Param, 4645 const Expr *ArgExpr) { 4646 // Static array parameters are not supported in C++. 4647 if (!Param || getLangOpts().CPlusPlus) 4648 return; 4649 4650 QualType OrigTy = Param->getOriginalType(); 4651 4652 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4653 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4654 return; 4655 4656 if (ArgExpr->isNullPointerConstant(Context, 4657 Expr::NPC_NeverValueDependent)) { 4658 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4659 DiagnoseCalleeStaticArrayParam(*this, Param); 4660 return; 4661 } 4662 4663 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4664 if (!CAT) 4665 return; 4666 4667 const ConstantArrayType *ArgCAT = 4668 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4669 if (!ArgCAT) 4670 return; 4671 4672 if (ArgCAT->getSize().ult(CAT->getSize())) { 4673 Diag(CallLoc, diag::warn_static_array_too_small) 4674 << ArgExpr->getSourceRange() 4675 << (unsigned) ArgCAT->getSize().getZExtValue() 4676 << (unsigned) CAT->getSize().getZExtValue(); 4677 DiagnoseCalleeStaticArrayParam(*this, Param); 4678 } 4679 } 4680 4681 /// Given a function expression of unknown-any type, try to rebuild it 4682 /// to have a function type. 4683 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4684 4685 /// Is the given type a placeholder that we need to lower out 4686 /// immediately during argument processing? 4687 static bool isPlaceholderToRemoveAsArg(QualType type) { 4688 // Placeholders are never sugared. 4689 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4690 if (!placeholder) return false; 4691 4692 switch (placeholder->getKind()) { 4693 // Ignore all the non-placeholder types. 4694 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4695 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4696 #include "clang/AST/BuiltinTypes.def" 4697 return false; 4698 4699 // We cannot lower out overload sets; they might validly be resolved 4700 // by the call machinery. 4701 case BuiltinType::Overload: 4702 return false; 4703 4704 // Unbridged casts in ARC can be handled in some call positions and 4705 // should be left in place. 4706 case BuiltinType::ARCUnbridgedCast: 4707 return false; 4708 4709 // Pseudo-objects should be converted as soon as possible. 4710 case BuiltinType::PseudoObject: 4711 return true; 4712 4713 // The debugger mode could theoretically but currently does not try 4714 // to resolve unknown-typed arguments based on known parameter types. 4715 case BuiltinType::UnknownAny: 4716 return true; 4717 4718 // These are always invalid as call arguments and should be reported. 4719 case BuiltinType::BoundMember: 4720 case BuiltinType::BuiltinFn: 4721 case BuiltinType::OMPArraySection: 4722 return true; 4723 4724 } 4725 llvm_unreachable("bad builtin type kind"); 4726 } 4727 4728 /// Check an argument list for placeholders that we won't try to 4729 /// handle later. 4730 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4731 // Apply this processing to all the arguments at once instead of 4732 // dying at the first failure. 4733 bool hasInvalid = false; 4734 for (size_t i = 0, e = args.size(); i != e; i++) { 4735 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4736 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4737 if (result.isInvalid()) hasInvalid = true; 4738 else args[i] = result.get(); 4739 } else if (hasInvalid) { 4740 (void)S.CorrectDelayedTyposInExpr(args[i]); 4741 } 4742 } 4743 return hasInvalid; 4744 } 4745 4746 /// If a builtin function has a pointer argument with no explicit address 4747 /// space, than it should be able to accept a pointer to any address 4748 /// space as input. In order to do this, we need to replace the 4749 /// standard builtin declaration with one that uses the same address space 4750 /// as the call. 4751 /// 4752 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4753 /// it does not contain any pointer arguments without 4754 /// an address space qualifer. Otherwise the rewritten 4755 /// FunctionDecl is returned. 4756 /// TODO: Handle pointer return types. 4757 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4758 const FunctionDecl *FDecl, 4759 MultiExprArg ArgExprs) { 4760 4761 QualType DeclType = FDecl->getType(); 4762 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4763 4764 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4765 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4766 return nullptr; 4767 4768 bool NeedsNewDecl = false; 4769 unsigned i = 0; 4770 SmallVector<QualType, 8> OverloadParams; 4771 4772 for (QualType ParamType : FT->param_types()) { 4773 4774 // Convert array arguments to pointer to simplify type lookup. 4775 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4776 QualType ArgType = Arg->getType(); 4777 if (!ParamType->isPointerType() || 4778 ParamType.getQualifiers().hasAddressSpace() || 4779 !ArgType->isPointerType() || 4780 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4781 OverloadParams.push_back(ParamType); 4782 continue; 4783 } 4784 4785 NeedsNewDecl = true; 4786 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 4787 4788 QualType PointeeType = ParamType->getPointeeType(); 4789 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 4790 OverloadParams.push_back(Context.getPointerType(PointeeType)); 4791 } 4792 4793 if (!NeedsNewDecl) 4794 return nullptr; 4795 4796 FunctionProtoType::ExtProtoInfo EPI; 4797 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 4798 OverloadParams, EPI); 4799 DeclContext *Parent = Context.getTranslationUnitDecl(); 4800 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 4801 FDecl->getLocation(), 4802 FDecl->getLocation(), 4803 FDecl->getIdentifier(), 4804 OverloadTy, 4805 /*TInfo=*/nullptr, 4806 SC_Extern, false, 4807 /*hasPrototype=*/true); 4808 SmallVector<ParmVarDecl*, 16> Params; 4809 FT = cast<FunctionProtoType>(OverloadTy); 4810 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 4811 QualType ParamType = FT->getParamType(i); 4812 ParmVarDecl *Parm = 4813 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 4814 SourceLocation(), nullptr, ParamType, 4815 /*TInfo=*/nullptr, SC_None, nullptr); 4816 Parm->setScopeInfo(0, i); 4817 Params.push_back(Parm); 4818 } 4819 OverloadDecl->setParams(Params); 4820 return OverloadDecl; 4821 } 4822 4823 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4824 /// This provides the location of the left/right parens and a list of comma 4825 /// locations. 4826 ExprResult 4827 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4828 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4829 Expr *ExecConfig, bool IsExecConfig) { 4830 // Since this might be a postfix expression, get rid of ParenListExprs. 4831 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4832 if (Result.isInvalid()) return ExprError(); 4833 Fn = Result.get(); 4834 4835 if (checkArgsForPlaceholders(*this, ArgExprs)) 4836 return ExprError(); 4837 4838 if (getLangOpts().CPlusPlus) { 4839 // If this is a pseudo-destructor expression, build the call immediately. 4840 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4841 if (!ArgExprs.empty()) { 4842 // Pseudo-destructor calls should not have any arguments. 4843 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4844 << FixItHint::CreateRemoval( 4845 SourceRange(ArgExprs.front()->getLocStart(), 4846 ArgExprs.back()->getLocEnd())); 4847 } 4848 4849 return new (Context) 4850 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4851 } 4852 if (Fn->getType() == Context.PseudoObjectTy) { 4853 ExprResult result = CheckPlaceholderExpr(Fn); 4854 if (result.isInvalid()) return ExprError(); 4855 Fn = result.get(); 4856 } 4857 4858 // Determine whether this is a dependent call inside a C++ template, 4859 // in which case we won't do any semantic analysis now. 4860 // FIXME: Will need to cache the results of name lookup (including ADL) in 4861 // Fn. 4862 bool Dependent = false; 4863 if (Fn->isTypeDependent()) 4864 Dependent = true; 4865 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4866 Dependent = true; 4867 4868 if (Dependent) { 4869 if (ExecConfig) { 4870 return new (Context) CUDAKernelCallExpr( 4871 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4872 Context.DependentTy, VK_RValue, RParenLoc); 4873 } else { 4874 return new (Context) CallExpr( 4875 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4876 } 4877 } 4878 4879 // Determine whether this is a call to an object (C++ [over.call.object]). 4880 if (Fn->getType()->isRecordType()) 4881 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4882 RParenLoc); 4883 4884 if (Fn->getType() == Context.UnknownAnyTy) { 4885 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4886 if (result.isInvalid()) return ExprError(); 4887 Fn = result.get(); 4888 } 4889 4890 if (Fn->getType() == Context.BoundMemberTy) { 4891 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4892 } 4893 } 4894 4895 // Check for overloaded calls. This can happen even in C due to extensions. 4896 if (Fn->getType() == Context.OverloadTy) { 4897 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4898 4899 // We aren't supposed to apply this logic for if there's an '&' involved. 4900 if (!find.HasFormOfMemberPointer) { 4901 OverloadExpr *ovl = find.Expression; 4902 if (isa<UnresolvedLookupExpr>(ovl)) { 4903 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4904 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4905 RParenLoc, ExecConfig); 4906 } else { 4907 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4908 RParenLoc); 4909 } 4910 } 4911 } 4912 4913 // If we're directly calling a function, get the appropriate declaration. 4914 if (Fn->getType() == Context.UnknownAnyTy) { 4915 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4916 if (result.isInvalid()) return ExprError(); 4917 Fn = result.get(); 4918 } 4919 4920 Expr *NakedFn = Fn->IgnoreParens(); 4921 4922 NamedDecl *NDecl = nullptr; 4923 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4924 if (UnOp->getOpcode() == UO_AddrOf) 4925 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4926 4927 if (isa<DeclRefExpr>(NakedFn)) { 4928 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4929 4930 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 4931 if (FDecl && FDecl->getBuiltinID()) { 4932 // Rewrite the function decl for this builtin by replacing paramaters 4933 // with no explicit address space with the address space of the arguments 4934 // in ArgExprs. 4935 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 4936 NDecl = FDecl; 4937 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 4938 SourceLocation(), FDecl, false, 4939 SourceLocation(), FDecl->getType(), 4940 Fn->getValueKind(), FDecl); 4941 } 4942 } 4943 } else if (isa<MemberExpr>(NakedFn)) 4944 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4945 4946 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4947 if (FD->hasAttr<EnableIfAttr>()) { 4948 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4949 Diag(Fn->getLocStart(), 4950 isa<CXXMethodDecl>(FD) ? 4951 diag::err_ovl_no_viable_member_function_in_call : 4952 diag::err_ovl_no_viable_function_in_call) 4953 << FD << FD->getSourceRange(); 4954 Diag(FD->getLocation(), 4955 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4956 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4957 } 4958 } 4959 } 4960 4961 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4962 ExecConfig, IsExecConfig); 4963 } 4964 4965 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4966 /// 4967 /// __builtin_astype( value, dst type ) 4968 /// 4969 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4970 SourceLocation BuiltinLoc, 4971 SourceLocation RParenLoc) { 4972 ExprValueKind VK = VK_RValue; 4973 ExprObjectKind OK = OK_Ordinary; 4974 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4975 QualType SrcTy = E->getType(); 4976 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4977 return ExprError(Diag(BuiltinLoc, 4978 diag::err_invalid_astype_of_different_size) 4979 << DstTy 4980 << SrcTy 4981 << E->getSourceRange()); 4982 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4983 } 4984 4985 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4986 /// provided arguments. 4987 /// 4988 /// __builtin_convertvector( value, dst type ) 4989 /// 4990 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4991 SourceLocation BuiltinLoc, 4992 SourceLocation RParenLoc) { 4993 TypeSourceInfo *TInfo; 4994 GetTypeFromParser(ParsedDestTy, &TInfo); 4995 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4996 } 4997 4998 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4999 /// i.e. an expression not of \p OverloadTy. The expression should 5000 /// unary-convert to an expression of function-pointer or 5001 /// block-pointer type. 5002 /// 5003 /// \param NDecl the declaration being called, if available 5004 ExprResult 5005 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5006 SourceLocation LParenLoc, 5007 ArrayRef<Expr *> Args, 5008 SourceLocation RParenLoc, 5009 Expr *Config, bool IsExecConfig) { 5010 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5011 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5012 5013 // Promote the function operand. 5014 // We special-case function promotion here because we only allow promoting 5015 // builtin functions to function pointers in the callee of a call. 5016 ExprResult Result; 5017 if (BuiltinID && 5018 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5019 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5020 CK_BuiltinFnToFnPtr).get(); 5021 } else { 5022 Result = CallExprUnaryConversions(Fn); 5023 } 5024 if (Result.isInvalid()) 5025 return ExprError(); 5026 Fn = Result.get(); 5027 5028 // Make the call expr early, before semantic checks. This guarantees cleanup 5029 // of arguments and function on error. 5030 CallExpr *TheCall; 5031 if (Config) 5032 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5033 cast<CallExpr>(Config), Args, 5034 Context.BoolTy, VK_RValue, 5035 RParenLoc); 5036 else 5037 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5038 VK_RValue, RParenLoc); 5039 5040 if (!getLangOpts().CPlusPlus) { 5041 // C cannot always handle TypoExpr nodes in builtin calls and direct 5042 // function calls as their argument checking don't necessarily handle 5043 // dependent types properly, so make sure any TypoExprs have been 5044 // dealt with. 5045 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5046 if (!Result.isUsable()) return ExprError(); 5047 TheCall = dyn_cast<CallExpr>(Result.get()); 5048 if (!TheCall) return Result; 5049 Args = ArrayRef<Expr *>(TheCall->getArgs(), TheCall->getNumArgs()); 5050 } 5051 5052 // Bail out early if calling a builtin with custom typechecking. 5053 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5054 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5055 5056 retry: 5057 const FunctionType *FuncT; 5058 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5059 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5060 // have type pointer to function". 5061 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5062 if (!FuncT) 5063 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5064 << Fn->getType() << Fn->getSourceRange()); 5065 } else if (const BlockPointerType *BPT = 5066 Fn->getType()->getAs<BlockPointerType>()) { 5067 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5068 } else { 5069 // Handle calls to expressions of unknown-any type. 5070 if (Fn->getType() == Context.UnknownAnyTy) { 5071 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5072 if (rewrite.isInvalid()) return ExprError(); 5073 Fn = rewrite.get(); 5074 TheCall->setCallee(Fn); 5075 goto retry; 5076 } 5077 5078 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5079 << Fn->getType() << Fn->getSourceRange()); 5080 } 5081 5082 if (getLangOpts().CUDA) { 5083 if (Config) { 5084 // CUDA: Kernel calls must be to global functions 5085 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5086 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5087 << FDecl->getName() << Fn->getSourceRange()); 5088 5089 // CUDA: Kernel function must have 'void' return type 5090 if (!FuncT->getReturnType()->isVoidType()) 5091 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5092 << Fn->getType() << Fn->getSourceRange()); 5093 } else { 5094 // CUDA: Calls to global functions must be configured 5095 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5096 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5097 << FDecl->getName() << Fn->getSourceRange()); 5098 } 5099 } 5100 5101 // Check for a valid return type 5102 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5103 FDecl)) 5104 return ExprError(); 5105 5106 // We know the result type of the call, set it. 5107 TheCall->setType(FuncT->getCallResultType(Context)); 5108 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5109 5110 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5111 if (Proto) { 5112 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5113 IsExecConfig)) 5114 return ExprError(); 5115 } else { 5116 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5117 5118 if (FDecl) { 5119 // Check if we have too few/too many template arguments, based 5120 // on our knowledge of the function definition. 5121 const FunctionDecl *Def = nullptr; 5122 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5123 Proto = Def->getType()->getAs<FunctionProtoType>(); 5124 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5125 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5126 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5127 } 5128 5129 // If the function we're calling isn't a function prototype, but we have 5130 // a function prototype from a prior declaratiom, use that prototype. 5131 if (!FDecl->hasPrototype()) 5132 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5133 } 5134 5135 // Promote the arguments (C99 6.5.2.2p6). 5136 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5137 Expr *Arg = Args[i]; 5138 5139 if (Proto && i < Proto->getNumParams()) { 5140 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5141 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5142 ExprResult ArgE = 5143 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5144 if (ArgE.isInvalid()) 5145 return true; 5146 5147 Arg = ArgE.getAs<Expr>(); 5148 5149 } else { 5150 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5151 5152 if (ArgE.isInvalid()) 5153 return true; 5154 5155 Arg = ArgE.getAs<Expr>(); 5156 } 5157 5158 if (RequireCompleteType(Arg->getLocStart(), 5159 Arg->getType(), 5160 diag::err_call_incomplete_argument, Arg)) 5161 return ExprError(); 5162 5163 TheCall->setArg(i, Arg); 5164 } 5165 } 5166 5167 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5168 if (!Method->isStatic()) 5169 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5170 << Fn->getSourceRange()); 5171 5172 // Check for sentinels 5173 if (NDecl) 5174 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5175 5176 // Do special checking on direct calls to functions. 5177 if (FDecl) { 5178 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5179 return ExprError(); 5180 5181 if (BuiltinID) 5182 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5183 } else if (NDecl) { 5184 if (CheckPointerCall(NDecl, TheCall, Proto)) 5185 return ExprError(); 5186 } else { 5187 if (CheckOtherCall(TheCall, Proto)) 5188 return ExprError(); 5189 } 5190 5191 return MaybeBindToTemporary(TheCall); 5192 } 5193 5194 ExprResult 5195 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5196 SourceLocation RParenLoc, Expr *InitExpr) { 5197 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5198 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5199 5200 TypeSourceInfo *TInfo; 5201 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5202 if (!TInfo) 5203 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5204 5205 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5206 } 5207 5208 ExprResult 5209 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5210 SourceLocation RParenLoc, Expr *LiteralExpr) { 5211 QualType literalType = TInfo->getType(); 5212 5213 if (literalType->isArrayType()) { 5214 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5215 diag::err_illegal_decl_array_incomplete_type, 5216 SourceRange(LParenLoc, 5217 LiteralExpr->getSourceRange().getEnd()))) 5218 return ExprError(); 5219 if (literalType->isVariableArrayType()) 5220 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5221 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5222 } else if (!literalType->isDependentType() && 5223 RequireCompleteType(LParenLoc, literalType, 5224 diag::err_typecheck_decl_incomplete_type, 5225 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5226 return ExprError(); 5227 5228 InitializedEntity Entity 5229 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5230 InitializationKind Kind 5231 = InitializationKind::CreateCStyleCast(LParenLoc, 5232 SourceRange(LParenLoc, RParenLoc), 5233 /*InitList=*/true); 5234 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5235 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5236 &literalType); 5237 if (Result.isInvalid()) 5238 return ExprError(); 5239 LiteralExpr = Result.get(); 5240 5241 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5242 if (isFileScope && 5243 !LiteralExpr->isTypeDependent() && 5244 !LiteralExpr->isValueDependent() && 5245 !literalType->isDependentType()) { // 6.5.2.5p3 5246 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5247 return ExprError(); 5248 } 5249 5250 // In C, compound literals are l-values for some reason. 5251 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5252 5253 return MaybeBindToTemporary( 5254 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5255 VK, LiteralExpr, isFileScope)); 5256 } 5257 5258 ExprResult 5259 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5260 SourceLocation RBraceLoc) { 5261 // Immediately handle non-overload placeholders. Overloads can be 5262 // resolved contextually, but everything else here can't. 5263 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5264 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5265 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5266 5267 // Ignore failures; dropping the entire initializer list because 5268 // of one failure would be terrible for indexing/etc. 5269 if (result.isInvalid()) continue; 5270 5271 InitArgList[I] = result.get(); 5272 } 5273 } 5274 5275 // Semantic analysis for initializers is done by ActOnDeclarator() and 5276 // CheckInitializer() - it requires knowledge of the object being intialized. 5277 5278 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5279 RBraceLoc); 5280 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5281 return E; 5282 } 5283 5284 /// Do an explicit extend of the given block pointer if we're in ARC. 5285 void Sema::maybeExtendBlockObject(ExprResult &E) { 5286 assert(E.get()->getType()->isBlockPointerType()); 5287 assert(E.get()->isRValue()); 5288 5289 // Only do this in an r-value context. 5290 if (!getLangOpts().ObjCAutoRefCount) return; 5291 5292 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5293 CK_ARCExtendBlockObject, E.get(), 5294 /*base path*/ nullptr, VK_RValue); 5295 ExprNeedsCleanups = true; 5296 } 5297 5298 /// Prepare a conversion of the given expression to an ObjC object 5299 /// pointer type. 5300 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5301 QualType type = E.get()->getType(); 5302 if (type->isObjCObjectPointerType()) { 5303 return CK_BitCast; 5304 } else if (type->isBlockPointerType()) { 5305 maybeExtendBlockObject(E); 5306 return CK_BlockPointerToObjCPointerCast; 5307 } else { 5308 assert(type->isPointerType()); 5309 return CK_CPointerToObjCPointerCast; 5310 } 5311 } 5312 5313 /// Prepares for a scalar cast, performing all the necessary stages 5314 /// except the final cast and returning the kind required. 5315 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5316 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5317 // Also, callers should have filtered out the invalid cases with 5318 // pointers. Everything else should be possible. 5319 5320 QualType SrcTy = Src.get()->getType(); 5321 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5322 return CK_NoOp; 5323 5324 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5325 case Type::STK_MemberPointer: 5326 llvm_unreachable("member pointer type in C"); 5327 5328 case Type::STK_CPointer: 5329 case Type::STK_BlockPointer: 5330 case Type::STK_ObjCObjectPointer: 5331 switch (DestTy->getScalarTypeKind()) { 5332 case Type::STK_CPointer: { 5333 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5334 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5335 if (SrcAS != DestAS) 5336 return CK_AddressSpaceConversion; 5337 return CK_BitCast; 5338 } 5339 case Type::STK_BlockPointer: 5340 return (SrcKind == Type::STK_BlockPointer 5341 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5342 case Type::STK_ObjCObjectPointer: 5343 if (SrcKind == Type::STK_ObjCObjectPointer) 5344 return CK_BitCast; 5345 if (SrcKind == Type::STK_CPointer) 5346 return CK_CPointerToObjCPointerCast; 5347 maybeExtendBlockObject(Src); 5348 return CK_BlockPointerToObjCPointerCast; 5349 case Type::STK_Bool: 5350 return CK_PointerToBoolean; 5351 case Type::STK_Integral: 5352 return CK_PointerToIntegral; 5353 case Type::STK_Floating: 5354 case Type::STK_FloatingComplex: 5355 case Type::STK_IntegralComplex: 5356 case Type::STK_MemberPointer: 5357 llvm_unreachable("illegal cast from pointer"); 5358 } 5359 llvm_unreachable("Should have returned before this"); 5360 5361 case Type::STK_Bool: // casting from bool is like casting from an integer 5362 case Type::STK_Integral: 5363 switch (DestTy->getScalarTypeKind()) { 5364 case Type::STK_CPointer: 5365 case Type::STK_ObjCObjectPointer: 5366 case Type::STK_BlockPointer: 5367 if (Src.get()->isNullPointerConstant(Context, 5368 Expr::NPC_ValueDependentIsNull)) 5369 return CK_NullToPointer; 5370 return CK_IntegralToPointer; 5371 case Type::STK_Bool: 5372 return CK_IntegralToBoolean; 5373 case Type::STK_Integral: 5374 return CK_IntegralCast; 5375 case Type::STK_Floating: 5376 return CK_IntegralToFloating; 5377 case Type::STK_IntegralComplex: 5378 Src = ImpCastExprToType(Src.get(), 5379 DestTy->castAs<ComplexType>()->getElementType(), 5380 CK_IntegralCast); 5381 return CK_IntegralRealToComplex; 5382 case Type::STK_FloatingComplex: 5383 Src = ImpCastExprToType(Src.get(), 5384 DestTy->castAs<ComplexType>()->getElementType(), 5385 CK_IntegralToFloating); 5386 return CK_FloatingRealToComplex; 5387 case Type::STK_MemberPointer: 5388 llvm_unreachable("member pointer type in C"); 5389 } 5390 llvm_unreachable("Should have returned before this"); 5391 5392 case Type::STK_Floating: 5393 switch (DestTy->getScalarTypeKind()) { 5394 case Type::STK_Floating: 5395 return CK_FloatingCast; 5396 case Type::STK_Bool: 5397 return CK_FloatingToBoolean; 5398 case Type::STK_Integral: 5399 return CK_FloatingToIntegral; 5400 case Type::STK_FloatingComplex: 5401 Src = ImpCastExprToType(Src.get(), 5402 DestTy->castAs<ComplexType>()->getElementType(), 5403 CK_FloatingCast); 5404 return CK_FloatingRealToComplex; 5405 case Type::STK_IntegralComplex: 5406 Src = ImpCastExprToType(Src.get(), 5407 DestTy->castAs<ComplexType>()->getElementType(), 5408 CK_FloatingToIntegral); 5409 return CK_IntegralRealToComplex; 5410 case Type::STK_CPointer: 5411 case Type::STK_ObjCObjectPointer: 5412 case Type::STK_BlockPointer: 5413 llvm_unreachable("valid float->pointer cast?"); 5414 case Type::STK_MemberPointer: 5415 llvm_unreachable("member pointer type in C"); 5416 } 5417 llvm_unreachable("Should have returned before this"); 5418 5419 case Type::STK_FloatingComplex: 5420 switch (DestTy->getScalarTypeKind()) { 5421 case Type::STK_FloatingComplex: 5422 return CK_FloatingComplexCast; 5423 case Type::STK_IntegralComplex: 5424 return CK_FloatingComplexToIntegralComplex; 5425 case Type::STK_Floating: { 5426 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5427 if (Context.hasSameType(ET, DestTy)) 5428 return CK_FloatingComplexToReal; 5429 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5430 return CK_FloatingCast; 5431 } 5432 case Type::STK_Bool: 5433 return CK_FloatingComplexToBoolean; 5434 case Type::STK_Integral: 5435 Src = ImpCastExprToType(Src.get(), 5436 SrcTy->castAs<ComplexType>()->getElementType(), 5437 CK_FloatingComplexToReal); 5438 return CK_FloatingToIntegral; 5439 case Type::STK_CPointer: 5440 case Type::STK_ObjCObjectPointer: 5441 case Type::STK_BlockPointer: 5442 llvm_unreachable("valid complex float->pointer cast?"); 5443 case Type::STK_MemberPointer: 5444 llvm_unreachable("member pointer type in C"); 5445 } 5446 llvm_unreachable("Should have returned before this"); 5447 5448 case Type::STK_IntegralComplex: 5449 switch (DestTy->getScalarTypeKind()) { 5450 case Type::STK_FloatingComplex: 5451 return CK_IntegralComplexToFloatingComplex; 5452 case Type::STK_IntegralComplex: 5453 return CK_IntegralComplexCast; 5454 case Type::STK_Integral: { 5455 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5456 if (Context.hasSameType(ET, DestTy)) 5457 return CK_IntegralComplexToReal; 5458 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5459 return CK_IntegralCast; 5460 } 5461 case Type::STK_Bool: 5462 return CK_IntegralComplexToBoolean; 5463 case Type::STK_Floating: 5464 Src = ImpCastExprToType(Src.get(), 5465 SrcTy->castAs<ComplexType>()->getElementType(), 5466 CK_IntegralComplexToReal); 5467 return CK_IntegralToFloating; 5468 case Type::STK_CPointer: 5469 case Type::STK_ObjCObjectPointer: 5470 case Type::STK_BlockPointer: 5471 llvm_unreachable("valid complex int->pointer cast?"); 5472 case Type::STK_MemberPointer: 5473 llvm_unreachable("member pointer type in C"); 5474 } 5475 llvm_unreachable("Should have returned before this"); 5476 } 5477 5478 llvm_unreachable("Unhandled scalar cast"); 5479 } 5480 5481 static bool breakDownVectorType(QualType type, uint64_t &len, 5482 QualType &eltType) { 5483 // Vectors are simple. 5484 if (const VectorType *vecType = type->getAs<VectorType>()) { 5485 len = vecType->getNumElements(); 5486 eltType = vecType->getElementType(); 5487 assert(eltType->isScalarType()); 5488 return true; 5489 } 5490 5491 // We allow lax conversion to and from non-vector types, but only if 5492 // they're real types (i.e. non-complex, non-pointer scalar types). 5493 if (!type->isRealType()) return false; 5494 5495 len = 1; 5496 eltType = type; 5497 return true; 5498 } 5499 5500 /// Are the two types lax-compatible vector types? That is, given 5501 /// that one of them is a vector, do they have equal storage sizes, 5502 /// where the storage size is the number of elements times the element 5503 /// size? 5504 /// 5505 /// This will also return false if either of the types is neither a 5506 /// vector nor a real type. 5507 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5508 assert(destTy->isVectorType() || srcTy->isVectorType()); 5509 5510 // Disallow lax conversions between scalars and ExtVectors (these 5511 // conversions are allowed for other vector types because common headers 5512 // depend on them). Most scalar OP ExtVector cases are handled by the 5513 // splat path anyway, which does what we want (convert, not bitcast). 5514 // What this rules out for ExtVectors is crazy things like char4*float. 5515 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5516 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5517 5518 uint64_t srcLen, destLen; 5519 QualType srcEltTy, destEltTy; 5520 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5521 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5522 5523 // ASTContext::getTypeSize will return the size rounded up to a 5524 // power of 2, so instead of using that, we need to use the raw 5525 // element size multiplied by the element count. 5526 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5527 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5528 5529 return (srcLen * srcEltSize == destLen * destEltSize); 5530 } 5531 5532 /// Is this a legal conversion between two types, one of which is 5533 /// known to be a vector type? 5534 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5535 assert(destTy->isVectorType() || srcTy->isVectorType()); 5536 5537 if (!Context.getLangOpts().LaxVectorConversions) 5538 return false; 5539 return areLaxCompatibleVectorTypes(srcTy, destTy); 5540 } 5541 5542 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5543 CastKind &Kind) { 5544 assert(VectorTy->isVectorType() && "Not a vector type!"); 5545 5546 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5547 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5548 return Diag(R.getBegin(), 5549 Ty->isVectorType() ? 5550 diag::err_invalid_conversion_between_vectors : 5551 diag::err_invalid_conversion_between_vector_and_integer) 5552 << VectorTy << Ty << R; 5553 } else 5554 return Diag(R.getBegin(), 5555 diag::err_invalid_conversion_between_vector_and_scalar) 5556 << VectorTy << Ty << R; 5557 5558 Kind = CK_BitCast; 5559 return false; 5560 } 5561 5562 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5563 Expr *CastExpr, CastKind &Kind) { 5564 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5565 5566 QualType SrcTy = CastExpr->getType(); 5567 5568 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5569 // an ExtVectorType. 5570 // In OpenCL, casts between vectors of different types are not allowed. 5571 // (See OpenCL 6.2). 5572 if (SrcTy->isVectorType()) { 5573 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5574 || (getLangOpts().OpenCL && 5575 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5576 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5577 << DestTy << SrcTy << R; 5578 return ExprError(); 5579 } 5580 Kind = CK_BitCast; 5581 return CastExpr; 5582 } 5583 5584 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5585 // conversion will take place first from scalar to elt type, and then 5586 // splat from elt type to vector. 5587 if (SrcTy->isPointerType()) 5588 return Diag(R.getBegin(), 5589 diag::err_invalid_conversion_between_vector_and_scalar) 5590 << DestTy << SrcTy << R; 5591 5592 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5593 ExprResult CastExprRes = CastExpr; 5594 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5595 if (CastExprRes.isInvalid()) 5596 return ExprError(); 5597 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5598 5599 Kind = CK_VectorSplat; 5600 return CastExpr; 5601 } 5602 5603 ExprResult 5604 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5605 Declarator &D, ParsedType &Ty, 5606 SourceLocation RParenLoc, Expr *CastExpr) { 5607 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5608 "ActOnCastExpr(): missing type or expr"); 5609 5610 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5611 if (D.isInvalidType()) 5612 return ExprError(); 5613 5614 if (getLangOpts().CPlusPlus) { 5615 // Check that there are no default arguments (C++ only). 5616 CheckExtraCXXDefaultArguments(D); 5617 } else { 5618 // Make sure any TypoExprs have been dealt with. 5619 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5620 if (!Res.isUsable()) 5621 return ExprError(); 5622 CastExpr = Res.get(); 5623 } 5624 5625 checkUnusedDeclAttributes(D); 5626 5627 QualType castType = castTInfo->getType(); 5628 Ty = CreateParsedType(castType, castTInfo); 5629 5630 bool isVectorLiteral = false; 5631 5632 // Check for an altivec or OpenCL literal, 5633 // i.e. all the elements are integer constants. 5634 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5635 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5636 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5637 && castType->isVectorType() && (PE || PLE)) { 5638 if (PLE && PLE->getNumExprs() == 0) { 5639 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5640 return ExprError(); 5641 } 5642 if (PE || PLE->getNumExprs() == 1) { 5643 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5644 if (!E->getType()->isVectorType()) 5645 isVectorLiteral = true; 5646 } 5647 else 5648 isVectorLiteral = true; 5649 } 5650 5651 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5652 // then handle it as such. 5653 if (isVectorLiteral) 5654 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5655 5656 // If the Expr being casted is a ParenListExpr, handle it specially. 5657 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5658 // sequence of BinOp comma operators. 5659 if (isa<ParenListExpr>(CastExpr)) { 5660 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5661 if (Result.isInvalid()) return ExprError(); 5662 CastExpr = Result.get(); 5663 } 5664 5665 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5666 !getSourceManager().isInSystemMacro(LParenLoc)) 5667 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5668 5669 CheckTollFreeBridgeCast(castType, CastExpr); 5670 5671 CheckObjCBridgeRelatedCast(castType, CastExpr); 5672 5673 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5674 } 5675 5676 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5677 SourceLocation RParenLoc, Expr *E, 5678 TypeSourceInfo *TInfo) { 5679 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5680 "Expected paren or paren list expression"); 5681 5682 Expr **exprs; 5683 unsigned numExprs; 5684 Expr *subExpr; 5685 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5686 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5687 LiteralLParenLoc = PE->getLParenLoc(); 5688 LiteralRParenLoc = PE->getRParenLoc(); 5689 exprs = PE->getExprs(); 5690 numExprs = PE->getNumExprs(); 5691 } else { // isa<ParenExpr> by assertion at function entrance 5692 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5693 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5694 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5695 exprs = &subExpr; 5696 numExprs = 1; 5697 } 5698 5699 QualType Ty = TInfo->getType(); 5700 assert(Ty->isVectorType() && "Expected vector type"); 5701 5702 SmallVector<Expr *, 8> initExprs; 5703 const VectorType *VTy = Ty->getAs<VectorType>(); 5704 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5705 5706 // '(...)' form of vector initialization in AltiVec: the number of 5707 // initializers must be one or must match the size of the vector. 5708 // If a single value is specified in the initializer then it will be 5709 // replicated to all the components of the vector 5710 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5711 // The number of initializers must be one or must match the size of the 5712 // vector. If a single value is specified in the initializer then it will 5713 // be replicated to all the components of the vector 5714 if (numExprs == 1) { 5715 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5716 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5717 if (Literal.isInvalid()) 5718 return ExprError(); 5719 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5720 PrepareScalarCast(Literal, ElemTy)); 5721 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5722 } 5723 else if (numExprs < numElems) { 5724 Diag(E->getExprLoc(), 5725 diag::err_incorrect_number_of_vector_initializers); 5726 return ExprError(); 5727 } 5728 else 5729 initExprs.append(exprs, exprs + numExprs); 5730 } 5731 else { 5732 // For OpenCL, when the number of initializers is a single value, 5733 // it will be replicated to all components of the vector. 5734 if (getLangOpts().OpenCL && 5735 VTy->getVectorKind() == VectorType::GenericVector && 5736 numExprs == 1) { 5737 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5738 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5739 if (Literal.isInvalid()) 5740 return ExprError(); 5741 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5742 PrepareScalarCast(Literal, ElemTy)); 5743 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5744 } 5745 5746 initExprs.append(exprs, exprs + numExprs); 5747 } 5748 // FIXME: This means that pretty-printing the final AST will produce curly 5749 // braces instead of the original commas. 5750 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5751 initExprs, LiteralRParenLoc); 5752 initE->setType(Ty); 5753 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5754 } 5755 5756 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5757 /// the ParenListExpr into a sequence of comma binary operators. 5758 ExprResult 5759 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5760 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5761 if (!E) 5762 return OrigExpr; 5763 5764 ExprResult Result(E->getExpr(0)); 5765 5766 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5767 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5768 E->getExpr(i)); 5769 5770 if (Result.isInvalid()) return ExprError(); 5771 5772 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5773 } 5774 5775 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5776 SourceLocation R, 5777 MultiExprArg Val) { 5778 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5779 return expr; 5780 } 5781 5782 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5783 /// constant and the other is not a pointer. Returns true if a diagnostic is 5784 /// emitted. 5785 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5786 SourceLocation QuestionLoc) { 5787 Expr *NullExpr = LHSExpr; 5788 Expr *NonPointerExpr = RHSExpr; 5789 Expr::NullPointerConstantKind NullKind = 5790 NullExpr->isNullPointerConstant(Context, 5791 Expr::NPC_ValueDependentIsNotNull); 5792 5793 if (NullKind == Expr::NPCK_NotNull) { 5794 NullExpr = RHSExpr; 5795 NonPointerExpr = LHSExpr; 5796 NullKind = 5797 NullExpr->isNullPointerConstant(Context, 5798 Expr::NPC_ValueDependentIsNotNull); 5799 } 5800 5801 if (NullKind == Expr::NPCK_NotNull) 5802 return false; 5803 5804 if (NullKind == Expr::NPCK_ZeroExpression) 5805 return false; 5806 5807 if (NullKind == Expr::NPCK_ZeroLiteral) { 5808 // In this case, check to make sure that we got here from a "NULL" 5809 // string in the source code. 5810 NullExpr = NullExpr->IgnoreParenImpCasts(); 5811 SourceLocation loc = NullExpr->getExprLoc(); 5812 if (!findMacroSpelling(loc, "NULL")) 5813 return false; 5814 } 5815 5816 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5817 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5818 << NonPointerExpr->getType() << DiagType 5819 << NonPointerExpr->getSourceRange(); 5820 return true; 5821 } 5822 5823 /// \brief Return false if the condition expression is valid, true otherwise. 5824 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 5825 QualType CondTy = Cond->getType(); 5826 5827 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 5828 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 5829 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 5830 << CondTy << Cond->getSourceRange(); 5831 return true; 5832 } 5833 5834 // C99 6.5.15p2 5835 if (CondTy->isScalarType()) return false; 5836 5837 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 5838 << CondTy << Cond->getSourceRange(); 5839 return true; 5840 } 5841 5842 /// \brief Handle when one or both operands are void type. 5843 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5844 ExprResult &RHS) { 5845 Expr *LHSExpr = LHS.get(); 5846 Expr *RHSExpr = RHS.get(); 5847 5848 if (!LHSExpr->getType()->isVoidType()) 5849 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5850 << RHSExpr->getSourceRange(); 5851 if (!RHSExpr->getType()->isVoidType()) 5852 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5853 << LHSExpr->getSourceRange(); 5854 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5855 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5856 return S.Context.VoidTy; 5857 } 5858 5859 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5860 /// true otherwise. 5861 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5862 QualType PointerTy) { 5863 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5864 !NullExpr.get()->isNullPointerConstant(S.Context, 5865 Expr::NPC_ValueDependentIsNull)) 5866 return true; 5867 5868 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5869 return false; 5870 } 5871 5872 /// \brief Checks compatibility between two pointers and return the resulting 5873 /// type. 5874 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5875 ExprResult &RHS, 5876 SourceLocation Loc) { 5877 QualType LHSTy = LHS.get()->getType(); 5878 QualType RHSTy = RHS.get()->getType(); 5879 5880 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5881 // Two identical pointers types are always compatible. 5882 return LHSTy; 5883 } 5884 5885 QualType lhptee, rhptee; 5886 5887 // Get the pointee types. 5888 bool IsBlockPointer = false; 5889 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5890 lhptee = LHSBTy->getPointeeType(); 5891 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5892 IsBlockPointer = true; 5893 } else { 5894 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5895 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5896 } 5897 5898 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5899 // differently qualified versions of compatible types, the result type is 5900 // a pointer to an appropriately qualified version of the composite 5901 // type. 5902 5903 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5904 // clause doesn't make sense for our extensions. E.g. address space 2 should 5905 // be incompatible with address space 3: they may live on different devices or 5906 // anything. 5907 Qualifiers lhQual = lhptee.getQualifiers(); 5908 Qualifiers rhQual = rhptee.getQualifiers(); 5909 5910 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5911 lhQual.removeCVRQualifiers(); 5912 rhQual.removeCVRQualifiers(); 5913 5914 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5915 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5916 5917 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5918 5919 if (CompositeTy.isNull()) { 5920 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 5921 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5922 << RHS.get()->getSourceRange(); 5923 // In this situation, we assume void* type. No especially good 5924 // reason, but this is what gcc does, and we do have to pick 5925 // to get a consistent AST. 5926 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5927 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5928 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5929 return incompatTy; 5930 } 5931 5932 // The pointer types are compatible. 5933 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5934 if (IsBlockPointer) 5935 ResultTy = S.Context.getBlockPointerType(ResultTy); 5936 else 5937 ResultTy = S.Context.getPointerType(ResultTy); 5938 5939 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5940 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5941 return ResultTy; 5942 } 5943 5944 /// \brief Return the resulting type when the operands are both block pointers. 5945 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5946 ExprResult &LHS, 5947 ExprResult &RHS, 5948 SourceLocation Loc) { 5949 QualType LHSTy = LHS.get()->getType(); 5950 QualType RHSTy = RHS.get()->getType(); 5951 5952 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5953 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5954 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5955 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5956 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5957 return destType; 5958 } 5959 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5960 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5961 << RHS.get()->getSourceRange(); 5962 return QualType(); 5963 } 5964 5965 // We have 2 block pointer types. 5966 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5967 } 5968 5969 /// \brief Return the resulting type when the operands are both pointers. 5970 static QualType 5971 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5972 ExprResult &RHS, 5973 SourceLocation Loc) { 5974 // get the pointer types 5975 QualType LHSTy = LHS.get()->getType(); 5976 QualType RHSTy = RHS.get()->getType(); 5977 5978 // get the "pointed to" types 5979 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5980 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5981 5982 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5983 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5984 // Figure out necessary qualifiers (C99 6.5.15p6) 5985 QualType destPointee 5986 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5987 QualType destType = S.Context.getPointerType(destPointee); 5988 // Add qualifiers if necessary. 5989 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 5990 // Promote to void*. 5991 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5992 return destType; 5993 } 5994 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5995 QualType destPointee 5996 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5997 QualType destType = S.Context.getPointerType(destPointee); 5998 // Add qualifiers if necessary. 5999 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6000 // Promote to void*. 6001 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6002 return destType; 6003 } 6004 6005 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6006 } 6007 6008 /// \brief Return false if the first expression is not an integer and the second 6009 /// expression is not a pointer, true otherwise. 6010 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6011 Expr* PointerExpr, SourceLocation Loc, 6012 bool IsIntFirstExpr) { 6013 if (!PointerExpr->getType()->isPointerType() || 6014 !Int.get()->getType()->isIntegerType()) 6015 return false; 6016 6017 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6018 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6019 6020 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6021 << Expr1->getType() << Expr2->getType() 6022 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6023 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6024 CK_IntegralToPointer); 6025 return true; 6026 } 6027 6028 /// \brief Simple conversion between integer and floating point types. 6029 /// 6030 /// Used when handling the OpenCL conditional operator where the 6031 /// condition is a vector while the other operands are scalar. 6032 /// 6033 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6034 /// types are either integer or floating type. Between the two 6035 /// operands, the type with the higher rank is defined as the "result 6036 /// type". The other operand needs to be promoted to the same type. No 6037 /// other type promotion is allowed. We cannot use 6038 /// UsualArithmeticConversions() for this purpose, since it always 6039 /// promotes promotable types. 6040 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6041 ExprResult &RHS, 6042 SourceLocation QuestionLoc) { 6043 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6044 if (LHS.isInvalid()) 6045 return QualType(); 6046 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6047 if (RHS.isInvalid()) 6048 return QualType(); 6049 6050 // For conversion purposes, we ignore any qualifiers. 6051 // For example, "const float" and "float" are equivalent. 6052 QualType LHSType = 6053 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6054 QualType RHSType = 6055 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6056 6057 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6058 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6059 << LHSType << LHS.get()->getSourceRange(); 6060 return QualType(); 6061 } 6062 6063 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6064 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6065 << RHSType << RHS.get()->getSourceRange(); 6066 return QualType(); 6067 } 6068 6069 // If both types are identical, no conversion is needed. 6070 if (LHSType == RHSType) 6071 return LHSType; 6072 6073 // Now handle "real" floating types (i.e. float, double, long double). 6074 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6075 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6076 /*IsCompAssign = */ false); 6077 6078 // Finally, we have two differing integer types. 6079 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6080 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6081 } 6082 6083 /// \brief Convert scalar operands to a vector that matches the 6084 /// condition in length. 6085 /// 6086 /// Used when handling the OpenCL conditional operator where the 6087 /// condition is a vector while the other operands are scalar. 6088 /// 6089 /// We first compute the "result type" for the scalar operands 6090 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6091 /// into a vector of that type where the length matches the condition 6092 /// vector type. s6.11.6 requires that the element types of the result 6093 /// and the condition must have the same number of bits. 6094 static QualType 6095 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6096 QualType CondTy, SourceLocation QuestionLoc) { 6097 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6098 if (ResTy.isNull()) return QualType(); 6099 6100 const VectorType *CV = CondTy->getAs<VectorType>(); 6101 assert(CV); 6102 6103 // Determine the vector result type 6104 unsigned NumElements = CV->getNumElements(); 6105 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6106 6107 // Ensure that all types have the same number of bits 6108 if (S.Context.getTypeSize(CV->getElementType()) 6109 != S.Context.getTypeSize(ResTy)) { 6110 // Since VectorTy is created internally, it does not pretty print 6111 // with an OpenCL name. Instead, we just print a description. 6112 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6113 SmallString<64> Str; 6114 llvm::raw_svector_ostream OS(Str); 6115 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6116 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6117 << CondTy << OS.str(); 6118 return QualType(); 6119 } 6120 6121 // Convert operands to the vector result type 6122 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6123 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6124 6125 return VectorTy; 6126 } 6127 6128 /// \brief Return false if this is a valid OpenCL condition vector 6129 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6130 SourceLocation QuestionLoc) { 6131 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6132 // integral type. 6133 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6134 assert(CondTy); 6135 QualType EleTy = CondTy->getElementType(); 6136 if (EleTy->isIntegerType()) return false; 6137 6138 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6139 << Cond->getType() << Cond->getSourceRange(); 6140 return true; 6141 } 6142 6143 /// \brief Return false if the vector condition type and the vector 6144 /// result type are compatible. 6145 /// 6146 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6147 /// number of elements, and their element types have the same number 6148 /// of bits. 6149 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6150 SourceLocation QuestionLoc) { 6151 const VectorType *CV = CondTy->getAs<VectorType>(); 6152 const VectorType *RV = VecResTy->getAs<VectorType>(); 6153 assert(CV && RV); 6154 6155 if (CV->getNumElements() != RV->getNumElements()) { 6156 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6157 << CondTy << VecResTy; 6158 return true; 6159 } 6160 6161 QualType CVE = CV->getElementType(); 6162 QualType RVE = RV->getElementType(); 6163 6164 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6165 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6166 << CondTy << VecResTy; 6167 return true; 6168 } 6169 6170 return false; 6171 } 6172 6173 /// \brief Return the resulting type for the conditional operator in 6174 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6175 /// s6.3.i) when the condition is a vector type. 6176 static QualType 6177 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6178 ExprResult &LHS, ExprResult &RHS, 6179 SourceLocation QuestionLoc) { 6180 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6181 if (Cond.isInvalid()) 6182 return QualType(); 6183 QualType CondTy = Cond.get()->getType(); 6184 6185 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6186 return QualType(); 6187 6188 // If either operand is a vector then find the vector type of the 6189 // result as specified in OpenCL v1.1 s6.3.i. 6190 if (LHS.get()->getType()->isVectorType() || 6191 RHS.get()->getType()->isVectorType()) { 6192 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6193 /*isCompAssign*/false, 6194 /*AllowBothBool*/true, 6195 /*AllowBoolConversions*/false); 6196 if (VecResTy.isNull()) return QualType(); 6197 // The result type must match the condition type as specified in 6198 // OpenCL v1.1 s6.11.6. 6199 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6200 return QualType(); 6201 return VecResTy; 6202 } 6203 6204 // Both operands are scalar. 6205 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6206 } 6207 6208 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6209 /// In that case, LHS = cond. 6210 /// C99 6.5.15 6211 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6212 ExprResult &RHS, ExprValueKind &VK, 6213 ExprObjectKind &OK, 6214 SourceLocation QuestionLoc) { 6215 6216 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6217 if (!LHSResult.isUsable()) return QualType(); 6218 LHS = LHSResult; 6219 6220 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6221 if (!RHSResult.isUsable()) return QualType(); 6222 RHS = RHSResult; 6223 6224 // C++ is sufficiently different to merit its own checker. 6225 if (getLangOpts().CPlusPlus) 6226 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6227 6228 VK = VK_RValue; 6229 OK = OK_Ordinary; 6230 6231 // The OpenCL operator with a vector condition is sufficiently 6232 // different to merit its own checker. 6233 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6234 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6235 6236 // First, check the condition. 6237 Cond = UsualUnaryConversions(Cond.get()); 6238 if (Cond.isInvalid()) 6239 return QualType(); 6240 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6241 return QualType(); 6242 6243 // Now check the two expressions. 6244 if (LHS.get()->getType()->isVectorType() || 6245 RHS.get()->getType()->isVectorType()) 6246 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6247 /*AllowBothBool*/true, 6248 /*AllowBoolConversions*/false); 6249 6250 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6251 if (LHS.isInvalid() || RHS.isInvalid()) 6252 return QualType(); 6253 6254 QualType LHSTy = LHS.get()->getType(); 6255 QualType RHSTy = RHS.get()->getType(); 6256 6257 // If both operands have arithmetic type, do the usual arithmetic conversions 6258 // to find a common type: C99 6.5.15p3,5. 6259 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6260 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6261 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6262 6263 return ResTy; 6264 } 6265 6266 // If both operands are the same structure or union type, the result is that 6267 // type. 6268 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6269 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6270 if (LHSRT->getDecl() == RHSRT->getDecl()) 6271 // "If both the operands have structure or union type, the result has 6272 // that type." This implies that CV qualifiers are dropped. 6273 return LHSTy.getUnqualifiedType(); 6274 // FIXME: Type of conditional expression must be complete in C mode. 6275 } 6276 6277 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6278 // The following || allows only one side to be void (a GCC-ism). 6279 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6280 return checkConditionalVoidType(*this, LHS, RHS); 6281 } 6282 6283 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6284 // the type of the other operand." 6285 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6286 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6287 6288 // All objective-c pointer type analysis is done here. 6289 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6290 QuestionLoc); 6291 if (LHS.isInvalid() || RHS.isInvalid()) 6292 return QualType(); 6293 if (!compositeType.isNull()) 6294 return compositeType; 6295 6296 6297 // Handle block pointer types. 6298 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6299 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6300 QuestionLoc); 6301 6302 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6303 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6304 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6305 QuestionLoc); 6306 6307 // GCC compatibility: soften pointer/integer mismatch. Note that 6308 // null pointers have been filtered out by this point. 6309 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6310 /*isIntFirstExpr=*/true)) 6311 return RHSTy; 6312 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6313 /*isIntFirstExpr=*/false)) 6314 return LHSTy; 6315 6316 // Emit a better diagnostic if one of the expressions is a null pointer 6317 // constant and the other is not a pointer type. In this case, the user most 6318 // likely forgot to take the address of the other expression. 6319 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6320 return QualType(); 6321 6322 // Otherwise, the operands are not compatible. 6323 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6324 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6325 << RHS.get()->getSourceRange(); 6326 return QualType(); 6327 } 6328 6329 /// FindCompositeObjCPointerType - Helper method to find composite type of 6330 /// two objective-c pointer types of the two input expressions. 6331 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6332 SourceLocation QuestionLoc) { 6333 QualType LHSTy = LHS.get()->getType(); 6334 QualType RHSTy = RHS.get()->getType(); 6335 6336 // Handle things like Class and struct objc_class*. Here we case the result 6337 // to the pseudo-builtin, because that will be implicitly cast back to the 6338 // redefinition type if an attempt is made to access its fields. 6339 if (LHSTy->isObjCClassType() && 6340 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6341 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6342 return LHSTy; 6343 } 6344 if (RHSTy->isObjCClassType() && 6345 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6346 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6347 return RHSTy; 6348 } 6349 // And the same for struct objc_object* / id 6350 if (LHSTy->isObjCIdType() && 6351 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6352 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6353 return LHSTy; 6354 } 6355 if (RHSTy->isObjCIdType() && 6356 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6357 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6358 return RHSTy; 6359 } 6360 // And the same for struct objc_selector* / SEL 6361 if (Context.isObjCSelType(LHSTy) && 6362 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6363 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6364 return LHSTy; 6365 } 6366 if (Context.isObjCSelType(RHSTy) && 6367 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6368 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6369 return RHSTy; 6370 } 6371 // Check constraints for Objective-C object pointers types. 6372 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6373 6374 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6375 // Two identical object pointer types are always compatible. 6376 return LHSTy; 6377 } 6378 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6379 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6380 QualType compositeType = LHSTy; 6381 6382 // If both operands are interfaces and either operand can be 6383 // assigned to the other, use that type as the composite 6384 // type. This allows 6385 // xxx ? (A*) a : (B*) b 6386 // where B is a subclass of A. 6387 // 6388 // Additionally, as for assignment, if either type is 'id' 6389 // allow silent coercion. Finally, if the types are 6390 // incompatible then make sure to use 'id' as the composite 6391 // type so the result is acceptable for sending messages to. 6392 6393 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6394 // It could return the composite type. 6395 if (!(compositeType = 6396 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6397 // Nothing more to do. 6398 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6399 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6400 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6401 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6402 } else if ((LHSTy->isObjCQualifiedIdType() || 6403 RHSTy->isObjCQualifiedIdType()) && 6404 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6405 // Need to handle "id<xx>" explicitly. 6406 // GCC allows qualified id and any Objective-C type to devolve to 6407 // id. Currently localizing to here until clear this should be 6408 // part of ObjCQualifiedIdTypesAreCompatible. 6409 compositeType = Context.getObjCIdType(); 6410 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6411 compositeType = Context.getObjCIdType(); 6412 } else { 6413 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6414 << LHSTy << RHSTy 6415 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6416 QualType incompatTy = Context.getObjCIdType(); 6417 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6418 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6419 return incompatTy; 6420 } 6421 // The object pointer types are compatible. 6422 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6423 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6424 return compositeType; 6425 } 6426 // Check Objective-C object pointer types and 'void *' 6427 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6428 if (getLangOpts().ObjCAutoRefCount) { 6429 // ARC forbids the implicit conversion of object pointers to 'void *', 6430 // so these types are not compatible. 6431 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6432 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6433 LHS = RHS = true; 6434 return QualType(); 6435 } 6436 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6437 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6438 QualType destPointee 6439 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6440 QualType destType = Context.getPointerType(destPointee); 6441 // Add qualifiers if necessary. 6442 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6443 // Promote to void*. 6444 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6445 return destType; 6446 } 6447 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6448 if (getLangOpts().ObjCAutoRefCount) { 6449 // ARC forbids the implicit conversion of object pointers to 'void *', 6450 // so these types are not compatible. 6451 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6452 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6453 LHS = RHS = true; 6454 return QualType(); 6455 } 6456 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6457 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6458 QualType destPointee 6459 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6460 QualType destType = Context.getPointerType(destPointee); 6461 // Add qualifiers if necessary. 6462 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6463 // Promote to void*. 6464 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6465 return destType; 6466 } 6467 return QualType(); 6468 } 6469 6470 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6471 /// ParenRange in parentheses. 6472 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6473 const PartialDiagnostic &Note, 6474 SourceRange ParenRange) { 6475 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 6476 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6477 EndLoc.isValid()) { 6478 Self.Diag(Loc, Note) 6479 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6480 << FixItHint::CreateInsertion(EndLoc, ")"); 6481 } else { 6482 // We can't display the parentheses, so just show the bare note. 6483 Self.Diag(Loc, Note) << ParenRange; 6484 } 6485 } 6486 6487 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6488 return Opc >= BO_Mul && Opc <= BO_Shr; 6489 } 6490 6491 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6492 /// expression, either using a built-in or overloaded operator, 6493 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6494 /// expression. 6495 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6496 Expr **RHSExprs) { 6497 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6498 E = E->IgnoreImpCasts(); 6499 E = E->IgnoreConversionOperator(); 6500 E = E->IgnoreImpCasts(); 6501 6502 // Built-in binary operator. 6503 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6504 if (IsArithmeticOp(OP->getOpcode())) { 6505 *Opcode = OP->getOpcode(); 6506 *RHSExprs = OP->getRHS(); 6507 return true; 6508 } 6509 } 6510 6511 // Overloaded operator. 6512 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6513 if (Call->getNumArgs() != 2) 6514 return false; 6515 6516 // Make sure this is really a binary operator that is safe to pass into 6517 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6518 OverloadedOperatorKind OO = Call->getOperator(); 6519 if (OO < OO_Plus || OO > OO_Arrow || 6520 OO == OO_PlusPlus || OO == OO_MinusMinus) 6521 return false; 6522 6523 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6524 if (IsArithmeticOp(OpKind)) { 6525 *Opcode = OpKind; 6526 *RHSExprs = Call->getArg(1); 6527 return true; 6528 } 6529 } 6530 6531 return false; 6532 } 6533 6534 static bool IsLogicOp(BinaryOperatorKind Opc) { 6535 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 6536 } 6537 6538 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6539 /// or is a logical expression such as (x==y) which has int type, but is 6540 /// commonly interpreted as boolean. 6541 static bool ExprLooksBoolean(Expr *E) { 6542 E = E->IgnoreParenImpCasts(); 6543 6544 if (E->getType()->isBooleanType()) 6545 return true; 6546 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6547 return IsLogicOp(OP->getOpcode()); 6548 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6549 return OP->getOpcode() == UO_LNot; 6550 if (E->getType()->isPointerType()) 6551 return true; 6552 6553 return false; 6554 } 6555 6556 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6557 /// and binary operator are mixed in a way that suggests the programmer assumed 6558 /// the conditional operator has higher precedence, for example: 6559 /// "int x = a + someBinaryCondition ? 1 : 2". 6560 static void DiagnoseConditionalPrecedence(Sema &Self, 6561 SourceLocation OpLoc, 6562 Expr *Condition, 6563 Expr *LHSExpr, 6564 Expr *RHSExpr) { 6565 BinaryOperatorKind CondOpcode; 6566 Expr *CondRHS; 6567 6568 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6569 return; 6570 if (!ExprLooksBoolean(CondRHS)) 6571 return; 6572 6573 // The condition is an arithmetic binary expression, with a right- 6574 // hand side that looks boolean, so warn. 6575 6576 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6577 << Condition->getSourceRange() 6578 << BinaryOperator::getOpcodeStr(CondOpcode); 6579 6580 SuggestParentheses(Self, OpLoc, 6581 Self.PDiag(diag::note_precedence_silence) 6582 << BinaryOperator::getOpcodeStr(CondOpcode), 6583 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6584 6585 SuggestParentheses(Self, OpLoc, 6586 Self.PDiag(diag::note_precedence_conditional_first), 6587 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6588 } 6589 6590 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6591 /// in the case of a the GNU conditional expr extension. 6592 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6593 SourceLocation ColonLoc, 6594 Expr *CondExpr, Expr *LHSExpr, 6595 Expr *RHSExpr) { 6596 if (!getLangOpts().CPlusPlus) { 6597 // C cannot handle TypoExpr nodes in the condition because it 6598 // doesn't handle dependent types properly, so make sure any TypoExprs have 6599 // been dealt with before checking the operands. 6600 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6601 if (!CondResult.isUsable()) return ExprError(); 6602 CondExpr = CondResult.get(); 6603 } 6604 6605 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6606 // was the condition. 6607 OpaqueValueExpr *opaqueValue = nullptr; 6608 Expr *commonExpr = nullptr; 6609 if (!LHSExpr) { 6610 commonExpr = CondExpr; 6611 // Lower out placeholder types first. This is important so that we don't 6612 // try to capture a placeholder. This happens in few cases in C++; such 6613 // as Objective-C++'s dictionary subscripting syntax. 6614 if (commonExpr->hasPlaceholderType()) { 6615 ExprResult result = CheckPlaceholderExpr(commonExpr); 6616 if (!result.isUsable()) return ExprError(); 6617 commonExpr = result.get(); 6618 } 6619 // We usually want to apply unary conversions *before* saving, except 6620 // in the special case of a C++ l-value conditional. 6621 if (!(getLangOpts().CPlusPlus 6622 && !commonExpr->isTypeDependent() 6623 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6624 && commonExpr->isGLValue() 6625 && commonExpr->isOrdinaryOrBitFieldObject() 6626 && RHSExpr->isOrdinaryOrBitFieldObject() 6627 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6628 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6629 if (commonRes.isInvalid()) 6630 return ExprError(); 6631 commonExpr = commonRes.get(); 6632 } 6633 6634 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6635 commonExpr->getType(), 6636 commonExpr->getValueKind(), 6637 commonExpr->getObjectKind(), 6638 commonExpr); 6639 LHSExpr = CondExpr = opaqueValue; 6640 } 6641 6642 ExprValueKind VK = VK_RValue; 6643 ExprObjectKind OK = OK_Ordinary; 6644 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6645 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6646 VK, OK, QuestionLoc); 6647 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6648 RHS.isInvalid()) 6649 return ExprError(); 6650 6651 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6652 RHS.get()); 6653 6654 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6655 6656 if (!commonExpr) 6657 return new (Context) 6658 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6659 RHS.get(), result, VK, OK); 6660 6661 return new (Context) BinaryConditionalOperator( 6662 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6663 ColonLoc, result, VK, OK); 6664 } 6665 6666 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6667 // being closely modeled after the C99 spec:-). The odd characteristic of this 6668 // routine is it effectively iqnores the qualifiers on the top level pointee. 6669 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6670 // FIXME: add a couple examples in this comment. 6671 static Sema::AssignConvertType 6672 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6673 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6674 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6675 6676 // get the "pointed to" type (ignoring qualifiers at the top level) 6677 const Type *lhptee, *rhptee; 6678 Qualifiers lhq, rhq; 6679 std::tie(lhptee, lhq) = 6680 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6681 std::tie(rhptee, rhq) = 6682 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6683 6684 Sema::AssignConvertType ConvTy = Sema::Compatible; 6685 6686 // C99 6.5.16.1p1: This following citation is common to constraints 6687 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6688 // qualifiers of the type *pointed to* by the right; 6689 6690 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6691 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6692 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6693 // Ignore lifetime for further calculation. 6694 lhq.removeObjCLifetime(); 6695 rhq.removeObjCLifetime(); 6696 } 6697 6698 if (!lhq.compatiblyIncludes(rhq)) { 6699 // Treat address-space mismatches as fatal. TODO: address subspaces 6700 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6701 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6702 6703 // It's okay to add or remove GC or lifetime qualifiers when converting to 6704 // and from void*. 6705 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6706 .compatiblyIncludes( 6707 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6708 && (lhptee->isVoidType() || rhptee->isVoidType())) 6709 ; // keep old 6710 6711 // Treat lifetime mismatches as fatal. 6712 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6713 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6714 6715 // For GCC compatibility, other qualifier mismatches are treated 6716 // as still compatible in C. 6717 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6718 } 6719 6720 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6721 // incomplete type and the other is a pointer to a qualified or unqualified 6722 // version of void... 6723 if (lhptee->isVoidType()) { 6724 if (rhptee->isIncompleteOrObjectType()) 6725 return ConvTy; 6726 6727 // As an extension, we allow cast to/from void* to function pointer. 6728 assert(rhptee->isFunctionType()); 6729 return Sema::FunctionVoidPointer; 6730 } 6731 6732 if (rhptee->isVoidType()) { 6733 if (lhptee->isIncompleteOrObjectType()) 6734 return ConvTy; 6735 6736 // As an extension, we allow cast to/from void* to function pointer. 6737 assert(lhptee->isFunctionType()); 6738 return Sema::FunctionVoidPointer; 6739 } 6740 6741 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6742 // unqualified versions of compatible types, ... 6743 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6744 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6745 // Check if the pointee types are compatible ignoring the sign. 6746 // We explicitly check for char so that we catch "char" vs 6747 // "unsigned char" on systems where "char" is unsigned. 6748 if (lhptee->isCharType()) 6749 ltrans = S.Context.UnsignedCharTy; 6750 else if (lhptee->hasSignedIntegerRepresentation()) 6751 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6752 6753 if (rhptee->isCharType()) 6754 rtrans = S.Context.UnsignedCharTy; 6755 else if (rhptee->hasSignedIntegerRepresentation()) 6756 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6757 6758 if (ltrans == rtrans) { 6759 // Types are compatible ignoring the sign. Qualifier incompatibility 6760 // takes priority over sign incompatibility because the sign 6761 // warning can be disabled. 6762 if (ConvTy != Sema::Compatible) 6763 return ConvTy; 6764 6765 return Sema::IncompatiblePointerSign; 6766 } 6767 6768 // If we are a multi-level pointer, it's possible that our issue is simply 6769 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6770 // the eventual target type is the same and the pointers have the same 6771 // level of indirection, this must be the issue. 6772 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6773 do { 6774 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6775 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6776 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6777 6778 if (lhptee == rhptee) 6779 return Sema::IncompatibleNestedPointerQualifiers; 6780 } 6781 6782 // General pointer incompatibility takes priority over qualifiers. 6783 return Sema::IncompatiblePointer; 6784 } 6785 if (!S.getLangOpts().CPlusPlus && 6786 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6787 return Sema::IncompatiblePointer; 6788 return ConvTy; 6789 } 6790 6791 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6792 /// block pointer types are compatible or whether a block and normal pointer 6793 /// are compatible. It is more restrict than comparing two function pointer 6794 // types. 6795 static Sema::AssignConvertType 6796 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6797 QualType RHSType) { 6798 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6799 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6800 6801 QualType lhptee, rhptee; 6802 6803 // get the "pointed to" type (ignoring qualifiers at the top level) 6804 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6805 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6806 6807 // In C++, the types have to match exactly. 6808 if (S.getLangOpts().CPlusPlus) 6809 return Sema::IncompatibleBlockPointer; 6810 6811 Sema::AssignConvertType ConvTy = Sema::Compatible; 6812 6813 // For blocks we enforce that qualifiers are identical. 6814 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6815 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6816 6817 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6818 return Sema::IncompatibleBlockPointer; 6819 6820 return ConvTy; 6821 } 6822 6823 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6824 /// for assignment compatibility. 6825 static Sema::AssignConvertType 6826 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6827 QualType RHSType) { 6828 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6829 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6830 6831 if (LHSType->isObjCBuiltinType()) { 6832 // Class is not compatible with ObjC object pointers. 6833 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6834 !RHSType->isObjCQualifiedClassType()) 6835 return Sema::IncompatiblePointer; 6836 return Sema::Compatible; 6837 } 6838 if (RHSType->isObjCBuiltinType()) { 6839 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6840 !LHSType->isObjCQualifiedClassType()) 6841 return Sema::IncompatiblePointer; 6842 return Sema::Compatible; 6843 } 6844 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6845 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6846 6847 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6848 // make an exception for id<P> 6849 !LHSType->isObjCQualifiedIdType()) 6850 return Sema::CompatiblePointerDiscardsQualifiers; 6851 6852 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6853 return Sema::Compatible; 6854 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6855 return Sema::IncompatibleObjCQualifiedId; 6856 return Sema::IncompatiblePointer; 6857 } 6858 6859 Sema::AssignConvertType 6860 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6861 QualType LHSType, QualType RHSType) { 6862 // Fake up an opaque expression. We don't actually care about what 6863 // cast operations are required, so if CheckAssignmentConstraints 6864 // adds casts to this they'll be wasted, but fortunately that doesn't 6865 // usually happen on valid code. 6866 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6867 ExprResult RHSPtr = &RHSExpr; 6868 CastKind K = CK_Invalid; 6869 6870 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 6871 } 6872 6873 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6874 /// has code to accommodate several GCC extensions when type checking 6875 /// pointers. Here are some objectionable examples that GCC considers warnings: 6876 /// 6877 /// int a, *pint; 6878 /// short *pshort; 6879 /// struct foo *pfoo; 6880 /// 6881 /// pint = pshort; // warning: assignment from incompatible pointer type 6882 /// a = pint; // warning: assignment makes integer from pointer without a cast 6883 /// pint = a; // warning: assignment makes pointer from integer without a cast 6884 /// pint = pfoo; // warning: assignment from incompatible pointer type 6885 /// 6886 /// As a result, the code for dealing with pointers is more complex than the 6887 /// C99 spec dictates. 6888 /// 6889 /// Sets 'Kind' for any result kind except Incompatible. 6890 Sema::AssignConvertType 6891 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6892 CastKind &Kind, bool ConvertRHS) { 6893 QualType RHSType = RHS.get()->getType(); 6894 QualType OrigLHSType = LHSType; 6895 6896 // Get canonical types. We're not formatting these types, just comparing 6897 // them. 6898 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6899 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6900 6901 // Common case: no conversion required. 6902 if (LHSType == RHSType) { 6903 Kind = CK_NoOp; 6904 return Compatible; 6905 } 6906 6907 // If we have an atomic type, try a non-atomic assignment, then just add an 6908 // atomic qualification step. 6909 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6910 Sema::AssignConvertType result = 6911 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6912 if (result != Compatible) 6913 return result; 6914 if (Kind != CK_NoOp && ConvertRHS) 6915 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 6916 Kind = CK_NonAtomicToAtomic; 6917 return Compatible; 6918 } 6919 6920 // If the left-hand side is a reference type, then we are in a 6921 // (rare!) case where we've allowed the use of references in C, 6922 // e.g., as a parameter type in a built-in function. In this case, 6923 // just make sure that the type referenced is compatible with the 6924 // right-hand side type. The caller is responsible for adjusting 6925 // LHSType so that the resulting expression does not have reference 6926 // type. 6927 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6928 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6929 Kind = CK_LValueBitCast; 6930 return Compatible; 6931 } 6932 return Incompatible; 6933 } 6934 6935 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6936 // to the same ExtVector type. 6937 if (LHSType->isExtVectorType()) { 6938 if (RHSType->isExtVectorType()) 6939 return Incompatible; 6940 if (RHSType->isArithmeticType()) { 6941 // CK_VectorSplat does T -> vector T, so first cast to the 6942 // element type. 6943 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6944 if (elType != RHSType && ConvertRHS) { 6945 Kind = PrepareScalarCast(RHS, elType); 6946 RHS = ImpCastExprToType(RHS.get(), elType, Kind); 6947 } 6948 Kind = CK_VectorSplat; 6949 return Compatible; 6950 } 6951 } 6952 6953 // Conversions to or from vector type. 6954 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6955 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6956 // Allow assignments of an AltiVec vector type to an equivalent GCC 6957 // vector type and vice versa 6958 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6959 Kind = CK_BitCast; 6960 return Compatible; 6961 } 6962 6963 // If we are allowing lax vector conversions, and LHS and RHS are both 6964 // vectors, the total size only needs to be the same. This is a bitcast; 6965 // no bits are changed but the result type is different. 6966 if (isLaxVectorConversion(RHSType, LHSType)) { 6967 Kind = CK_BitCast; 6968 return IncompatibleVectors; 6969 } 6970 } 6971 return Incompatible; 6972 } 6973 6974 // Arithmetic conversions. 6975 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6976 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6977 if (ConvertRHS) 6978 Kind = PrepareScalarCast(RHS, LHSType); 6979 return Compatible; 6980 } 6981 6982 // Conversions to normal pointers. 6983 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6984 // U* -> T* 6985 if (isa<PointerType>(RHSType)) { 6986 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 6987 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 6988 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 6989 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6990 } 6991 6992 // int -> T* 6993 if (RHSType->isIntegerType()) { 6994 Kind = CK_IntegralToPointer; // FIXME: null? 6995 return IntToPointer; 6996 } 6997 6998 // C pointers are not compatible with ObjC object pointers, 6999 // with two exceptions: 7000 if (isa<ObjCObjectPointerType>(RHSType)) { 7001 // - conversions to void* 7002 if (LHSPointer->getPointeeType()->isVoidType()) { 7003 Kind = CK_BitCast; 7004 return Compatible; 7005 } 7006 7007 // - conversions from 'Class' to the redefinition type 7008 if (RHSType->isObjCClassType() && 7009 Context.hasSameType(LHSType, 7010 Context.getObjCClassRedefinitionType())) { 7011 Kind = CK_BitCast; 7012 return Compatible; 7013 } 7014 7015 Kind = CK_BitCast; 7016 return IncompatiblePointer; 7017 } 7018 7019 // U^ -> void* 7020 if (RHSType->getAs<BlockPointerType>()) { 7021 if (LHSPointer->getPointeeType()->isVoidType()) { 7022 Kind = CK_BitCast; 7023 return Compatible; 7024 } 7025 } 7026 7027 return Incompatible; 7028 } 7029 7030 // Conversions to block pointers. 7031 if (isa<BlockPointerType>(LHSType)) { 7032 // U^ -> T^ 7033 if (RHSType->isBlockPointerType()) { 7034 Kind = CK_BitCast; 7035 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7036 } 7037 7038 // int or null -> T^ 7039 if (RHSType->isIntegerType()) { 7040 Kind = CK_IntegralToPointer; // FIXME: null 7041 return IntToBlockPointer; 7042 } 7043 7044 // id -> T^ 7045 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7046 Kind = CK_AnyPointerToBlockPointerCast; 7047 return Compatible; 7048 } 7049 7050 // void* -> T^ 7051 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7052 if (RHSPT->getPointeeType()->isVoidType()) { 7053 Kind = CK_AnyPointerToBlockPointerCast; 7054 return Compatible; 7055 } 7056 7057 return Incompatible; 7058 } 7059 7060 // Conversions to Objective-C pointers. 7061 if (isa<ObjCObjectPointerType>(LHSType)) { 7062 // A* -> B* 7063 if (RHSType->isObjCObjectPointerType()) { 7064 Kind = CK_BitCast; 7065 Sema::AssignConvertType result = 7066 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7067 if (getLangOpts().ObjCAutoRefCount && 7068 result == Compatible && 7069 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7070 result = IncompatibleObjCWeakRef; 7071 return result; 7072 } 7073 7074 // int or null -> A* 7075 if (RHSType->isIntegerType()) { 7076 Kind = CK_IntegralToPointer; // FIXME: null 7077 return IntToPointer; 7078 } 7079 7080 // In general, C pointers are not compatible with ObjC object pointers, 7081 // with two exceptions: 7082 if (isa<PointerType>(RHSType)) { 7083 Kind = CK_CPointerToObjCPointerCast; 7084 7085 // - conversions from 'void*' 7086 if (RHSType->isVoidPointerType()) { 7087 return Compatible; 7088 } 7089 7090 // - conversions to 'Class' from its redefinition type 7091 if (LHSType->isObjCClassType() && 7092 Context.hasSameType(RHSType, 7093 Context.getObjCClassRedefinitionType())) { 7094 return Compatible; 7095 } 7096 7097 return IncompatiblePointer; 7098 } 7099 7100 // Only under strict condition T^ is compatible with an Objective-C pointer. 7101 if (RHSType->isBlockPointerType() && 7102 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7103 if (ConvertRHS) 7104 maybeExtendBlockObject(RHS); 7105 Kind = CK_BlockPointerToObjCPointerCast; 7106 return Compatible; 7107 } 7108 7109 return Incompatible; 7110 } 7111 7112 // Conversions from pointers that are not covered by the above. 7113 if (isa<PointerType>(RHSType)) { 7114 // T* -> _Bool 7115 if (LHSType == Context.BoolTy) { 7116 Kind = CK_PointerToBoolean; 7117 return Compatible; 7118 } 7119 7120 // T* -> int 7121 if (LHSType->isIntegerType()) { 7122 Kind = CK_PointerToIntegral; 7123 return PointerToInt; 7124 } 7125 7126 return Incompatible; 7127 } 7128 7129 // Conversions from Objective-C pointers that are not covered by the above. 7130 if (isa<ObjCObjectPointerType>(RHSType)) { 7131 // T* -> _Bool 7132 if (LHSType == Context.BoolTy) { 7133 Kind = CK_PointerToBoolean; 7134 return Compatible; 7135 } 7136 7137 // T* -> int 7138 if (LHSType->isIntegerType()) { 7139 Kind = CK_PointerToIntegral; 7140 return PointerToInt; 7141 } 7142 7143 return Incompatible; 7144 } 7145 7146 // struct A -> struct B 7147 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7148 if (Context.typesAreCompatible(LHSType, RHSType)) { 7149 Kind = CK_NoOp; 7150 return Compatible; 7151 } 7152 } 7153 7154 return Incompatible; 7155 } 7156 7157 /// \brief Constructs a transparent union from an expression that is 7158 /// used to initialize the transparent union. 7159 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7160 ExprResult &EResult, QualType UnionType, 7161 FieldDecl *Field) { 7162 // Build an initializer list that designates the appropriate member 7163 // of the transparent union. 7164 Expr *E = EResult.get(); 7165 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7166 E, SourceLocation()); 7167 Initializer->setType(UnionType); 7168 Initializer->setInitializedFieldInUnion(Field); 7169 7170 // Build a compound literal constructing a value of the transparent 7171 // union type from this initializer list. 7172 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7173 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7174 VK_RValue, Initializer, false); 7175 } 7176 7177 Sema::AssignConvertType 7178 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7179 ExprResult &RHS) { 7180 QualType RHSType = RHS.get()->getType(); 7181 7182 // If the ArgType is a Union type, we want to handle a potential 7183 // transparent_union GCC extension. 7184 const RecordType *UT = ArgType->getAsUnionType(); 7185 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7186 return Incompatible; 7187 7188 // The field to initialize within the transparent union. 7189 RecordDecl *UD = UT->getDecl(); 7190 FieldDecl *InitField = nullptr; 7191 // It's compatible if the expression matches any of the fields. 7192 for (auto *it : UD->fields()) { 7193 if (it->getType()->isPointerType()) { 7194 // If the transparent union contains a pointer type, we allow: 7195 // 1) void pointer 7196 // 2) null pointer constant 7197 if (RHSType->isPointerType()) 7198 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7199 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7200 InitField = it; 7201 break; 7202 } 7203 7204 if (RHS.get()->isNullPointerConstant(Context, 7205 Expr::NPC_ValueDependentIsNull)) { 7206 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7207 CK_NullToPointer); 7208 InitField = it; 7209 break; 7210 } 7211 } 7212 7213 CastKind Kind = CK_Invalid; 7214 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7215 == Compatible) { 7216 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7217 InitField = it; 7218 break; 7219 } 7220 } 7221 7222 if (!InitField) 7223 return Incompatible; 7224 7225 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7226 return Compatible; 7227 } 7228 7229 Sema::AssignConvertType 7230 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7231 bool Diagnose, 7232 bool DiagnoseCFAudited, 7233 bool ConvertRHS) { 7234 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7235 // we can't avoid *all* modifications at the moment, so we need some somewhere 7236 // to put the updated value. 7237 ExprResult LocalRHS = CallerRHS; 7238 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7239 7240 if (getLangOpts().CPlusPlus) { 7241 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7242 // C++ 5.17p3: If the left operand is not of class type, the 7243 // expression is implicitly converted (C++ 4) to the 7244 // cv-unqualified type of the left operand. 7245 ExprResult Res; 7246 if (Diagnose) { 7247 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7248 AA_Assigning); 7249 } else { 7250 ImplicitConversionSequence ICS = 7251 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7252 /*SuppressUserConversions=*/false, 7253 /*AllowExplicit=*/false, 7254 /*InOverloadResolution=*/false, 7255 /*CStyle=*/false, 7256 /*AllowObjCWritebackConversion=*/false); 7257 if (ICS.isFailure()) 7258 return Incompatible; 7259 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7260 ICS, AA_Assigning); 7261 } 7262 if (Res.isInvalid()) 7263 return Incompatible; 7264 Sema::AssignConvertType result = Compatible; 7265 if (getLangOpts().ObjCAutoRefCount && 7266 !CheckObjCARCUnavailableWeakConversion(LHSType, 7267 RHS.get()->getType())) 7268 result = IncompatibleObjCWeakRef; 7269 RHS = Res; 7270 return result; 7271 } 7272 7273 // FIXME: Currently, we fall through and treat C++ classes like C 7274 // structures. 7275 // FIXME: We also fall through for atomics; not sure what should 7276 // happen there, though. 7277 } else if (RHS.get()->getType() == Context.OverloadTy) { 7278 // As a set of extensions to C, we support overloading on functions. These 7279 // functions need to be resolved here. 7280 DeclAccessPair DAP; 7281 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7282 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7283 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7284 else 7285 return Incompatible; 7286 } 7287 7288 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7289 // a null pointer constant. 7290 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7291 LHSType->isBlockPointerType()) && 7292 RHS.get()->isNullPointerConstant(Context, 7293 Expr::NPC_ValueDependentIsNull)) { 7294 CastKind Kind; 7295 CXXCastPath Path; 7296 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 7297 if (ConvertRHS) 7298 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7299 return Compatible; 7300 } 7301 7302 // This check seems unnatural, however it is necessary to ensure the proper 7303 // conversion of functions/arrays. If the conversion were done for all 7304 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7305 // expressions that suppress this implicit conversion (&, sizeof). 7306 // 7307 // Suppress this for references: C++ 8.5.3p5. 7308 if (!LHSType->isReferenceType()) { 7309 // FIXME: We potentially allocate here even if ConvertRHS is false. 7310 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7311 if (RHS.isInvalid()) 7312 return Incompatible; 7313 } 7314 7315 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7316 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) { 7317 ObjCProtocolDecl *PDecl = OPE->getProtocol(); 7318 if (PDecl && !PDecl->hasDefinition()) { 7319 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7320 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7321 } 7322 } 7323 7324 CastKind Kind = CK_Invalid; 7325 Sema::AssignConvertType result = 7326 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7327 7328 // C99 6.5.16.1p2: The value of the right operand is converted to the 7329 // type of the assignment expression. 7330 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7331 // so that we can use references in built-in functions even in C. 7332 // The getNonReferenceType() call makes sure that the resulting expression 7333 // does not have reference type. 7334 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7335 QualType Ty = LHSType.getNonLValueExprType(Context); 7336 Expr *E = RHS.get(); 7337 if (getLangOpts().ObjCAutoRefCount) 7338 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7339 DiagnoseCFAudited); 7340 if (getLangOpts().ObjC1 && 7341 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 7342 LHSType, E->getType(), E) || 7343 ConversionToObjCStringLiteralCheck(LHSType, E))) { 7344 RHS = E; 7345 return Compatible; 7346 } 7347 7348 if (ConvertRHS) 7349 RHS = ImpCastExprToType(E, Ty, Kind); 7350 } 7351 return result; 7352 } 7353 7354 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7355 ExprResult &RHS) { 7356 Diag(Loc, diag::err_typecheck_invalid_operands) 7357 << LHS.get()->getType() << RHS.get()->getType() 7358 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7359 return QualType(); 7360 } 7361 7362 /// Try to convert a value of non-vector type to a vector type by converting 7363 /// the type to the element type of the vector and then performing a splat. 7364 /// If the language is OpenCL, we only use conversions that promote scalar 7365 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7366 /// for float->int. 7367 /// 7368 /// \param scalar - if non-null, actually perform the conversions 7369 /// \return true if the operation fails (but without diagnosing the failure) 7370 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7371 QualType scalarTy, 7372 QualType vectorEltTy, 7373 QualType vectorTy) { 7374 // The conversion to apply to the scalar before splatting it, 7375 // if necessary. 7376 CastKind scalarCast = CK_Invalid; 7377 7378 if (vectorEltTy->isIntegralType(S.Context)) { 7379 if (!scalarTy->isIntegralType(S.Context)) 7380 return true; 7381 if (S.getLangOpts().OpenCL && 7382 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7383 return true; 7384 scalarCast = CK_IntegralCast; 7385 } else if (vectorEltTy->isRealFloatingType()) { 7386 if (scalarTy->isRealFloatingType()) { 7387 if (S.getLangOpts().OpenCL && 7388 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7389 return true; 7390 scalarCast = CK_FloatingCast; 7391 } 7392 else if (scalarTy->isIntegralType(S.Context)) 7393 scalarCast = CK_IntegralToFloating; 7394 else 7395 return true; 7396 } else { 7397 return true; 7398 } 7399 7400 // Adjust scalar if desired. 7401 if (scalar) { 7402 if (scalarCast != CK_Invalid) 7403 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7404 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7405 } 7406 return false; 7407 } 7408 7409 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7410 SourceLocation Loc, bool IsCompAssign, 7411 bool AllowBothBool, 7412 bool AllowBoolConversions) { 7413 if (!IsCompAssign) { 7414 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7415 if (LHS.isInvalid()) 7416 return QualType(); 7417 } 7418 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7419 if (RHS.isInvalid()) 7420 return QualType(); 7421 7422 // For conversion purposes, we ignore any qualifiers. 7423 // For example, "const float" and "float" are equivalent. 7424 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7425 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7426 7427 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7428 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7429 assert(LHSVecType || RHSVecType); 7430 7431 // AltiVec-style "vector bool op vector bool" combinations are allowed 7432 // for some operators but not others. 7433 if (!AllowBothBool && 7434 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7435 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7436 return InvalidOperands(Loc, LHS, RHS); 7437 7438 // If the vector types are identical, return. 7439 if (Context.hasSameType(LHSType, RHSType)) 7440 return LHSType; 7441 7442 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7443 if (LHSVecType && RHSVecType && 7444 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7445 if (isa<ExtVectorType>(LHSVecType)) { 7446 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7447 return LHSType; 7448 } 7449 7450 if (!IsCompAssign) 7451 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7452 return RHSType; 7453 } 7454 7455 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7456 // can be mixed, with the result being the non-bool type. The non-bool 7457 // operand must have integer element type. 7458 if (AllowBoolConversions && LHSVecType && RHSVecType && 7459 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7460 (Context.getTypeSize(LHSVecType->getElementType()) == 7461 Context.getTypeSize(RHSVecType->getElementType()))) { 7462 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7463 LHSVecType->getElementType()->isIntegerType() && 7464 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7465 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7466 return LHSType; 7467 } 7468 if (!IsCompAssign && 7469 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7470 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7471 RHSVecType->getElementType()->isIntegerType()) { 7472 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7473 return RHSType; 7474 } 7475 } 7476 7477 // If there's an ext-vector type and a scalar, try to convert the scalar to 7478 // the vector element type and splat. 7479 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7480 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7481 LHSVecType->getElementType(), LHSType)) 7482 return LHSType; 7483 } 7484 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7485 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7486 LHSType, RHSVecType->getElementType(), 7487 RHSType)) 7488 return RHSType; 7489 } 7490 7491 // If we're allowing lax vector conversions, only the total (data) size 7492 // needs to be the same. 7493 // FIXME: Should we really be allowing this? 7494 // FIXME: We really just pick the LHS type arbitrarily? 7495 if (isLaxVectorConversion(RHSType, LHSType)) { 7496 QualType resultType = LHSType; 7497 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7498 return resultType; 7499 } 7500 7501 // Okay, the expression is invalid. 7502 7503 // If there's a non-vector, non-real operand, diagnose that. 7504 if ((!RHSVecType && !RHSType->isRealType()) || 7505 (!LHSVecType && !LHSType->isRealType())) { 7506 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7507 << LHSType << RHSType 7508 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7509 return QualType(); 7510 } 7511 7512 // OpenCL V1.1 6.2.6.p1: 7513 // If the operands are of more than one vector type, then an error shall 7514 // occur. Implicit conversions between vector types are not permitted, per 7515 // section 6.2.1. 7516 if (getLangOpts().OpenCL && 7517 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7518 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7519 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7520 << RHSType; 7521 return QualType(); 7522 } 7523 7524 // Otherwise, use the generic diagnostic. 7525 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7526 << LHSType << RHSType 7527 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7528 return QualType(); 7529 } 7530 7531 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7532 // expression. These are mainly cases where the null pointer is used as an 7533 // integer instead of a pointer. 7534 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7535 SourceLocation Loc, bool IsCompare) { 7536 // The canonical way to check for a GNU null is with isNullPointerConstant, 7537 // but we use a bit of a hack here for speed; this is a relatively 7538 // hot path, and isNullPointerConstant is slow. 7539 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7540 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7541 7542 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7543 7544 // Avoid analyzing cases where the result will either be invalid (and 7545 // diagnosed as such) or entirely valid and not something to warn about. 7546 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7547 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7548 return; 7549 7550 // Comparison operations would not make sense with a null pointer no matter 7551 // what the other expression is. 7552 if (!IsCompare) { 7553 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7554 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7555 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7556 return; 7557 } 7558 7559 // The rest of the operations only make sense with a null pointer 7560 // if the other expression is a pointer. 7561 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7562 NonNullType->canDecayToPointerType()) 7563 return; 7564 7565 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7566 << LHSNull /* LHS is NULL */ << NonNullType 7567 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7568 } 7569 7570 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7571 ExprResult &RHS, 7572 SourceLocation Loc, bool IsDiv) { 7573 // Check for division/remainder by zero. 7574 unsigned Diag = (IsDiv) ? diag::warn_division_by_zero : 7575 diag::warn_remainder_by_zero; 7576 llvm::APSInt RHSValue; 7577 if (!RHS.get()->isValueDependent() && 7578 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7579 S.DiagRuntimeBehavior(Loc, RHS.get(), 7580 S.PDiag(Diag) << RHS.get()->getSourceRange()); 7581 } 7582 7583 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7584 SourceLocation Loc, 7585 bool IsCompAssign, bool IsDiv) { 7586 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7587 7588 if (LHS.get()->getType()->isVectorType() || 7589 RHS.get()->getType()->isVectorType()) 7590 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7591 /*AllowBothBool*/getLangOpts().AltiVec, 7592 /*AllowBoolConversions*/false); 7593 7594 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7595 if (LHS.isInvalid() || RHS.isInvalid()) 7596 return QualType(); 7597 7598 7599 if (compType.isNull() || !compType->isArithmeticType()) 7600 return InvalidOperands(Loc, LHS, RHS); 7601 if (IsDiv) 7602 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7603 return compType; 7604 } 7605 7606 QualType Sema::CheckRemainderOperands( 7607 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7608 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7609 7610 if (LHS.get()->getType()->isVectorType() || 7611 RHS.get()->getType()->isVectorType()) { 7612 if (LHS.get()->getType()->hasIntegerRepresentation() && 7613 RHS.get()->getType()->hasIntegerRepresentation()) 7614 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7615 /*AllowBothBool*/getLangOpts().AltiVec, 7616 /*AllowBoolConversions*/false); 7617 return InvalidOperands(Loc, LHS, RHS); 7618 } 7619 7620 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7621 if (LHS.isInvalid() || RHS.isInvalid()) 7622 return QualType(); 7623 7624 if (compType.isNull() || !compType->isIntegerType()) 7625 return InvalidOperands(Loc, LHS, RHS); 7626 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 7627 return compType; 7628 } 7629 7630 /// \brief Diagnose invalid arithmetic on two void pointers. 7631 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7632 Expr *LHSExpr, Expr *RHSExpr) { 7633 S.Diag(Loc, S.getLangOpts().CPlusPlus 7634 ? diag::err_typecheck_pointer_arith_void_type 7635 : diag::ext_gnu_void_ptr) 7636 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7637 << RHSExpr->getSourceRange(); 7638 } 7639 7640 /// \brief Diagnose invalid arithmetic on a void pointer. 7641 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7642 Expr *Pointer) { 7643 S.Diag(Loc, S.getLangOpts().CPlusPlus 7644 ? diag::err_typecheck_pointer_arith_void_type 7645 : diag::ext_gnu_void_ptr) 7646 << 0 /* one pointer */ << Pointer->getSourceRange(); 7647 } 7648 7649 /// \brief Diagnose invalid arithmetic on two function pointers. 7650 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7651 Expr *LHS, Expr *RHS) { 7652 assert(LHS->getType()->isAnyPointerType()); 7653 assert(RHS->getType()->isAnyPointerType()); 7654 S.Diag(Loc, S.getLangOpts().CPlusPlus 7655 ? diag::err_typecheck_pointer_arith_function_type 7656 : diag::ext_gnu_ptr_func_arith) 7657 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7658 // We only show the second type if it differs from the first. 7659 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7660 RHS->getType()) 7661 << RHS->getType()->getPointeeType() 7662 << LHS->getSourceRange() << RHS->getSourceRange(); 7663 } 7664 7665 /// \brief Diagnose invalid arithmetic on a function pointer. 7666 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7667 Expr *Pointer) { 7668 assert(Pointer->getType()->isAnyPointerType()); 7669 S.Diag(Loc, S.getLangOpts().CPlusPlus 7670 ? diag::err_typecheck_pointer_arith_function_type 7671 : diag::ext_gnu_ptr_func_arith) 7672 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7673 << 0 /* one pointer, so only one type */ 7674 << Pointer->getSourceRange(); 7675 } 7676 7677 /// \brief Emit error if Operand is incomplete pointer type 7678 /// 7679 /// \returns True if pointer has incomplete type 7680 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7681 Expr *Operand) { 7682 QualType ResType = Operand->getType(); 7683 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7684 ResType = ResAtomicType->getValueType(); 7685 7686 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7687 QualType PointeeTy = ResType->getPointeeType(); 7688 return S.RequireCompleteType(Loc, PointeeTy, 7689 diag::err_typecheck_arithmetic_incomplete_type, 7690 PointeeTy, Operand->getSourceRange()); 7691 } 7692 7693 /// \brief Check the validity of an arithmetic pointer operand. 7694 /// 7695 /// If the operand has pointer type, this code will check for pointer types 7696 /// which are invalid in arithmetic operations. These will be diagnosed 7697 /// appropriately, including whether or not the use is supported as an 7698 /// extension. 7699 /// 7700 /// \returns True when the operand is valid to use (even if as an extension). 7701 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7702 Expr *Operand) { 7703 QualType ResType = Operand->getType(); 7704 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7705 ResType = ResAtomicType->getValueType(); 7706 7707 if (!ResType->isAnyPointerType()) return true; 7708 7709 QualType PointeeTy = ResType->getPointeeType(); 7710 if (PointeeTy->isVoidType()) { 7711 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7712 return !S.getLangOpts().CPlusPlus; 7713 } 7714 if (PointeeTy->isFunctionType()) { 7715 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7716 return !S.getLangOpts().CPlusPlus; 7717 } 7718 7719 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7720 7721 return true; 7722 } 7723 7724 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7725 /// operands. 7726 /// 7727 /// This routine will diagnose any invalid arithmetic on pointer operands much 7728 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7729 /// for emitting a single diagnostic even for operations where both LHS and RHS 7730 /// are (potentially problematic) pointers. 7731 /// 7732 /// \returns True when the operand is valid to use (even if as an extension). 7733 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7734 Expr *LHSExpr, Expr *RHSExpr) { 7735 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7736 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7737 if (!isLHSPointer && !isRHSPointer) return true; 7738 7739 QualType LHSPointeeTy, RHSPointeeTy; 7740 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7741 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7742 7743 // if both are pointers check if operation is valid wrt address spaces 7744 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 7745 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 7746 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 7747 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 7748 S.Diag(Loc, 7749 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7750 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 7751 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7752 return false; 7753 } 7754 } 7755 7756 // Check for arithmetic on pointers to incomplete types. 7757 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7758 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7759 if (isLHSVoidPtr || isRHSVoidPtr) { 7760 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7761 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7762 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7763 7764 return !S.getLangOpts().CPlusPlus; 7765 } 7766 7767 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7768 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7769 if (isLHSFuncPtr || isRHSFuncPtr) { 7770 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7771 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7772 RHSExpr); 7773 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7774 7775 return !S.getLangOpts().CPlusPlus; 7776 } 7777 7778 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7779 return false; 7780 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7781 return false; 7782 7783 return true; 7784 } 7785 7786 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7787 /// literal. 7788 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7789 Expr *LHSExpr, Expr *RHSExpr) { 7790 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7791 Expr* IndexExpr = RHSExpr; 7792 if (!StrExpr) { 7793 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7794 IndexExpr = LHSExpr; 7795 } 7796 7797 bool IsStringPlusInt = StrExpr && 7798 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7799 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 7800 return; 7801 7802 llvm::APSInt index; 7803 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7804 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7805 if (index.isNonNegative() && 7806 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7807 index.isUnsigned())) 7808 return; 7809 } 7810 7811 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7812 Self.Diag(OpLoc, diag::warn_string_plus_int) 7813 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7814 7815 // Only print a fixit for "str" + int, not for int + "str". 7816 if (IndexExpr == RHSExpr) { 7817 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7818 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7819 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7820 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7821 << FixItHint::CreateInsertion(EndLoc, "]"); 7822 } else 7823 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7824 } 7825 7826 /// \brief Emit a warning when adding a char literal to a string. 7827 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7828 Expr *LHSExpr, Expr *RHSExpr) { 7829 const Expr *StringRefExpr = LHSExpr; 7830 const CharacterLiteral *CharExpr = 7831 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7832 7833 if (!CharExpr) { 7834 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7835 StringRefExpr = RHSExpr; 7836 } 7837 7838 if (!CharExpr || !StringRefExpr) 7839 return; 7840 7841 const QualType StringType = StringRefExpr->getType(); 7842 7843 // Return if not a PointerType. 7844 if (!StringType->isAnyPointerType()) 7845 return; 7846 7847 // Return if not a CharacterType. 7848 if (!StringType->getPointeeType()->isAnyCharacterType()) 7849 return; 7850 7851 ASTContext &Ctx = Self.getASTContext(); 7852 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7853 7854 const QualType CharType = CharExpr->getType(); 7855 if (!CharType->isAnyCharacterType() && 7856 CharType->isIntegerType() && 7857 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7858 Self.Diag(OpLoc, diag::warn_string_plus_char) 7859 << DiagRange << Ctx.CharTy; 7860 } else { 7861 Self.Diag(OpLoc, diag::warn_string_plus_char) 7862 << DiagRange << CharExpr->getType(); 7863 } 7864 7865 // Only print a fixit for str + char, not for char + str. 7866 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7867 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7868 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7869 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7870 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7871 << FixItHint::CreateInsertion(EndLoc, "]"); 7872 } else { 7873 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7874 } 7875 } 7876 7877 /// \brief Emit error when two pointers are incompatible. 7878 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7879 Expr *LHSExpr, Expr *RHSExpr) { 7880 assert(LHSExpr->getType()->isAnyPointerType()); 7881 assert(RHSExpr->getType()->isAnyPointerType()); 7882 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7883 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7884 << RHSExpr->getSourceRange(); 7885 } 7886 7887 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7888 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7889 QualType* CompLHSTy) { 7890 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7891 7892 if (LHS.get()->getType()->isVectorType() || 7893 RHS.get()->getType()->isVectorType()) { 7894 QualType compType = CheckVectorOperands( 7895 LHS, RHS, Loc, CompLHSTy, 7896 /*AllowBothBool*/getLangOpts().AltiVec, 7897 /*AllowBoolConversions*/getLangOpts().ZVector); 7898 if (CompLHSTy) *CompLHSTy = compType; 7899 return compType; 7900 } 7901 7902 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7903 if (LHS.isInvalid() || RHS.isInvalid()) 7904 return QualType(); 7905 7906 // Diagnose "string literal" '+' int and string '+' "char literal". 7907 if (Opc == BO_Add) { 7908 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7909 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7910 } 7911 7912 // handle the common case first (both operands are arithmetic). 7913 if (!compType.isNull() && compType->isArithmeticType()) { 7914 if (CompLHSTy) *CompLHSTy = compType; 7915 return compType; 7916 } 7917 7918 // Type-checking. Ultimately the pointer's going to be in PExp; 7919 // note that we bias towards the LHS being the pointer. 7920 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7921 7922 bool isObjCPointer; 7923 if (PExp->getType()->isPointerType()) { 7924 isObjCPointer = false; 7925 } else if (PExp->getType()->isObjCObjectPointerType()) { 7926 isObjCPointer = true; 7927 } else { 7928 std::swap(PExp, IExp); 7929 if (PExp->getType()->isPointerType()) { 7930 isObjCPointer = false; 7931 } else if (PExp->getType()->isObjCObjectPointerType()) { 7932 isObjCPointer = true; 7933 } else { 7934 return InvalidOperands(Loc, LHS, RHS); 7935 } 7936 } 7937 assert(PExp->getType()->isAnyPointerType()); 7938 7939 if (!IExp->getType()->isIntegerType()) 7940 return InvalidOperands(Loc, LHS, RHS); 7941 7942 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7943 return QualType(); 7944 7945 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7946 return QualType(); 7947 7948 // Check array bounds for pointer arithemtic 7949 CheckArrayAccess(PExp, IExp); 7950 7951 if (CompLHSTy) { 7952 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7953 if (LHSTy.isNull()) { 7954 LHSTy = LHS.get()->getType(); 7955 if (LHSTy->isPromotableIntegerType()) 7956 LHSTy = Context.getPromotedIntegerType(LHSTy); 7957 } 7958 *CompLHSTy = LHSTy; 7959 } 7960 7961 return PExp->getType(); 7962 } 7963 7964 // C99 6.5.6 7965 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7966 SourceLocation Loc, 7967 QualType* CompLHSTy) { 7968 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7969 7970 if (LHS.get()->getType()->isVectorType() || 7971 RHS.get()->getType()->isVectorType()) { 7972 QualType compType = CheckVectorOperands( 7973 LHS, RHS, Loc, CompLHSTy, 7974 /*AllowBothBool*/getLangOpts().AltiVec, 7975 /*AllowBoolConversions*/getLangOpts().ZVector); 7976 if (CompLHSTy) *CompLHSTy = compType; 7977 return compType; 7978 } 7979 7980 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7981 if (LHS.isInvalid() || RHS.isInvalid()) 7982 return QualType(); 7983 7984 // Enforce type constraints: C99 6.5.6p3. 7985 7986 // Handle the common case first (both operands are arithmetic). 7987 if (!compType.isNull() && compType->isArithmeticType()) { 7988 if (CompLHSTy) *CompLHSTy = compType; 7989 return compType; 7990 } 7991 7992 // Either ptr - int or ptr - ptr. 7993 if (LHS.get()->getType()->isAnyPointerType()) { 7994 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7995 7996 // Diagnose bad cases where we step over interface counts. 7997 if (LHS.get()->getType()->isObjCObjectPointerType() && 7998 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7999 return QualType(); 8000 8001 // The result type of a pointer-int computation is the pointer type. 8002 if (RHS.get()->getType()->isIntegerType()) { 8003 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8004 return QualType(); 8005 8006 // Check array bounds for pointer arithemtic 8007 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8008 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8009 8010 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8011 return LHS.get()->getType(); 8012 } 8013 8014 // Handle pointer-pointer subtractions. 8015 if (const PointerType *RHSPTy 8016 = RHS.get()->getType()->getAs<PointerType>()) { 8017 QualType rpointee = RHSPTy->getPointeeType(); 8018 8019 if (getLangOpts().CPlusPlus) { 8020 // Pointee types must be the same: C++ [expr.add] 8021 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8022 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8023 } 8024 } else { 8025 // Pointee types must be compatible C99 6.5.6p3 8026 if (!Context.typesAreCompatible( 8027 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8028 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8029 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8030 return QualType(); 8031 } 8032 } 8033 8034 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8035 LHS.get(), RHS.get())) 8036 return QualType(); 8037 8038 // The pointee type may have zero size. As an extension, a structure or 8039 // union may have zero size or an array may have zero length. In this 8040 // case subtraction does not make sense. 8041 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8042 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8043 if (ElementSize.isZero()) { 8044 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8045 << rpointee.getUnqualifiedType() 8046 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8047 } 8048 } 8049 8050 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8051 return Context.getPointerDiffType(); 8052 } 8053 } 8054 8055 return InvalidOperands(Loc, LHS, RHS); 8056 } 8057 8058 static bool isScopedEnumerationType(QualType T) { 8059 if (const EnumType *ET = T->getAs<EnumType>()) 8060 return ET->getDecl()->isScoped(); 8061 return false; 8062 } 8063 8064 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8065 SourceLocation Loc, unsigned Opc, 8066 QualType LHSType) { 8067 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8068 // so skip remaining warnings as we don't want to modify values within Sema. 8069 if (S.getLangOpts().OpenCL) 8070 return; 8071 8072 llvm::APSInt Right; 8073 // Check right/shifter operand 8074 if (RHS.get()->isValueDependent() || 8075 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8076 return; 8077 8078 if (Right.isNegative()) { 8079 S.DiagRuntimeBehavior(Loc, RHS.get(), 8080 S.PDiag(diag::warn_shift_negative) 8081 << RHS.get()->getSourceRange()); 8082 return; 8083 } 8084 llvm::APInt LeftBits(Right.getBitWidth(), 8085 S.Context.getTypeSize(LHS.get()->getType())); 8086 if (Right.uge(LeftBits)) { 8087 S.DiagRuntimeBehavior(Loc, RHS.get(), 8088 S.PDiag(diag::warn_shift_gt_typewidth) 8089 << RHS.get()->getSourceRange()); 8090 return; 8091 } 8092 if (Opc != BO_Shl) 8093 return; 8094 8095 // When left shifting an ICE which is signed, we can check for overflow which 8096 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8097 // integers have defined behavior modulo one more than the maximum value 8098 // representable in the result type, so never warn for those. 8099 llvm::APSInt Left; 8100 if (LHS.get()->isValueDependent() || 8101 LHSType->hasUnsignedIntegerRepresentation() || 8102 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8103 return; 8104 8105 // If LHS does not have a signed type and non-negative value 8106 // then, the behavior is undefined. Warn about it. 8107 if (Left.isNegative()) { 8108 S.DiagRuntimeBehavior(Loc, LHS.get(), 8109 S.PDiag(diag::warn_shift_lhs_negative) 8110 << LHS.get()->getSourceRange()); 8111 return; 8112 } 8113 8114 llvm::APInt ResultBits = 8115 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8116 if (LeftBits.uge(ResultBits)) 8117 return; 8118 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8119 Result = Result.shl(Right); 8120 8121 // Print the bit representation of the signed integer as an unsigned 8122 // hexadecimal number. 8123 SmallString<40> HexResult; 8124 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8125 8126 // If we are only missing a sign bit, this is less likely to result in actual 8127 // bugs -- if the result is cast back to an unsigned type, it will have the 8128 // expected value. Thus we place this behind a different warning that can be 8129 // turned off separately if needed. 8130 if (LeftBits == ResultBits - 1) { 8131 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8132 << HexResult << LHSType 8133 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8134 return; 8135 } 8136 8137 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8138 << HexResult.str() << Result.getMinSignedBits() << LHSType 8139 << Left.getBitWidth() << LHS.get()->getSourceRange() 8140 << RHS.get()->getSourceRange(); 8141 } 8142 8143 /// \brief Return the resulting type when an OpenCL vector is shifted 8144 /// by a scalar or vector shift amount. 8145 static QualType checkOpenCLVectorShift(Sema &S, 8146 ExprResult &LHS, ExprResult &RHS, 8147 SourceLocation Loc, bool IsCompAssign) { 8148 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8149 if (!LHS.get()->getType()->isVectorType()) { 8150 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8151 << RHS.get()->getType() << LHS.get()->getType() 8152 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8153 return QualType(); 8154 } 8155 8156 if (!IsCompAssign) { 8157 LHS = S.UsualUnaryConversions(LHS.get()); 8158 if (LHS.isInvalid()) return QualType(); 8159 } 8160 8161 RHS = S.UsualUnaryConversions(RHS.get()); 8162 if (RHS.isInvalid()) return QualType(); 8163 8164 QualType LHSType = LHS.get()->getType(); 8165 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8166 QualType LHSEleType = LHSVecTy->getElementType(); 8167 8168 // Note that RHS might not be a vector. 8169 QualType RHSType = RHS.get()->getType(); 8170 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8171 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8172 8173 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8174 if (!LHSEleType->isIntegerType()) { 8175 S.Diag(Loc, diag::err_typecheck_expect_int) 8176 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8177 return QualType(); 8178 } 8179 8180 if (!RHSEleType->isIntegerType()) { 8181 S.Diag(Loc, diag::err_typecheck_expect_int) 8182 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8183 return QualType(); 8184 } 8185 8186 if (RHSVecTy) { 8187 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8188 // are applied component-wise. So if RHS is a vector, then ensure 8189 // that the number of elements is the same as LHS... 8190 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8191 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8192 << LHS.get()->getType() << RHS.get()->getType() 8193 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8194 return QualType(); 8195 } 8196 } else { 8197 // ...else expand RHS to match the number of elements in LHS. 8198 QualType VecTy = 8199 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8200 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8201 } 8202 8203 return LHSType; 8204 } 8205 8206 // C99 6.5.7 8207 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8208 SourceLocation Loc, unsigned Opc, 8209 bool IsCompAssign) { 8210 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8211 8212 // Vector shifts promote their scalar inputs to vector type. 8213 if (LHS.get()->getType()->isVectorType() || 8214 RHS.get()->getType()->isVectorType()) { 8215 if (LangOpts.OpenCL) 8216 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8217 if (LangOpts.ZVector) { 8218 // The shift operators for the z vector extensions work basically 8219 // like OpenCL shifts, except that neither the LHS nor the RHS is 8220 // allowed to be a "vector bool". 8221 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8222 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8223 return InvalidOperands(Loc, LHS, RHS); 8224 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8225 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8226 return InvalidOperands(Loc, LHS, RHS); 8227 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8228 } 8229 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8230 /*AllowBothBool*/true, 8231 /*AllowBoolConversions*/false); 8232 } 8233 8234 // Shifts don't perform usual arithmetic conversions, they just do integer 8235 // promotions on each operand. C99 6.5.7p3 8236 8237 // For the LHS, do usual unary conversions, but then reset them away 8238 // if this is a compound assignment. 8239 ExprResult OldLHS = LHS; 8240 LHS = UsualUnaryConversions(LHS.get()); 8241 if (LHS.isInvalid()) 8242 return QualType(); 8243 QualType LHSType = LHS.get()->getType(); 8244 if (IsCompAssign) LHS = OldLHS; 8245 8246 // The RHS is simpler. 8247 RHS = UsualUnaryConversions(RHS.get()); 8248 if (RHS.isInvalid()) 8249 return QualType(); 8250 QualType RHSType = RHS.get()->getType(); 8251 8252 // C99 6.5.7p2: Each of the operands shall have integer type. 8253 if (!LHSType->hasIntegerRepresentation() || 8254 !RHSType->hasIntegerRepresentation()) 8255 return InvalidOperands(Loc, LHS, RHS); 8256 8257 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8258 // hasIntegerRepresentation() above instead of this. 8259 if (isScopedEnumerationType(LHSType) || 8260 isScopedEnumerationType(RHSType)) { 8261 return InvalidOperands(Loc, LHS, RHS); 8262 } 8263 // Sanity-check shift operands 8264 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8265 8266 // "The type of the result is that of the promoted left operand." 8267 return LHSType; 8268 } 8269 8270 static bool IsWithinTemplateSpecialization(Decl *D) { 8271 if (DeclContext *DC = D->getDeclContext()) { 8272 if (isa<ClassTemplateSpecializationDecl>(DC)) 8273 return true; 8274 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8275 return FD->isFunctionTemplateSpecialization(); 8276 } 8277 return false; 8278 } 8279 8280 /// If two different enums are compared, raise a warning. 8281 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8282 Expr *RHS) { 8283 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8284 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8285 8286 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8287 if (!LHSEnumType) 8288 return; 8289 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8290 if (!RHSEnumType) 8291 return; 8292 8293 // Ignore anonymous enums. 8294 if (!LHSEnumType->getDecl()->getIdentifier()) 8295 return; 8296 if (!RHSEnumType->getDecl()->getIdentifier()) 8297 return; 8298 8299 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8300 return; 8301 8302 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8303 << LHSStrippedType << RHSStrippedType 8304 << LHS->getSourceRange() << RHS->getSourceRange(); 8305 } 8306 8307 /// \brief Diagnose bad pointer comparisons. 8308 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8309 ExprResult &LHS, ExprResult &RHS, 8310 bool IsError) { 8311 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8312 : diag::ext_typecheck_comparison_of_distinct_pointers) 8313 << LHS.get()->getType() << RHS.get()->getType() 8314 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8315 } 8316 8317 /// \brief Returns false if the pointers are converted to a composite type, 8318 /// true otherwise. 8319 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8320 ExprResult &LHS, ExprResult &RHS) { 8321 // C++ [expr.rel]p2: 8322 // [...] Pointer conversions (4.10) and qualification 8323 // conversions (4.4) are performed on pointer operands (or on 8324 // a pointer operand and a null pointer constant) to bring 8325 // them to their composite pointer type. [...] 8326 // 8327 // C++ [expr.eq]p1 uses the same notion for (in)equality 8328 // comparisons of pointers. 8329 8330 // C++ [expr.eq]p2: 8331 // In addition, pointers to members can be compared, or a pointer to 8332 // member and a null pointer constant. Pointer to member conversions 8333 // (4.11) and qualification conversions (4.4) are performed to bring 8334 // them to a common type. If one operand is a null pointer constant, 8335 // the common type is the type of the other operand. Otherwise, the 8336 // common type is a pointer to member type similar (4.4) to the type 8337 // of one of the operands, with a cv-qualification signature (4.4) 8338 // that is the union of the cv-qualification signatures of the operand 8339 // types. 8340 8341 QualType LHSType = LHS.get()->getType(); 8342 QualType RHSType = RHS.get()->getType(); 8343 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8344 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8345 8346 bool NonStandardCompositeType = false; 8347 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8348 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8349 if (T.isNull()) { 8350 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8351 return true; 8352 } 8353 8354 if (NonStandardCompositeType) 8355 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8356 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8357 << RHS.get()->getSourceRange(); 8358 8359 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8360 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8361 return false; 8362 } 8363 8364 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8365 ExprResult &LHS, 8366 ExprResult &RHS, 8367 bool IsError) { 8368 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8369 : diag::ext_typecheck_comparison_of_fptr_to_void) 8370 << LHS.get()->getType() << RHS.get()->getType() 8371 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8372 } 8373 8374 static bool isObjCObjectLiteral(ExprResult &E) { 8375 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8376 case Stmt::ObjCArrayLiteralClass: 8377 case Stmt::ObjCDictionaryLiteralClass: 8378 case Stmt::ObjCStringLiteralClass: 8379 case Stmt::ObjCBoxedExprClass: 8380 return true; 8381 default: 8382 // Note that ObjCBoolLiteral is NOT an object literal! 8383 return false; 8384 } 8385 } 8386 8387 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8388 const ObjCObjectPointerType *Type = 8389 LHS->getType()->getAs<ObjCObjectPointerType>(); 8390 8391 // If this is not actually an Objective-C object, bail out. 8392 if (!Type) 8393 return false; 8394 8395 // Get the LHS object's interface type. 8396 QualType InterfaceType = Type->getPointeeType(); 8397 8398 // If the RHS isn't an Objective-C object, bail out. 8399 if (!RHS->getType()->isObjCObjectPointerType()) 8400 return false; 8401 8402 // Try to find the -isEqual: method. 8403 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8404 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8405 InterfaceType, 8406 /*instance=*/true); 8407 if (!Method) { 8408 if (Type->isObjCIdType()) { 8409 // For 'id', just check the global pool. 8410 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8411 /*receiverId=*/true); 8412 } else { 8413 // Check protocols. 8414 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8415 /*instance=*/true); 8416 } 8417 } 8418 8419 if (!Method) 8420 return false; 8421 8422 QualType T = Method->parameters()[0]->getType(); 8423 if (!T->isObjCObjectPointerType()) 8424 return false; 8425 8426 QualType R = Method->getReturnType(); 8427 if (!R->isScalarType()) 8428 return false; 8429 8430 return true; 8431 } 8432 8433 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8434 FromE = FromE->IgnoreParenImpCasts(); 8435 switch (FromE->getStmtClass()) { 8436 default: 8437 break; 8438 case Stmt::ObjCStringLiteralClass: 8439 // "string literal" 8440 return LK_String; 8441 case Stmt::ObjCArrayLiteralClass: 8442 // "array literal" 8443 return LK_Array; 8444 case Stmt::ObjCDictionaryLiteralClass: 8445 // "dictionary literal" 8446 return LK_Dictionary; 8447 case Stmt::BlockExprClass: 8448 return LK_Block; 8449 case Stmt::ObjCBoxedExprClass: { 8450 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8451 switch (Inner->getStmtClass()) { 8452 case Stmt::IntegerLiteralClass: 8453 case Stmt::FloatingLiteralClass: 8454 case Stmt::CharacterLiteralClass: 8455 case Stmt::ObjCBoolLiteralExprClass: 8456 case Stmt::CXXBoolLiteralExprClass: 8457 // "numeric literal" 8458 return LK_Numeric; 8459 case Stmt::ImplicitCastExprClass: { 8460 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8461 // Boolean literals can be represented by implicit casts. 8462 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8463 return LK_Numeric; 8464 break; 8465 } 8466 default: 8467 break; 8468 } 8469 return LK_Boxed; 8470 } 8471 } 8472 return LK_None; 8473 } 8474 8475 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8476 ExprResult &LHS, ExprResult &RHS, 8477 BinaryOperator::Opcode Opc){ 8478 Expr *Literal; 8479 Expr *Other; 8480 if (isObjCObjectLiteral(LHS)) { 8481 Literal = LHS.get(); 8482 Other = RHS.get(); 8483 } else { 8484 Literal = RHS.get(); 8485 Other = LHS.get(); 8486 } 8487 8488 // Don't warn on comparisons against nil. 8489 Other = Other->IgnoreParenCasts(); 8490 if (Other->isNullPointerConstant(S.getASTContext(), 8491 Expr::NPC_ValueDependentIsNotNull)) 8492 return; 8493 8494 // This should be kept in sync with warn_objc_literal_comparison. 8495 // LK_String should always be after the other literals, since it has its own 8496 // warning flag. 8497 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8498 assert(LiteralKind != Sema::LK_Block); 8499 if (LiteralKind == Sema::LK_None) { 8500 llvm_unreachable("Unknown Objective-C object literal kind"); 8501 } 8502 8503 if (LiteralKind == Sema::LK_String) 8504 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8505 << Literal->getSourceRange(); 8506 else 8507 S.Diag(Loc, diag::warn_objc_literal_comparison) 8508 << LiteralKind << Literal->getSourceRange(); 8509 8510 if (BinaryOperator::isEqualityOp(Opc) && 8511 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8512 SourceLocation Start = LHS.get()->getLocStart(); 8513 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 8514 CharSourceRange OpRange = 8515 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 8516 8517 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8518 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8519 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8520 << FixItHint::CreateInsertion(End, "]"); 8521 } 8522 } 8523 8524 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8525 ExprResult &RHS, 8526 SourceLocation Loc, 8527 unsigned OpaqueOpc) { 8528 // Check that left hand side is !something. 8529 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8530 if (!UO || UO->getOpcode() != UO_LNot) return; 8531 8532 // Only check if the right hand side is non-bool arithmetic type. 8533 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8534 8535 // Make sure that the something in !something is not bool. 8536 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8537 if (SubExpr->isKnownToHaveBooleanValue()) return; 8538 8539 // Emit warning. 8540 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8541 << Loc; 8542 8543 // First note suggest !(x < y) 8544 SourceLocation FirstOpen = SubExpr->getLocStart(); 8545 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8546 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 8547 if (FirstClose.isInvalid()) 8548 FirstOpen = SourceLocation(); 8549 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8550 << FixItHint::CreateInsertion(FirstOpen, "(") 8551 << FixItHint::CreateInsertion(FirstClose, ")"); 8552 8553 // Second note suggests (!x) < y 8554 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8555 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8556 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 8557 if (SecondClose.isInvalid()) 8558 SecondOpen = SourceLocation(); 8559 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8560 << FixItHint::CreateInsertion(SecondOpen, "(") 8561 << FixItHint::CreateInsertion(SecondClose, ")"); 8562 } 8563 8564 // Get the decl for a simple expression: a reference to a variable, 8565 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8566 static ValueDecl *getCompareDecl(Expr *E) { 8567 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8568 return DR->getDecl(); 8569 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8570 if (Ivar->isFreeIvar()) 8571 return Ivar->getDecl(); 8572 } 8573 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8574 if (Mem->isImplicitAccess()) 8575 return Mem->getMemberDecl(); 8576 } 8577 return nullptr; 8578 } 8579 8580 // C99 6.5.8, C++ [expr.rel] 8581 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8582 SourceLocation Loc, unsigned OpaqueOpc, 8583 bool IsRelational) { 8584 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8585 8586 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 8587 8588 // Handle vector comparisons separately. 8589 if (LHS.get()->getType()->isVectorType() || 8590 RHS.get()->getType()->isVectorType()) 8591 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8592 8593 QualType LHSType = LHS.get()->getType(); 8594 QualType RHSType = RHS.get()->getType(); 8595 8596 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8597 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8598 8599 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8600 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 8601 8602 if (!LHSType->hasFloatingRepresentation() && 8603 !(LHSType->isBlockPointerType() && IsRelational) && 8604 !LHS.get()->getLocStart().isMacroID() && 8605 !RHS.get()->getLocStart().isMacroID() && 8606 ActiveTemplateInstantiations.empty()) { 8607 // For non-floating point types, check for self-comparisons of the form 8608 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8609 // often indicate logic errors in the program. 8610 // 8611 // NOTE: Don't warn about comparison expressions resulting from macro 8612 // expansion. Also don't warn about comparisons which are only self 8613 // comparisons within a template specialization. The warnings should catch 8614 // obvious cases in the definition of the template anyways. The idea is to 8615 // warn when the typed comparison operator will always evaluate to the same 8616 // result. 8617 ValueDecl *DL = getCompareDecl(LHSStripped); 8618 ValueDecl *DR = getCompareDecl(RHSStripped); 8619 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8620 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8621 << 0 // self- 8622 << (Opc == BO_EQ 8623 || Opc == BO_LE 8624 || Opc == BO_GE)); 8625 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8626 !DL->getType()->isReferenceType() && 8627 !DR->getType()->isReferenceType()) { 8628 // what is it always going to eval to? 8629 char always_evals_to; 8630 switch(Opc) { 8631 case BO_EQ: // e.g. array1 == array2 8632 always_evals_to = 0; // false 8633 break; 8634 case BO_NE: // e.g. array1 != array2 8635 always_evals_to = 1; // true 8636 break; 8637 default: 8638 // best we can say is 'a constant' 8639 always_evals_to = 2; // e.g. array1 <= array2 8640 break; 8641 } 8642 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8643 << 1 // array 8644 << always_evals_to); 8645 } 8646 8647 if (isa<CastExpr>(LHSStripped)) 8648 LHSStripped = LHSStripped->IgnoreParenCasts(); 8649 if (isa<CastExpr>(RHSStripped)) 8650 RHSStripped = RHSStripped->IgnoreParenCasts(); 8651 8652 // Warn about comparisons against a string constant (unless the other 8653 // operand is null), the user probably wants strcmp. 8654 Expr *literalString = nullptr; 8655 Expr *literalStringStripped = nullptr; 8656 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8657 !RHSStripped->isNullPointerConstant(Context, 8658 Expr::NPC_ValueDependentIsNull)) { 8659 literalString = LHS.get(); 8660 literalStringStripped = LHSStripped; 8661 } else if ((isa<StringLiteral>(RHSStripped) || 8662 isa<ObjCEncodeExpr>(RHSStripped)) && 8663 !LHSStripped->isNullPointerConstant(Context, 8664 Expr::NPC_ValueDependentIsNull)) { 8665 literalString = RHS.get(); 8666 literalStringStripped = RHSStripped; 8667 } 8668 8669 if (literalString) { 8670 DiagRuntimeBehavior(Loc, nullptr, 8671 PDiag(diag::warn_stringcompare) 8672 << isa<ObjCEncodeExpr>(literalStringStripped) 8673 << literalString->getSourceRange()); 8674 } 8675 } 8676 8677 // C99 6.5.8p3 / C99 6.5.9p4 8678 UsualArithmeticConversions(LHS, RHS); 8679 if (LHS.isInvalid() || RHS.isInvalid()) 8680 return QualType(); 8681 8682 LHSType = LHS.get()->getType(); 8683 RHSType = RHS.get()->getType(); 8684 8685 // The result of comparisons is 'bool' in C++, 'int' in C. 8686 QualType ResultTy = Context.getLogicalOperationType(); 8687 8688 if (IsRelational) { 8689 if (LHSType->isRealType() && RHSType->isRealType()) 8690 return ResultTy; 8691 } else { 8692 // Check for comparisons of floating point operands using != and ==. 8693 if (LHSType->hasFloatingRepresentation()) 8694 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8695 8696 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8697 return ResultTy; 8698 } 8699 8700 const Expr::NullPointerConstantKind LHSNullKind = 8701 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8702 const Expr::NullPointerConstantKind RHSNullKind = 8703 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8704 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8705 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8706 8707 if (!IsRelational && LHSIsNull != RHSIsNull) { 8708 bool IsEquality = Opc == BO_EQ; 8709 if (RHSIsNull) 8710 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 8711 RHS.get()->getSourceRange()); 8712 else 8713 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 8714 LHS.get()->getSourceRange()); 8715 } 8716 8717 // All of the following pointer-related warnings are GCC extensions, except 8718 // when handling null pointer constants. 8719 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 8720 QualType LCanPointeeTy = 8721 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8722 QualType RCanPointeeTy = 8723 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8724 8725 if (getLangOpts().CPlusPlus) { 8726 if (LCanPointeeTy == RCanPointeeTy) 8727 return ResultTy; 8728 if (!IsRelational && 8729 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8730 // Valid unless comparison between non-null pointer and function pointer 8731 // This is a gcc extension compatibility comparison. 8732 // In a SFINAE context, we treat this as a hard error to maintain 8733 // conformance with the C++ standard. 8734 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8735 && !LHSIsNull && !RHSIsNull) { 8736 diagnoseFunctionPointerToVoidComparison( 8737 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8738 8739 if (isSFINAEContext()) 8740 return QualType(); 8741 8742 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8743 return ResultTy; 8744 } 8745 } 8746 8747 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8748 return QualType(); 8749 else 8750 return ResultTy; 8751 } 8752 // C99 6.5.9p2 and C99 6.5.8p2 8753 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8754 RCanPointeeTy.getUnqualifiedType())) { 8755 // Valid unless a relational comparison of function pointers 8756 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8757 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8758 << LHSType << RHSType << LHS.get()->getSourceRange() 8759 << RHS.get()->getSourceRange(); 8760 } 8761 } else if (!IsRelational && 8762 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8763 // Valid unless comparison between non-null pointer and function pointer 8764 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8765 && !LHSIsNull && !RHSIsNull) 8766 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8767 /*isError*/false); 8768 } else { 8769 // Invalid 8770 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8771 } 8772 if (LCanPointeeTy != RCanPointeeTy) { 8773 if (getLangOpts().OpenCL) { 8774 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 8775 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 8776 Diag(Loc, 8777 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8778 << LHSType << RHSType << 0 /* comparison */ 8779 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8780 } 8781 } 8782 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 8783 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 8784 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 8785 : CK_BitCast; 8786 if (LHSIsNull && !RHSIsNull) 8787 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 8788 else 8789 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 8790 } 8791 return ResultTy; 8792 } 8793 8794 if (getLangOpts().CPlusPlus) { 8795 // Comparison of nullptr_t with itself. 8796 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 8797 return ResultTy; 8798 8799 // Comparison of pointers with null pointer constants and equality 8800 // comparisons of member pointers to null pointer constants. 8801 if (RHSIsNull && 8802 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 8803 (!IsRelational && 8804 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 8805 RHS = ImpCastExprToType(RHS.get(), LHSType, 8806 LHSType->isMemberPointerType() 8807 ? CK_NullToMemberPointer 8808 : CK_NullToPointer); 8809 return ResultTy; 8810 } 8811 if (LHSIsNull && 8812 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 8813 (!IsRelational && 8814 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 8815 LHS = ImpCastExprToType(LHS.get(), RHSType, 8816 RHSType->isMemberPointerType() 8817 ? CK_NullToMemberPointer 8818 : CK_NullToPointer); 8819 return ResultTy; 8820 } 8821 8822 // Comparison of member pointers. 8823 if (!IsRelational && 8824 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 8825 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8826 return QualType(); 8827 else 8828 return ResultTy; 8829 } 8830 8831 // Handle scoped enumeration types specifically, since they don't promote 8832 // to integers. 8833 if (LHS.get()->getType()->isEnumeralType() && 8834 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8835 RHS.get()->getType())) 8836 return ResultTy; 8837 } 8838 8839 // Handle block pointer types. 8840 if (!IsRelational && LHSType->isBlockPointerType() && 8841 RHSType->isBlockPointerType()) { 8842 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8843 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8844 8845 if (!LHSIsNull && !RHSIsNull && 8846 !Context.typesAreCompatible(lpointee, rpointee)) { 8847 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8848 << LHSType << RHSType << LHS.get()->getSourceRange() 8849 << RHS.get()->getSourceRange(); 8850 } 8851 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8852 return ResultTy; 8853 } 8854 8855 // Allow block pointers to be compared with null pointer constants. 8856 if (!IsRelational 8857 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8858 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8859 if (!LHSIsNull && !RHSIsNull) { 8860 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8861 ->getPointeeType()->isVoidType()) 8862 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8863 ->getPointeeType()->isVoidType()))) 8864 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8865 << LHSType << RHSType << LHS.get()->getSourceRange() 8866 << RHS.get()->getSourceRange(); 8867 } 8868 if (LHSIsNull && !RHSIsNull) 8869 LHS = ImpCastExprToType(LHS.get(), RHSType, 8870 RHSType->isPointerType() ? CK_BitCast 8871 : CK_AnyPointerToBlockPointerCast); 8872 else 8873 RHS = ImpCastExprToType(RHS.get(), LHSType, 8874 LHSType->isPointerType() ? CK_BitCast 8875 : CK_AnyPointerToBlockPointerCast); 8876 return ResultTy; 8877 } 8878 8879 if (LHSType->isObjCObjectPointerType() || 8880 RHSType->isObjCObjectPointerType()) { 8881 const PointerType *LPT = LHSType->getAs<PointerType>(); 8882 const PointerType *RPT = RHSType->getAs<PointerType>(); 8883 if (LPT || RPT) { 8884 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8885 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8886 8887 if (!LPtrToVoid && !RPtrToVoid && 8888 !Context.typesAreCompatible(LHSType, RHSType)) { 8889 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8890 /*isError*/false); 8891 } 8892 if (LHSIsNull && !RHSIsNull) { 8893 Expr *E = LHS.get(); 8894 if (getLangOpts().ObjCAutoRefCount) 8895 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8896 LHS = ImpCastExprToType(E, RHSType, 8897 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8898 } 8899 else { 8900 Expr *E = RHS.get(); 8901 if (getLangOpts().ObjCAutoRefCount) 8902 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false, 8903 Opc); 8904 RHS = ImpCastExprToType(E, LHSType, 8905 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8906 } 8907 return ResultTy; 8908 } 8909 if (LHSType->isObjCObjectPointerType() && 8910 RHSType->isObjCObjectPointerType()) { 8911 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8912 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8913 /*isError*/false); 8914 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8915 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8916 8917 if (LHSIsNull && !RHSIsNull) 8918 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8919 else 8920 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8921 return ResultTy; 8922 } 8923 } 8924 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8925 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8926 unsigned DiagID = 0; 8927 bool isError = false; 8928 if (LangOpts.DebuggerSupport) { 8929 // Under a debugger, allow the comparison of pointers to integers, 8930 // since users tend to want to compare addresses. 8931 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8932 (RHSIsNull && RHSType->isIntegerType())) { 8933 if (IsRelational && !getLangOpts().CPlusPlus) 8934 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8935 } else if (IsRelational && !getLangOpts().CPlusPlus) 8936 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8937 else if (getLangOpts().CPlusPlus) { 8938 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8939 isError = true; 8940 } else 8941 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8942 8943 if (DiagID) { 8944 Diag(Loc, DiagID) 8945 << LHSType << RHSType << LHS.get()->getSourceRange() 8946 << RHS.get()->getSourceRange(); 8947 if (isError) 8948 return QualType(); 8949 } 8950 8951 if (LHSType->isIntegerType()) 8952 LHS = ImpCastExprToType(LHS.get(), RHSType, 8953 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8954 else 8955 RHS = ImpCastExprToType(RHS.get(), LHSType, 8956 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8957 return ResultTy; 8958 } 8959 8960 // Handle block pointers. 8961 if (!IsRelational && RHSIsNull 8962 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8963 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8964 return ResultTy; 8965 } 8966 if (!IsRelational && LHSIsNull 8967 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8968 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 8969 return ResultTy; 8970 } 8971 8972 return InvalidOperands(Loc, LHS, RHS); 8973 } 8974 8975 8976 // Return a signed type that is of identical size and number of elements. 8977 // For floating point vectors, return an integer type of identical size 8978 // and number of elements. 8979 QualType Sema::GetSignedVectorType(QualType V) { 8980 const VectorType *VTy = V->getAs<VectorType>(); 8981 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8982 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8983 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8984 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8985 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8986 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8987 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8988 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8989 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8990 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8991 "Unhandled vector element size in vector compare"); 8992 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8993 } 8994 8995 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 8996 /// operates on extended vector types. Instead of producing an IntTy result, 8997 /// like a scalar comparison, a vector comparison produces a vector of integer 8998 /// types. 8999 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9000 SourceLocation Loc, 9001 bool IsRelational) { 9002 // Check to make sure we're operating on vectors of the same type and width, 9003 // Allowing one side to be a scalar of element type. 9004 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9005 /*AllowBothBool*/true, 9006 /*AllowBoolConversions*/getLangOpts().ZVector); 9007 if (vType.isNull()) 9008 return vType; 9009 9010 QualType LHSType = LHS.get()->getType(); 9011 9012 // If AltiVec, the comparison results in a numeric type, i.e. 9013 // bool for C++, int for C 9014 if (getLangOpts().AltiVec && 9015 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9016 return Context.getLogicalOperationType(); 9017 9018 // For non-floating point types, check for self-comparisons of the form 9019 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9020 // often indicate logic errors in the program. 9021 if (!LHSType->hasFloatingRepresentation() && 9022 ActiveTemplateInstantiations.empty()) { 9023 if (DeclRefExpr* DRL 9024 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9025 if (DeclRefExpr* DRR 9026 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9027 if (DRL->getDecl() == DRR->getDecl()) 9028 DiagRuntimeBehavior(Loc, nullptr, 9029 PDiag(diag::warn_comparison_always) 9030 << 0 // self- 9031 << 2 // "a constant" 9032 ); 9033 } 9034 9035 // Check for comparisons of floating point operands using != and ==. 9036 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9037 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9038 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9039 } 9040 9041 // Return a signed type for the vector. 9042 return GetSignedVectorType(LHSType); 9043 } 9044 9045 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9046 SourceLocation Loc) { 9047 // Ensure that either both operands are of the same vector type, or 9048 // one operand is of a vector type and the other is of its element type. 9049 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9050 /*AllowBothBool*/true, 9051 /*AllowBoolConversions*/false); 9052 if (vType.isNull()) 9053 return InvalidOperands(Loc, LHS, RHS); 9054 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9055 vType->hasFloatingRepresentation()) 9056 return InvalidOperands(Loc, LHS, RHS); 9057 9058 return GetSignedVectorType(LHS.get()->getType()); 9059 } 9060 9061 inline QualType Sema::CheckBitwiseOperands( 9062 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9063 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9064 9065 if (LHS.get()->getType()->isVectorType() || 9066 RHS.get()->getType()->isVectorType()) { 9067 if (LHS.get()->getType()->hasIntegerRepresentation() && 9068 RHS.get()->getType()->hasIntegerRepresentation()) 9069 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9070 /*AllowBothBool*/true, 9071 /*AllowBoolConversions*/getLangOpts().ZVector); 9072 return InvalidOperands(Loc, LHS, RHS); 9073 } 9074 9075 ExprResult LHSResult = LHS, RHSResult = RHS; 9076 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9077 IsCompAssign); 9078 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9079 return QualType(); 9080 LHS = LHSResult.get(); 9081 RHS = RHSResult.get(); 9082 9083 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9084 return compType; 9085 return InvalidOperands(Loc, LHS, RHS); 9086 } 9087 9088 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 9089 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 9090 9091 // Check vector operands differently. 9092 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9093 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9094 9095 // Diagnose cases where the user write a logical and/or but probably meant a 9096 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9097 // is a constant. 9098 if (LHS.get()->getType()->isIntegerType() && 9099 !LHS.get()->getType()->isBooleanType() && 9100 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9101 // Don't warn in macros or template instantiations. 9102 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9103 // If the RHS can be constant folded, and if it constant folds to something 9104 // that isn't 0 or 1 (which indicate a potential logical operation that 9105 // happened to fold to true/false) then warn. 9106 // Parens on the RHS are ignored. 9107 llvm::APSInt Result; 9108 if (RHS.get()->EvaluateAsInt(Result, Context)) 9109 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9110 !RHS.get()->getExprLoc().isMacroID()) || 9111 (Result != 0 && Result != 1)) { 9112 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9113 << RHS.get()->getSourceRange() 9114 << (Opc == BO_LAnd ? "&&" : "||"); 9115 // Suggest replacing the logical operator with the bitwise version 9116 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9117 << (Opc == BO_LAnd ? "&" : "|") 9118 << FixItHint::CreateReplacement(SourceRange( 9119 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 9120 getLangOpts())), 9121 Opc == BO_LAnd ? "&" : "|"); 9122 if (Opc == BO_LAnd) 9123 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9124 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9125 << FixItHint::CreateRemoval( 9126 SourceRange( 9127 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 9128 0, getSourceManager(), 9129 getLangOpts()), 9130 RHS.get()->getLocEnd())); 9131 } 9132 } 9133 9134 if (!Context.getLangOpts().CPlusPlus) { 9135 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9136 // not operate on the built-in scalar and vector float types. 9137 if (Context.getLangOpts().OpenCL && 9138 Context.getLangOpts().OpenCLVersion < 120) { 9139 if (LHS.get()->getType()->isFloatingType() || 9140 RHS.get()->getType()->isFloatingType()) 9141 return InvalidOperands(Loc, LHS, RHS); 9142 } 9143 9144 LHS = UsualUnaryConversions(LHS.get()); 9145 if (LHS.isInvalid()) 9146 return QualType(); 9147 9148 RHS = UsualUnaryConversions(RHS.get()); 9149 if (RHS.isInvalid()) 9150 return QualType(); 9151 9152 if (!LHS.get()->getType()->isScalarType() || 9153 !RHS.get()->getType()->isScalarType()) 9154 return InvalidOperands(Loc, LHS, RHS); 9155 9156 return Context.IntTy; 9157 } 9158 9159 // The following is safe because we only use this method for 9160 // non-overloadable operands. 9161 9162 // C++ [expr.log.and]p1 9163 // C++ [expr.log.or]p1 9164 // The operands are both contextually converted to type bool. 9165 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9166 if (LHSRes.isInvalid()) 9167 return InvalidOperands(Loc, LHS, RHS); 9168 LHS = LHSRes; 9169 9170 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9171 if (RHSRes.isInvalid()) 9172 return InvalidOperands(Loc, LHS, RHS); 9173 RHS = RHSRes; 9174 9175 // C++ [expr.log.and]p2 9176 // C++ [expr.log.or]p2 9177 // The result is a bool. 9178 return Context.BoolTy; 9179 } 9180 9181 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9182 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9183 if (!ME) return false; 9184 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9185 ObjCMessageExpr *Base = 9186 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9187 if (!Base) return false; 9188 return Base->getMethodDecl() != nullptr; 9189 } 9190 9191 /// Is the given expression (which must be 'const') a reference to a 9192 /// variable which was originally non-const, but which has become 9193 /// 'const' due to being captured within a block? 9194 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9195 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9196 assert(E->isLValue() && E->getType().isConstQualified()); 9197 E = E->IgnoreParens(); 9198 9199 // Must be a reference to a declaration from an enclosing scope. 9200 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9201 if (!DRE) return NCCK_None; 9202 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9203 9204 // The declaration must be a variable which is not declared 'const'. 9205 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9206 if (!var) return NCCK_None; 9207 if (var->getType().isConstQualified()) return NCCK_None; 9208 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9209 9210 // Decide whether the first capture was for a block or a lambda. 9211 DeclContext *DC = S.CurContext, *Prev = nullptr; 9212 while (DC != var->getDeclContext()) { 9213 Prev = DC; 9214 DC = DC->getParent(); 9215 } 9216 // Unless we have an init-capture, we've gone one step too far. 9217 if (!var->isInitCapture()) 9218 DC = Prev; 9219 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9220 } 9221 9222 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9223 Ty = Ty.getNonReferenceType(); 9224 if (IsDereference && Ty->isPointerType()) 9225 Ty = Ty->getPointeeType(); 9226 return !Ty.isConstQualified(); 9227 } 9228 9229 /// Emit the "read-only variable not assignable" error and print notes to give 9230 /// more information about why the variable is not assignable, such as pointing 9231 /// to the declaration of a const variable, showing that a method is const, or 9232 /// that the function is returning a const reference. 9233 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9234 SourceLocation Loc) { 9235 // Update err_typecheck_assign_const and note_typecheck_assign_const 9236 // when this enum is changed. 9237 enum { 9238 ConstFunction, 9239 ConstVariable, 9240 ConstMember, 9241 ConstMethod, 9242 ConstUnknown, // Keep as last element 9243 }; 9244 9245 SourceRange ExprRange = E->getSourceRange(); 9246 9247 // Only emit one error on the first const found. All other consts will emit 9248 // a note to the error. 9249 bool DiagnosticEmitted = false; 9250 9251 // Track if the current expression is the result of a derefence, and if the 9252 // next checked expression is the result of a derefence. 9253 bool IsDereference = false; 9254 bool NextIsDereference = false; 9255 9256 // Loop to process MemberExpr chains. 9257 while (true) { 9258 IsDereference = NextIsDereference; 9259 NextIsDereference = false; 9260 9261 E = E->IgnoreParenImpCasts(); 9262 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9263 NextIsDereference = ME->isArrow(); 9264 const ValueDecl *VD = ME->getMemberDecl(); 9265 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9266 // Mutable fields can be modified even if the class is const. 9267 if (Field->isMutable()) { 9268 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9269 break; 9270 } 9271 9272 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9273 if (!DiagnosticEmitted) { 9274 S.Diag(Loc, diag::err_typecheck_assign_const) 9275 << ExprRange << ConstMember << false /*static*/ << Field 9276 << Field->getType(); 9277 DiagnosticEmitted = true; 9278 } 9279 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9280 << ConstMember << false /*static*/ << Field << Field->getType() 9281 << Field->getSourceRange(); 9282 } 9283 E = ME->getBase(); 9284 continue; 9285 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9286 if (VDecl->getType().isConstQualified()) { 9287 if (!DiagnosticEmitted) { 9288 S.Diag(Loc, diag::err_typecheck_assign_const) 9289 << ExprRange << ConstMember << true /*static*/ << VDecl 9290 << VDecl->getType(); 9291 DiagnosticEmitted = true; 9292 } 9293 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9294 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9295 << VDecl->getSourceRange(); 9296 } 9297 // Static fields do not inherit constness from parents. 9298 break; 9299 } 9300 break; 9301 } // End MemberExpr 9302 break; 9303 } 9304 9305 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9306 // Function calls 9307 const FunctionDecl *FD = CE->getDirectCallee(); 9308 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9309 if (!DiagnosticEmitted) { 9310 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9311 << ConstFunction << FD; 9312 DiagnosticEmitted = true; 9313 } 9314 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9315 diag::note_typecheck_assign_const) 9316 << ConstFunction << FD << FD->getReturnType() 9317 << FD->getReturnTypeSourceRange(); 9318 } 9319 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9320 // Point to variable declaration. 9321 if (const ValueDecl *VD = DRE->getDecl()) { 9322 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9323 if (!DiagnosticEmitted) { 9324 S.Diag(Loc, diag::err_typecheck_assign_const) 9325 << ExprRange << ConstVariable << VD << VD->getType(); 9326 DiagnosticEmitted = true; 9327 } 9328 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9329 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9330 } 9331 } 9332 } else if (isa<CXXThisExpr>(E)) { 9333 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9334 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9335 if (MD->isConst()) { 9336 if (!DiagnosticEmitted) { 9337 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9338 << ConstMethod << MD; 9339 DiagnosticEmitted = true; 9340 } 9341 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9342 << ConstMethod << MD << MD->getSourceRange(); 9343 } 9344 } 9345 } 9346 } 9347 9348 if (DiagnosticEmitted) 9349 return; 9350 9351 // Can't determine a more specific message, so display the generic error. 9352 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9353 } 9354 9355 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9356 /// emit an error and return true. If so, return false. 9357 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9358 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9359 SourceLocation OrigLoc = Loc; 9360 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9361 &Loc); 9362 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9363 IsLV = Expr::MLV_InvalidMessageExpression; 9364 if (IsLV == Expr::MLV_Valid) 9365 return false; 9366 9367 unsigned DiagID = 0; 9368 bool NeedType = false; 9369 switch (IsLV) { // C99 6.5.16p2 9370 case Expr::MLV_ConstQualified: 9371 // Use a specialized diagnostic when we're assigning to an object 9372 // from an enclosing function or block. 9373 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9374 if (NCCK == NCCK_Block) 9375 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9376 else 9377 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9378 break; 9379 } 9380 9381 // In ARC, use some specialized diagnostics for occasions where we 9382 // infer 'const'. These are always pseudo-strong variables. 9383 if (S.getLangOpts().ObjCAutoRefCount) { 9384 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9385 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9386 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9387 9388 // Use the normal diagnostic if it's pseudo-__strong but the 9389 // user actually wrote 'const'. 9390 if (var->isARCPseudoStrong() && 9391 (!var->getTypeSourceInfo() || 9392 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9393 // There are two pseudo-strong cases: 9394 // - self 9395 ObjCMethodDecl *method = S.getCurMethodDecl(); 9396 if (method && var == method->getSelfDecl()) 9397 DiagID = method->isClassMethod() 9398 ? diag::err_typecheck_arc_assign_self_class_method 9399 : diag::err_typecheck_arc_assign_self; 9400 9401 // - fast enumeration variables 9402 else 9403 DiagID = diag::err_typecheck_arr_assign_enumeration; 9404 9405 SourceRange Assign; 9406 if (Loc != OrigLoc) 9407 Assign = SourceRange(OrigLoc, OrigLoc); 9408 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9409 // We need to preserve the AST regardless, so migration tool 9410 // can do its job. 9411 return false; 9412 } 9413 } 9414 } 9415 9416 // If none of the special cases above are triggered, then this is a 9417 // simple const assignment. 9418 if (DiagID == 0) { 9419 DiagnoseConstAssignment(S, E, Loc); 9420 return true; 9421 } 9422 9423 break; 9424 case Expr::MLV_ConstAddrSpace: 9425 DiagnoseConstAssignment(S, E, Loc); 9426 return true; 9427 case Expr::MLV_ArrayType: 9428 case Expr::MLV_ArrayTemporary: 9429 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9430 NeedType = true; 9431 break; 9432 case Expr::MLV_NotObjectType: 9433 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9434 NeedType = true; 9435 break; 9436 case Expr::MLV_LValueCast: 9437 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9438 break; 9439 case Expr::MLV_Valid: 9440 llvm_unreachable("did not take early return for MLV_Valid"); 9441 case Expr::MLV_InvalidExpression: 9442 case Expr::MLV_MemberFunction: 9443 case Expr::MLV_ClassTemporary: 9444 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9445 break; 9446 case Expr::MLV_IncompleteType: 9447 case Expr::MLV_IncompleteVoidType: 9448 return S.RequireCompleteType(Loc, E->getType(), 9449 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9450 case Expr::MLV_DuplicateVectorComponents: 9451 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9452 break; 9453 case Expr::MLV_NoSetterProperty: 9454 llvm_unreachable("readonly properties should be processed differently"); 9455 case Expr::MLV_InvalidMessageExpression: 9456 DiagID = diag::error_readonly_message_assignment; 9457 break; 9458 case Expr::MLV_SubObjCPropertySetting: 9459 DiagID = diag::error_no_subobject_property_setting; 9460 break; 9461 } 9462 9463 SourceRange Assign; 9464 if (Loc != OrigLoc) 9465 Assign = SourceRange(OrigLoc, OrigLoc); 9466 if (NeedType) 9467 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9468 else 9469 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9470 return true; 9471 } 9472 9473 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9474 SourceLocation Loc, 9475 Sema &Sema) { 9476 // C / C++ fields 9477 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9478 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9479 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9480 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9481 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9482 } 9483 9484 // Objective-C instance variables 9485 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9486 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9487 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9488 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9489 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9490 if (RL && RR && RL->getDecl() == RR->getDecl()) 9491 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9492 } 9493 } 9494 9495 // C99 6.5.16.1 9496 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9497 SourceLocation Loc, 9498 QualType CompoundType) { 9499 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9500 9501 // Verify that LHS is a modifiable lvalue, and emit error if not. 9502 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9503 return QualType(); 9504 9505 QualType LHSType = LHSExpr->getType(); 9506 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9507 CompoundType; 9508 AssignConvertType ConvTy; 9509 if (CompoundType.isNull()) { 9510 Expr *RHSCheck = RHS.get(); 9511 9512 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9513 9514 QualType LHSTy(LHSType); 9515 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9516 if (RHS.isInvalid()) 9517 return QualType(); 9518 // Special case of NSObject attributes on c-style pointer types. 9519 if (ConvTy == IncompatiblePointer && 9520 ((Context.isObjCNSObjectType(LHSType) && 9521 RHSType->isObjCObjectPointerType()) || 9522 (Context.isObjCNSObjectType(RHSType) && 9523 LHSType->isObjCObjectPointerType()))) 9524 ConvTy = Compatible; 9525 9526 if (ConvTy == Compatible && 9527 LHSType->isObjCObjectType()) 9528 Diag(Loc, diag::err_objc_object_assignment) 9529 << LHSType; 9530 9531 // If the RHS is a unary plus or minus, check to see if they = and + are 9532 // right next to each other. If so, the user may have typo'd "x =+ 4" 9533 // instead of "x += 4". 9534 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9535 RHSCheck = ICE->getSubExpr(); 9536 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9537 if ((UO->getOpcode() == UO_Plus || 9538 UO->getOpcode() == UO_Minus) && 9539 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9540 // Only if the two operators are exactly adjacent. 9541 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9542 // And there is a space or other character before the subexpr of the 9543 // unary +/-. We don't want to warn on "x=-1". 9544 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9545 UO->getSubExpr()->getLocStart().isFileID()) { 9546 Diag(Loc, diag::warn_not_compound_assign) 9547 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9548 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9549 } 9550 } 9551 9552 if (ConvTy == Compatible) { 9553 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9554 // Warn about retain cycles where a block captures the LHS, but 9555 // not if the LHS is a simple variable into which the block is 9556 // being stored...unless that variable can be captured by reference! 9557 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9558 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9559 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9560 checkRetainCycles(LHSExpr, RHS.get()); 9561 9562 // It is safe to assign a weak reference into a strong variable. 9563 // Although this code can still have problems: 9564 // id x = self.weakProp; 9565 // id y = self.weakProp; 9566 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9567 // paths through the function. This should be revisited if 9568 // -Wrepeated-use-of-weak is made flow-sensitive. 9569 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9570 RHS.get()->getLocStart())) 9571 getCurFunction()->markSafeWeakUse(RHS.get()); 9572 9573 } else if (getLangOpts().ObjCAutoRefCount) { 9574 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9575 } 9576 } 9577 } else { 9578 // Compound assignment "x += y" 9579 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9580 } 9581 9582 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9583 RHS.get(), AA_Assigning)) 9584 return QualType(); 9585 9586 CheckForNullPointerDereference(*this, LHSExpr); 9587 9588 // C99 6.5.16p3: The type of an assignment expression is the type of the 9589 // left operand unless the left operand has qualified type, in which case 9590 // it is the unqualified version of the type of the left operand. 9591 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9592 // is converted to the type of the assignment expression (above). 9593 // C++ 5.17p1: the type of the assignment expression is that of its left 9594 // operand. 9595 return (getLangOpts().CPlusPlus 9596 ? LHSType : LHSType.getUnqualifiedType()); 9597 } 9598 9599 // C99 6.5.17 9600 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9601 SourceLocation Loc) { 9602 LHS = S.CheckPlaceholderExpr(LHS.get()); 9603 RHS = S.CheckPlaceholderExpr(RHS.get()); 9604 if (LHS.isInvalid() || RHS.isInvalid()) 9605 return QualType(); 9606 9607 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9608 // operands, but not unary promotions. 9609 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9610 9611 // So we treat the LHS as a ignored value, and in C++ we allow the 9612 // containing site to determine what should be done with the RHS. 9613 LHS = S.IgnoredValueConversions(LHS.get()); 9614 if (LHS.isInvalid()) 9615 return QualType(); 9616 9617 S.DiagnoseUnusedExprResult(LHS.get()); 9618 9619 if (!S.getLangOpts().CPlusPlus) { 9620 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9621 if (RHS.isInvalid()) 9622 return QualType(); 9623 if (!RHS.get()->getType()->isVoidType()) 9624 S.RequireCompleteType(Loc, RHS.get()->getType(), 9625 diag::err_incomplete_type); 9626 } 9627 9628 return RHS.get()->getType(); 9629 } 9630 9631 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9632 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9633 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9634 ExprValueKind &VK, 9635 ExprObjectKind &OK, 9636 SourceLocation OpLoc, 9637 bool IsInc, bool IsPrefix) { 9638 if (Op->isTypeDependent()) 9639 return S.Context.DependentTy; 9640 9641 QualType ResType = Op->getType(); 9642 // Atomic types can be used for increment / decrement where the non-atomic 9643 // versions can, so ignore the _Atomic() specifier for the purpose of 9644 // checking. 9645 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9646 ResType = ResAtomicType->getValueType(); 9647 9648 assert(!ResType.isNull() && "no type for increment/decrement expression"); 9649 9650 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 9651 // Decrement of bool is not allowed. 9652 if (!IsInc) { 9653 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 9654 return QualType(); 9655 } 9656 // Increment of bool sets it to true, but is deprecated. 9657 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 9658 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 9659 // Error on enum increments and decrements in C++ mode 9660 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 9661 return QualType(); 9662 } else if (ResType->isRealType()) { 9663 // OK! 9664 } else if (ResType->isPointerType()) { 9665 // C99 6.5.2.4p2, 6.5.6p2 9666 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 9667 return QualType(); 9668 } else if (ResType->isObjCObjectPointerType()) { 9669 // On modern runtimes, ObjC pointer arithmetic is forbidden. 9670 // Otherwise, we just need a complete type. 9671 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 9672 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 9673 return QualType(); 9674 } else if (ResType->isAnyComplexType()) { 9675 // C99 does not support ++/-- on complex types, we allow as an extension. 9676 S.Diag(OpLoc, diag::ext_integer_increment_complex) 9677 << ResType << Op->getSourceRange(); 9678 } else if (ResType->isPlaceholderType()) { 9679 ExprResult PR = S.CheckPlaceholderExpr(Op); 9680 if (PR.isInvalid()) return QualType(); 9681 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 9682 IsInc, IsPrefix); 9683 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 9684 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 9685 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 9686 (ResType->getAs<VectorType>()->getVectorKind() != 9687 VectorType::AltiVecBool)) { 9688 // The z vector extensions allow ++ and -- for non-bool vectors. 9689 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 9690 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 9691 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 9692 } else { 9693 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 9694 << ResType << int(IsInc) << Op->getSourceRange(); 9695 return QualType(); 9696 } 9697 // At this point, we know we have a real, complex or pointer type. 9698 // Now make sure the operand is a modifiable lvalue. 9699 if (CheckForModifiableLvalue(Op, OpLoc, S)) 9700 return QualType(); 9701 // In C++, a prefix increment is the same type as the operand. Otherwise 9702 // (in C or with postfix), the increment is the unqualified type of the 9703 // operand. 9704 if (IsPrefix && S.getLangOpts().CPlusPlus) { 9705 VK = VK_LValue; 9706 OK = Op->getObjectKind(); 9707 return ResType; 9708 } else { 9709 VK = VK_RValue; 9710 return ResType.getUnqualifiedType(); 9711 } 9712 } 9713 9714 9715 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 9716 /// This routine allows us to typecheck complex/recursive expressions 9717 /// where the declaration is needed for type checking. We only need to 9718 /// handle cases when the expression references a function designator 9719 /// or is an lvalue. Here are some examples: 9720 /// - &(x) => x 9721 /// - &*****f => f for f a function designator. 9722 /// - &s.xx => s 9723 /// - &s.zz[1].yy -> s, if zz is an array 9724 /// - *(x + 1) -> x, if x is an array 9725 /// - &"123"[2] -> 0 9726 /// - & __real__ x -> x 9727 static ValueDecl *getPrimaryDecl(Expr *E) { 9728 switch (E->getStmtClass()) { 9729 case Stmt::DeclRefExprClass: 9730 return cast<DeclRefExpr>(E)->getDecl(); 9731 case Stmt::MemberExprClass: 9732 // If this is an arrow operator, the address is an offset from 9733 // the base's value, so the object the base refers to is 9734 // irrelevant. 9735 if (cast<MemberExpr>(E)->isArrow()) 9736 return nullptr; 9737 // Otherwise, the expression refers to a part of the base 9738 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 9739 case Stmt::ArraySubscriptExprClass: { 9740 // FIXME: This code shouldn't be necessary! We should catch the implicit 9741 // promotion of register arrays earlier. 9742 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 9743 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 9744 if (ICE->getSubExpr()->getType()->isArrayType()) 9745 return getPrimaryDecl(ICE->getSubExpr()); 9746 } 9747 return nullptr; 9748 } 9749 case Stmt::UnaryOperatorClass: { 9750 UnaryOperator *UO = cast<UnaryOperator>(E); 9751 9752 switch(UO->getOpcode()) { 9753 case UO_Real: 9754 case UO_Imag: 9755 case UO_Extension: 9756 return getPrimaryDecl(UO->getSubExpr()); 9757 default: 9758 return nullptr; 9759 } 9760 } 9761 case Stmt::ParenExprClass: 9762 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 9763 case Stmt::ImplicitCastExprClass: 9764 // If the result of an implicit cast is an l-value, we care about 9765 // the sub-expression; otherwise, the result here doesn't matter. 9766 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 9767 default: 9768 return nullptr; 9769 } 9770 } 9771 9772 namespace { 9773 enum { 9774 AO_Bit_Field = 0, 9775 AO_Vector_Element = 1, 9776 AO_Property_Expansion = 2, 9777 AO_Register_Variable = 3, 9778 AO_No_Error = 4 9779 }; 9780 } 9781 /// \brief Diagnose invalid operand for address of operations. 9782 /// 9783 /// \param Type The type of operand which cannot have its address taken. 9784 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 9785 Expr *E, unsigned Type) { 9786 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 9787 } 9788 9789 /// CheckAddressOfOperand - The operand of & must be either a function 9790 /// designator or an lvalue designating an object. If it is an lvalue, the 9791 /// object cannot be declared with storage class register or be a bit field. 9792 /// Note: The usual conversions are *not* applied to the operand of the & 9793 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 9794 /// In C++, the operand might be an overloaded function name, in which case 9795 /// we allow the '&' but retain the overloaded-function type. 9796 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 9797 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 9798 if (PTy->getKind() == BuiltinType::Overload) { 9799 Expr *E = OrigOp.get()->IgnoreParens(); 9800 if (!isa<OverloadExpr>(E)) { 9801 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 9802 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 9803 << OrigOp.get()->getSourceRange(); 9804 return QualType(); 9805 } 9806 9807 OverloadExpr *Ovl = cast<OverloadExpr>(E); 9808 if (isa<UnresolvedMemberExpr>(Ovl)) 9809 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 9810 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9811 << OrigOp.get()->getSourceRange(); 9812 return QualType(); 9813 } 9814 9815 return Context.OverloadTy; 9816 } 9817 9818 if (PTy->getKind() == BuiltinType::UnknownAny) 9819 return Context.UnknownAnyTy; 9820 9821 if (PTy->getKind() == BuiltinType::BoundMember) { 9822 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9823 << OrigOp.get()->getSourceRange(); 9824 return QualType(); 9825 } 9826 9827 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 9828 if (OrigOp.isInvalid()) return QualType(); 9829 } 9830 9831 if (OrigOp.get()->isTypeDependent()) 9832 return Context.DependentTy; 9833 9834 assert(!OrigOp.get()->getType()->isPlaceholderType()); 9835 9836 // Make sure to ignore parentheses in subsequent checks 9837 Expr *op = OrigOp.get()->IgnoreParens(); 9838 9839 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 9840 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 9841 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 9842 return QualType(); 9843 } 9844 9845 if (getLangOpts().C99) { 9846 // Implement C99-only parts of addressof rules. 9847 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 9848 if (uOp->getOpcode() == UO_Deref) 9849 // Per C99 6.5.3.2, the address of a deref always returns a valid result 9850 // (assuming the deref expression is valid). 9851 return uOp->getSubExpr()->getType(); 9852 } 9853 // Technically, there should be a check for array subscript 9854 // expressions here, but the result of one is always an lvalue anyway. 9855 } 9856 ValueDecl *dcl = getPrimaryDecl(op); 9857 Expr::LValueClassification lval = op->ClassifyLValue(Context); 9858 unsigned AddressOfError = AO_No_Error; 9859 9860 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 9861 bool sfinae = (bool)isSFINAEContext(); 9862 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 9863 : diag::ext_typecheck_addrof_temporary) 9864 << op->getType() << op->getSourceRange(); 9865 if (sfinae) 9866 return QualType(); 9867 // Materialize the temporary as an lvalue so that we can take its address. 9868 OrigOp = op = new (Context) 9869 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 9870 } else if (isa<ObjCSelectorExpr>(op)) { 9871 return Context.getPointerType(op->getType()); 9872 } else if (lval == Expr::LV_MemberFunction) { 9873 // If it's an instance method, make a member pointer. 9874 // The expression must have exactly the form &A::foo. 9875 9876 // If the underlying expression isn't a decl ref, give up. 9877 if (!isa<DeclRefExpr>(op)) { 9878 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9879 << OrigOp.get()->getSourceRange(); 9880 return QualType(); 9881 } 9882 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 9883 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 9884 9885 // The id-expression was parenthesized. 9886 if (OrigOp.get() != DRE) { 9887 Diag(OpLoc, diag::err_parens_pointer_member_function) 9888 << OrigOp.get()->getSourceRange(); 9889 9890 // The method was named without a qualifier. 9891 } else if (!DRE->getQualifier()) { 9892 if (MD->getParent()->getName().empty()) 9893 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9894 << op->getSourceRange(); 9895 else { 9896 SmallString<32> Str; 9897 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 9898 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9899 << op->getSourceRange() 9900 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 9901 } 9902 } 9903 9904 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 9905 if (isa<CXXDestructorDecl>(MD)) 9906 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 9907 9908 QualType MPTy = Context.getMemberPointerType( 9909 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 9910 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9911 RequireCompleteType(OpLoc, MPTy, 0); 9912 return MPTy; 9913 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 9914 // C99 6.5.3.2p1 9915 // The operand must be either an l-value or a function designator 9916 if (!op->getType()->isFunctionType()) { 9917 // Use a special diagnostic for loads from property references. 9918 if (isa<PseudoObjectExpr>(op)) { 9919 AddressOfError = AO_Property_Expansion; 9920 } else { 9921 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 9922 << op->getType() << op->getSourceRange(); 9923 return QualType(); 9924 } 9925 } 9926 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 9927 // The operand cannot be a bit-field 9928 AddressOfError = AO_Bit_Field; 9929 } else if (op->getObjectKind() == OK_VectorComponent) { 9930 // The operand cannot be an element of a vector 9931 AddressOfError = AO_Vector_Element; 9932 } else if (dcl) { // C99 6.5.3.2p1 9933 // We have an lvalue with a decl. Make sure the decl is not declared 9934 // with the register storage-class specifier. 9935 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 9936 // in C++ it is not error to take address of a register 9937 // variable (c++03 7.1.1P3) 9938 if (vd->getStorageClass() == SC_Register && 9939 !getLangOpts().CPlusPlus) { 9940 AddressOfError = AO_Register_Variable; 9941 } 9942 } else if (isa<MSPropertyDecl>(dcl)) { 9943 AddressOfError = AO_Property_Expansion; 9944 } else if (isa<FunctionTemplateDecl>(dcl)) { 9945 return Context.OverloadTy; 9946 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 9947 // Okay: we can take the address of a field. 9948 // Could be a pointer to member, though, if there is an explicit 9949 // scope qualifier for the class. 9950 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 9951 DeclContext *Ctx = dcl->getDeclContext(); 9952 if (Ctx && Ctx->isRecord()) { 9953 if (dcl->getType()->isReferenceType()) { 9954 Diag(OpLoc, 9955 diag::err_cannot_form_pointer_to_member_of_reference_type) 9956 << dcl->getDeclName() << dcl->getType(); 9957 return QualType(); 9958 } 9959 9960 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 9961 Ctx = Ctx->getParent(); 9962 9963 QualType MPTy = Context.getMemberPointerType( 9964 op->getType(), 9965 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 9966 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9967 RequireCompleteType(OpLoc, MPTy, 0); 9968 return MPTy; 9969 } 9970 } 9971 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 9972 llvm_unreachable("Unknown/unexpected decl type"); 9973 } 9974 9975 if (AddressOfError != AO_No_Error) { 9976 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 9977 return QualType(); 9978 } 9979 9980 if (lval == Expr::LV_IncompleteVoidType) { 9981 // Taking the address of a void variable is technically illegal, but we 9982 // allow it in cases which are otherwise valid. 9983 // Example: "extern void x; void* y = &x;". 9984 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 9985 } 9986 9987 // If the operand has type "type", the result has type "pointer to type". 9988 if (op->getType()->isObjCObjectType()) 9989 return Context.getObjCObjectPointerType(op->getType()); 9990 return Context.getPointerType(op->getType()); 9991 } 9992 9993 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 9994 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 9995 if (!DRE) 9996 return; 9997 const Decl *D = DRE->getDecl(); 9998 if (!D) 9999 return; 10000 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10001 if (!Param) 10002 return; 10003 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10004 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10005 return; 10006 if (FunctionScopeInfo *FD = S.getCurFunction()) 10007 if (!FD->ModifiedNonNullParams.count(Param)) 10008 FD->ModifiedNonNullParams.insert(Param); 10009 } 10010 10011 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10012 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10013 SourceLocation OpLoc) { 10014 if (Op->isTypeDependent()) 10015 return S.Context.DependentTy; 10016 10017 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10018 if (ConvResult.isInvalid()) 10019 return QualType(); 10020 Op = ConvResult.get(); 10021 QualType OpTy = Op->getType(); 10022 QualType Result; 10023 10024 if (isa<CXXReinterpretCastExpr>(Op)) { 10025 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10026 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10027 Op->getSourceRange()); 10028 } 10029 10030 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10031 Result = PT->getPointeeType(); 10032 else if (const ObjCObjectPointerType *OPT = 10033 OpTy->getAs<ObjCObjectPointerType>()) 10034 Result = OPT->getPointeeType(); 10035 else { 10036 ExprResult PR = S.CheckPlaceholderExpr(Op); 10037 if (PR.isInvalid()) return QualType(); 10038 if (PR.get() != Op) 10039 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10040 } 10041 10042 if (Result.isNull()) { 10043 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10044 << OpTy << Op->getSourceRange(); 10045 return QualType(); 10046 } 10047 10048 // Note that per both C89 and C99, indirection is always legal, even if Result 10049 // is an incomplete type or void. It would be possible to warn about 10050 // dereferencing a void pointer, but it's completely well-defined, and such a 10051 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10052 // for pointers to 'void' but is fine for any other pointer type: 10053 // 10054 // C++ [expr.unary.op]p1: 10055 // [...] the expression to which [the unary * operator] is applied shall 10056 // be a pointer to an object type, or a pointer to a function type 10057 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10058 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10059 << OpTy << Op->getSourceRange(); 10060 10061 // Dereferences are usually l-values... 10062 VK = VK_LValue; 10063 10064 // ...except that certain expressions are never l-values in C. 10065 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10066 VK = VK_RValue; 10067 10068 return Result; 10069 } 10070 10071 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10072 BinaryOperatorKind Opc; 10073 switch (Kind) { 10074 default: llvm_unreachable("Unknown binop!"); 10075 case tok::periodstar: Opc = BO_PtrMemD; break; 10076 case tok::arrowstar: Opc = BO_PtrMemI; break; 10077 case tok::star: Opc = BO_Mul; break; 10078 case tok::slash: Opc = BO_Div; break; 10079 case tok::percent: Opc = BO_Rem; break; 10080 case tok::plus: Opc = BO_Add; break; 10081 case tok::minus: Opc = BO_Sub; break; 10082 case tok::lessless: Opc = BO_Shl; break; 10083 case tok::greatergreater: Opc = BO_Shr; break; 10084 case tok::lessequal: Opc = BO_LE; break; 10085 case tok::less: Opc = BO_LT; break; 10086 case tok::greaterequal: Opc = BO_GE; break; 10087 case tok::greater: Opc = BO_GT; break; 10088 case tok::exclaimequal: Opc = BO_NE; break; 10089 case tok::equalequal: Opc = BO_EQ; break; 10090 case tok::amp: Opc = BO_And; break; 10091 case tok::caret: Opc = BO_Xor; break; 10092 case tok::pipe: Opc = BO_Or; break; 10093 case tok::ampamp: Opc = BO_LAnd; break; 10094 case tok::pipepipe: Opc = BO_LOr; break; 10095 case tok::equal: Opc = BO_Assign; break; 10096 case tok::starequal: Opc = BO_MulAssign; break; 10097 case tok::slashequal: Opc = BO_DivAssign; break; 10098 case tok::percentequal: Opc = BO_RemAssign; break; 10099 case tok::plusequal: Opc = BO_AddAssign; break; 10100 case tok::minusequal: Opc = BO_SubAssign; break; 10101 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10102 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10103 case tok::ampequal: Opc = BO_AndAssign; break; 10104 case tok::caretequal: Opc = BO_XorAssign; break; 10105 case tok::pipeequal: Opc = BO_OrAssign; break; 10106 case tok::comma: Opc = BO_Comma; break; 10107 } 10108 return Opc; 10109 } 10110 10111 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10112 tok::TokenKind Kind) { 10113 UnaryOperatorKind Opc; 10114 switch (Kind) { 10115 default: llvm_unreachable("Unknown unary op!"); 10116 case tok::plusplus: Opc = UO_PreInc; break; 10117 case tok::minusminus: Opc = UO_PreDec; break; 10118 case tok::amp: Opc = UO_AddrOf; break; 10119 case tok::star: Opc = UO_Deref; break; 10120 case tok::plus: Opc = UO_Plus; break; 10121 case tok::minus: Opc = UO_Minus; break; 10122 case tok::tilde: Opc = UO_Not; break; 10123 case tok::exclaim: Opc = UO_LNot; break; 10124 case tok::kw___real: Opc = UO_Real; break; 10125 case tok::kw___imag: Opc = UO_Imag; break; 10126 case tok::kw___extension__: Opc = UO_Extension; break; 10127 } 10128 return Opc; 10129 } 10130 10131 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10132 /// This warning is only emitted for builtin assignment operations. It is also 10133 /// suppressed in the event of macro expansions. 10134 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10135 SourceLocation OpLoc) { 10136 if (!S.ActiveTemplateInstantiations.empty()) 10137 return; 10138 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10139 return; 10140 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10141 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10142 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10143 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10144 if (!LHSDeclRef || !RHSDeclRef || 10145 LHSDeclRef->getLocation().isMacroID() || 10146 RHSDeclRef->getLocation().isMacroID()) 10147 return; 10148 const ValueDecl *LHSDecl = 10149 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10150 const ValueDecl *RHSDecl = 10151 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10152 if (LHSDecl != RHSDecl) 10153 return; 10154 if (LHSDecl->getType().isVolatileQualified()) 10155 return; 10156 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10157 if (RefTy->getPointeeType().isVolatileQualified()) 10158 return; 10159 10160 S.Diag(OpLoc, diag::warn_self_assignment) 10161 << LHSDeclRef->getType() 10162 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10163 } 10164 10165 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10166 /// is usually indicative of introspection within the Objective-C pointer. 10167 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10168 SourceLocation OpLoc) { 10169 if (!S.getLangOpts().ObjC1) 10170 return; 10171 10172 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10173 const Expr *LHS = L.get(); 10174 const Expr *RHS = R.get(); 10175 10176 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10177 ObjCPointerExpr = LHS; 10178 OtherExpr = RHS; 10179 } 10180 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10181 ObjCPointerExpr = RHS; 10182 OtherExpr = LHS; 10183 } 10184 10185 // This warning is deliberately made very specific to reduce false 10186 // positives with logic that uses '&' for hashing. This logic mainly 10187 // looks for code trying to introspect into tagged pointers, which 10188 // code should generally never do. 10189 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10190 unsigned Diag = diag::warn_objc_pointer_masking; 10191 // Determine if we are introspecting the result of performSelectorXXX. 10192 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10193 // Special case messages to -performSelector and friends, which 10194 // can return non-pointer values boxed in a pointer value. 10195 // Some clients may wish to silence warnings in this subcase. 10196 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10197 Selector S = ME->getSelector(); 10198 StringRef SelArg0 = S.getNameForSlot(0); 10199 if (SelArg0.startswith("performSelector")) 10200 Diag = diag::warn_objc_pointer_masking_performSelector; 10201 } 10202 10203 S.Diag(OpLoc, Diag) 10204 << ObjCPointerExpr->getSourceRange(); 10205 } 10206 } 10207 10208 static NamedDecl *getDeclFromExpr(Expr *E) { 10209 if (!E) 10210 return nullptr; 10211 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10212 return DRE->getDecl(); 10213 if (auto *ME = dyn_cast<MemberExpr>(E)) 10214 return ME->getMemberDecl(); 10215 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10216 return IRE->getDecl(); 10217 return nullptr; 10218 } 10219 10220 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10221 /// operator @p Opc at location @c TokLoc. This routine only supports 10222 /// built-in operations; ActOnBinOp handles overloaded operators. 10223 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10224 BinaryOperatorKind Opc, 10225 Expr *LHSExpr, Expr *RHSExpr) { 10226 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10227 // The syntax only allows initializer lists on the RHS of assignment, 10228 // so we don't need to worry about accepting invalid code for 10229 // non-assignment operators. 10230 // C++11 5.17p9: 10231 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10232 // of x = {} is x = T(). 10233 InitializationKind Kind = 10234 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10235 InitializedEntity Entity = 10236 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10237 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10238 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10239 if (Init.isInvalid()) 10240 return Init; 10241 RHSExpr = Init.get(); 10242 } 10243 10244 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10245 QualType ResultTy; // Result type of the binary operator. 10246 // The following two variables are used for compound assignment operators 10247 QualType CompLHSTy; // Type of LHS after promotions for computation 10248 QualType CompResultTy; // Type of computation result 10249 ExprValueKind VK = VK_RValue; 10250 ExprObjectKind OK = OK_Ordinary; 10251 10252 if (!getLangOpts().CPlusPlus) { 10253 // C cannot handle TypoExpr nodes on either side of a binop because it 10254 // doesn't handle dependent types properly, so make sure any TypoExprs have 10255 // been dealt with before checking the operands. 10256 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10257 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10258 if (Opc != BO_Assign) 10259 return ExprResult(E); 10260 // Avoid correcting the RHS to the same Expr as the LHS. 10261 Decl *D = getDeclFromExpr(E); 10262 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10263 }); 10264 if (!LHS.isUsable() || !RHS.isUsable()) 10265 return ExprError(); 10266 } 10267 10268 if (getLangOpts().OpenCL) { 10269 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10270 // the ATOMIC_VAR_INIT macro. 10271 if (LHSExpr->getType()->isAtomicType() || 10272 RHSExpr->getType()->isAtomicType()) { 10273 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10274 if (BO_Assign == Opc) 10275 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10276 else 10277 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10278 return ExprError(); 10279 } 10280 } 10281 10282 switch (Opc) { 10283 case BO_Assign: 10284 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10285 if (getLangOpts().CPlusPlus && 10286 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10287 VK = LHS.get()->getValueKind(); 10288 OK = LHS.get()->getObjectKind(); 10289 } 10290 if (!ResultTy.isNull()) { 10291 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10292 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10293 } 10294 RecordModifiableNonNullParam(*this, LHS.get()); 10295 break; 10296 case BO_PtrMemD: 10297 case BO_PtrMemI: 10298 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10299 Opc == BO_PtrMemI); 10300 break; 10301 case BO_Mul: 10302 case BO_Div: 10303 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10304 Opc == BO_Div); 10305 break; 10306 case BO_Rem: 10307 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10308 break; 10309 case BO_Add: 10310 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10311 break; 10312 case BO_Sub: 10313 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10314 break; 10315 case BO_Shl: 10316 case BO_Shr: 10317 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10318 break; 10319 case BO_LE: 10320 case BO_LT: 10321 case BO_GE: 10322 case BO_GT: 10323 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10324 break; 10325 case BO_EQ: 10326 case BO_NE: 10327 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10328 break; 10329 case BO_And: 10330 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10331 case BO_Xor: 10332 case BO_Or: 10333 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10334 break; 10335 case BO_LAnd: 10336 case BO_LOr: 10337 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10338 break; 10339 case BO_MulAssign: 10340 case BO_DivAssign: 10341 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10342 Opc == BO_DivAssign); 10343 CompLHSTy = CompResultTy; 10344 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10345 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10346 break; 10347 case BO_RemAssign: 10348 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10349 CompLHSTy = CompResultTy; 10350 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10351 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10352 break; 10353 case BO_AddAssign: 10354 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10355 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10356 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10357 break; 10358 case BO_SubAssign: 10359 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10360 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10361 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10362 break; 10363 case BO_ShlAssign: 10364 case BO_ShrAssign: 10365 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10366 CompLHSTy = CompResultTy; 10367 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10368 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10369 break; 10370 case BO_AndAssign: 10371 case BO_OrAssign: // fallthrough 10372 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10373 case BO_XorAssign: 10374 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10375 CompLHSTy = CompResultTy; 10376 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10377 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10378 break; 10379 case BO_Comma: 10380 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10381 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10382 VK = RHS.get()->getValueKind(); 10383 OK = RHS.get()->getObjectKind(); 10384 } 10385 break; 10386 } 10387 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10388 return ExprError(); 10389 10390 // Check for array bounds violations for both sides of the BinaryOperator 10391 CheckArrayAccess(LHS.get()); 10392 CheckArrayAccess(RHS.get()); 10393 10394 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10395 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10396 &Context.Idents.get("object_setClass"), 10397 SourceLocation(), LookupOrdinaryName); 10398 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10399 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 10400 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10401 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10402 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10403 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10404 } 10405 else 10406 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10407 } 10408 else if (const ObjCIvarRefExpr *OIRE = 10409 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10410 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10411 10412 if (CompResultTy.isNull()) 10413 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10414 OK, OpLoc, FPFeatures.fp_contract); 10415 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10416 OK_ObjCProperty) { 10417 VK = VK_LValue; 10418 OK = LHS.get()->getObjectKind(); 10419 } 10420 return new (Context) CompoundAssignOperator( 10421 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10422 OpLoc, FPFeatures.fp_contract); 10423 } 10424 10425 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10426 /// operators are mixed in a way that suggests that the programmer forgot that 10427 /// comparison operators have higher precedence. The most typical example of 10428 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10429 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10430 SourceLocation OpLoc, Expr *LHSExpr, 10431 Expr *RHSExpr) { 10432 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10433 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10434 10435 // Check that one of the sides is a comparison operator. 10436 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10437 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10438 if (!isLeftComp && !isRightComp) 10439 return; 10440 10441 // Bitwise operations are sometimes used as eager logical ops. 10442 // Don't diagnose this. 10443 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10444 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10445 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 10446 return; 10447 10448 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10449 OpLoc) 10450 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10451 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10452 SourceRange ParensRange = isLeftComp ? 10453 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10454 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10455 10456 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10457 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10458 SuggestParentheses(Self, OpLoc, 10459 Self.PDiag(diag::note_precedence_silence) << OpStr, 10460 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10461 SuggestParentheses(Self, OpLoc, 10462 Self.PDiag(diag::note_precedence_bitwise_first) 10463 << BinaryOperator::getOpcodeStr(Opc), 10464 ParensRange); 10465 } 10466 10467 /// \brief It accepts a '&' expr that is inside a '|' one. 10468 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 10469 /// in parentheses. 10470 static void 10471 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 10472 BinaryOperator *Bop) { 10473 assert(Bop->getOpcode() == BO_And); 10474 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 10475 << Bop->getSourceRange() << OpLoc; 10476 SuggestParentheses(Self, Bop->getOperatorLoc(), 10477 Self.PDiag(diag::note_precedence_silence) 10478 << Bop->getOpcodeStr(), 10479 Bop->getSourceRange()); 10480 } 10481 10482 /// \brief It accepts a '&&' expr that is inside a '||' one. 10483 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10484 /// in parentheses. 10485 static void 10486 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10487 BinaryOperator *Bop) { 10488 assert(Bop->getOpcode() == BO_LAnd); 10489 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10490 << Bop->getSourceRange() << OpLoc; 10491 SuggestParentheses(Self, Bop->getOperatorLoc(), 10492 Self.PDiag(diag::note_precedence_silence) 10493 << Bop->getOpcodeStr(), 10494 Bop->getSourceRange()); 10495 } 10496 10497 /// \brief Returns true if the given expression can be evaluated as a constant 10498 /// 'true'. 10499 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10500 bool Res; 10501 return !E->isValueDependent() && 10502 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10503 } 10504 10505 /// \brief Returns true if the given expression can be evaluated as a constant 10506 /// 'false'. 10507 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10508 bool Res; 10509 return !E->isValueDependent() && 10510 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10511 } 10512 10513 /// \brief Look for '&&' in the left hand of a '||' expr. 10514 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10515 Expr *LHSExpr, Expr *RHSExpr) { 10516 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10517 if (Bop->getOpcode() == BO_LAnd) { 10518 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10519 if (EvaluatesAsFalse(S, RHSExpr)) 10520 return; 10521 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10522 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10523 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10524 } else if (Bop->getOpcode() == BO_LOr) { 10525 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10526 // If it's "a || b && 1 || c" we didn't warn earlier for 10527 // "a || b && 1", but warn now. 10528 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10529 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10530 } 10531 } 10532 } 10533 } 10534 10535 /// \brief Look for '&&' in the right hand of a '||' expr. 10536 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10537 Expr *LHSExpr, Expr *RHSExpr) { 10538 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10539 if (Bop->getOpcode() == BO_LAnd) { 10540 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10541 if (EvaluatesAsFalse(S, LHSExpr)) 10542 return; 10543 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10544 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10545 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10546 } 10547 } 10548 } 10549 10550 /// \brief Look for '&' in the left or right hand of a '|' expr. 10551 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 10552 Expr *OrArg) { 10553 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 10554 if (Bop->getOpcode() == BO_And) 10555 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 10556 } 10557 } 10558 10559 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10560 Expr *SubExpr, StringRef Shift) { 10561 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10562 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10563 StringRef Op = Bop->getOpcodeStr(); 10564 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10565 << Bop->getSourceRange() << OpLoc << Shift << Op; 10566 SuggestParentheses(S, Bop->getOperatorLoc(), 10567 S.PDiag(diag::note_precedence_silence) << Op, 10568 Bop->getSourceRange()); 10569 } 10570 } 10571 } 10572 10573 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10574 Expr *LHSExpr, Expr *RHSExpr) { 10575 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10576 if (!OCE) 10577 return; 10578 10579 FunctionDecl *FD = OCE->getDirectCallee(); 10580 if (!FD || !FD->isOverloadedOperator()) 10581 return; 10582 10583 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10584 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10585 return; 10586 10587 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10588 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10589 << (Kind == OO_LessLess); 10590 SuggestParentheses(S, OCE->getOperatorLoc(), 10591 S.PDiag(diag::note_precedence_silence) 10592 << (Kind == OO_LessLess ? "<<" : ">>"), 10593 OCE->getSourceRange()); 10594 SuggestParentheses(S, OpLoc, 10595 S.PDiag(diag::note_evaluate_comparison_first), 10596 SourceRange(OCE->getArg(1)->getLocStart(), 10597 RHSExpr->getLocEnd())); 10598 } 10599 10600 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10601 /// precedence. 10602 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10603 SourceLocation OpLoc, Expr *LHSExpr, 10604 Expr *RHSExpr){ 10605 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10606 if (BinaryOperator::isBitwiseOp(Opc)) 10607 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10608 10609 // Diagnose "arg1 & arg2 | arg3" 10610 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10611 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 10612 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 10613 } 10614 10615 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10616 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10617 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10618 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10619 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10620 } 10621 10622 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 10623 || Opc == BO_Shr) { 10624 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 10625 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 10626 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 10627 } 10628 10629 // Warn on overloaded shift operators and comparisons, such as: 10630 // cout << 5 == 4; 10631 if (BinaryOperator::isComparisonOp(Opc)) 10632 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 10633 } 10634 10635 // Binary Operators. 'Tok' is the token for the operator. 10636 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 10637 tok::TokenKind Kind, 10638 Expr *LHSExpr, Expr *RHSExpr) { 10639 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 10640 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 10641 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 10642 10643 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 10644 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 10645 10646 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 10647 } 10648 10649 /// Build an overloaded binary operator expression in the given scope. 10650 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 10651 BinaryOperatorKind Opc, 10652 Expr *LHS, Expr *RHS) { 10653 // Find all of the overloaded operators visible from this 10654 // point. We perform both an operator-name lookup from the local 10655 // scope and an argument-dependent lookup based on the types of 10656 // the arguments. 10657 UnresolvedSet<16> Functions; 10658 OverloadedOperatorKind OverOp 10659 = BinaryOperator::getOverloadedOperator(Opc); 10660 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 10661 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 10662 RHS->getType(), Functions); 10663 10664 // Build the (potentially-overloaded, potentially-dependent) 10665 // binary operation. 10666 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 10667 } 10668 10669 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 10670 BinaryOperatorKind Opc, 10671 Expr *LHSExpr, Expr *RHSExpr) { 10672 // We want to end up calling one of checkPseudoObjectAssignment 10673 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 10674 // both expressions are overloadable or either is type-dependent), 10675 // or CreateBuiltinBinOp (in any other case). We also want to get 10676 // any placeholder types out of the way. 10677 10678 // Handle pseudo-objects in the LHS. 10679 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 10680 // Assignments with a pseudo-object l-value need special analysis. 10681 if (pty->getKind() == BuiltinType::PseudoObject && 10682 BinaryOperator::isAssignmentOp(Opc)) 10683 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 10684 10685 // Don't resolve overloads if the other type is overloadable. 10686 if (pty->getKind() == BuiltinType::Overload) { 10687 // We can't actually test that if we still have a placeholder, 10688 // though. Fortunately, none of the exceptions we see in that 10689 // code below are valid when the LHS is an overload set. Note 10690 // that an overload set can be dependently-typed, but it never 10691 // instantiates to having an overloadable type. 10692 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10693 if (resolvedRHS.isInvalid()) return ExprError(); 10694 RHSExpr = resolvedRHS.get(); 10695 10696 if (RHSExpr->isTypeDependent() || 10697 RHSExpr->getType()->isOverloadableType()) 10698 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10699 } 10700 10701 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 10702 if (LHS.isInvalid()) return ExprError(); 10703 LHSExpr = LHS.get(); 10704 } 10705 10706 // Handle pseudo-objects in the RHS. 10707 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 10708 // An overload in the RHS can potentially be resolved by the type 10709 // being assigned to. 10710 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 10711 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10712 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10713 10714 if (LHSExpr->getType()->isOverloadableType()) 10715 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10716 10717 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10718 } 10719 10720 // Don't resolve overloads if the other type is overloadable. 10721 if (pty->getKind() == BuiltinType::Overload && 10722 LHSExpr->getType()->isOverloadableType()) 10723 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10724 10725 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10726 if (!resolvedRHS.isUsable()) return ExprError(); 10727 RHSExpr = resolvedRHS.get(); 10728 } 10729 10730 if (getLangOpts().CPlusPlus) { 10731 // If either expression is type-dependent, always build an 10732 // overloaded op. 10733 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10734 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10735 10736 // Otherwise, build an overloaded op if either expression has an 10737 // overloadable type. 10738 if (LHSExpr->getType()->isOverloadableType() || 10739 RHSExpr->getType()->isOverloadableType()) 10740 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10741 } 10742 10743 // Build a built-in binary operation. 10744 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10745 } 10746 10747 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 10748 UnaryOperatorKind Opc, 10749 Expr *InputExpr) { 10750 ExprResult Input = InputExpr; 10751 ExprValueKind VK = VK_RValue; 10752 ExprObjectKind OK = OK_Ordinary; 10753 QualType resultType; 10754 if (getLangOpts().OpenCL) { 10755 // The only legal unary operation for atomics is '&'. 10756 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 10757 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10758 << InputExpr->getType() 10759 << Input.get()->getSourceRange()); 10760 } 10761 } 10762 switch (Opc) { 10763 case UO_PreInc: 10764 case UO_PreDec: 10765 case UO_PostInc: 10766 case UO_PostDec: 10767 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 10768 OpLoc, 10769 Opc == UO_PreInc || 10770 Opc == UO_PostInc, 10771 Opc == UO_PreInc || 10772 Opc == UO_PreDec); 10773 break; 10774 case UO_AddrOf: 10775 resultType = CheckAddressOfOperand(Input, OpLoc); 10776 RecordModifiableNonNullParam(*this, InputExpr); 10777 break; 10778 case UO_Deref: { 10779 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10780 if (Input.isInvalid()) return ExprError(); 10781 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 10782 break; 10783 } 10784 case UO_Plus: 10785 case UO_Minus: 10786 Input = UsualUnaryConversions(Input.get()); 10787 if (Input.isInvalid()) return ExprError(); 10788 resultType = Input.get()->getType(); 10789 if (resultType->isDependentType()) 10790 break; 10791 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 10792 break; 10793 else if (resultType->isVectorType() && 10794 // The z vector extensions don't allow + or - with bool vectors. 10795 (!Context.getLangOpts().ZVector || 10796 resultType->getAs<VectorType>()->getVectorKind() != 10797 VectorType::AltiVecBool)) 10798 break; 10799 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 10800 Opc == UO_Plus && 10801 resultType->isPointerType()) 10802 break; 10803 10804 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10805 << resultType << Input.get()->getSourceRange()); 10806 10807 case UO_Not: // bitwise complement 10808 Input = UsualUnaryConversions(Input.get()); 10809 if (Input.isInvalid()) 10810 return ExprError(); 10811 resultType = Input.get()->getType(); 10812 if (resultType->isDependentType()) 10813 break; 10814 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 10815 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 10816 // C99 does not support '~' for complex conjugation. 10817 Diag(OpLoc, diag::ext_integer_complement_complex) 10818 << resultType << Input.get()->getSourceRange(); 10819 else if (resultType->hasIntegerRepresentation()) 10820 break; 10821 else if (resultType->isExtVectorType()) { 10822 if (Context.getLangOpts().OpenCL) { 10823 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 10824 // on vector float types. 10825 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10826 if (!T->isIntegerType()) 10827 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10828 << resultType << Input.get()->getSourceRange()); 10829 } 10830 break; 10831 } else { 10832 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10833 << resultType << Input.get()->getSourceRange()); 10834 } 10835 break; 10836 10837 case UO_LNot: // logical negation 10838 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 10839 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10840 if (Input.isInvalid()) return ExprError(); 10841 resultType = Input.get()->getType(); 10842 10843 // Though we still have to promote half FP to float... 10844 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 10845 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 10846 resultType = Context.FloatTy; 10847 } 10848 10849 if (resultType->isDependentType()) 10850 break; 10851 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 10852 // C99 6.5.3.3p1: ok, fallthrough; 10853 if (Context.getLangOpts().CPlusPlus) { 10854 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 10855 // operand contextually converted to bool. 10856 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 10857 ScalarTypeToBooleanCastKind(resultType)); 10858 } else if (Context.getLangOpts().OpenCL && 10859 Context.getLangOpts().OpenCLVersion < 120) { 10860 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10861 // operate on scalar float types. 10862 if (!resultType->isIntegerType()) 10863 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10864 << resultType << Input.get()->getSourceRange()); 10865 } 10866 } else if (resultType->isExtVectorType()) { 10867 if (Context.getLangOpts().OpenCL && 10868 Context.getLangOpts().OpenCLVersion < 120) { 10869 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10870 // operate on vector float types. 10871 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10872 if (!T->isIntegerType()) 10873 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10874 << resultType << Input.get()->getSourceRange()); 10875 } 10876 // Vector logical not returns the signed variant of the operand type. 10877 resultType = GetSignedVectorType(resultType); 10878 break; 10879 } else { 10880 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10881 << resultType << Input.get()->getSourceRange()); 10882 } 10883 10884 // LNot always has type int. C99 6.5.3.3p5. 10885 // In C++, it's bool. C++ 5.3.1p8 10886 resultType = Context.getLogicalOperationType(); 10887 break; 10888 case UO_Real: 10889 case UO_Imag: 10890 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 10891 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 10892 // complex l-values to ordinary l-values and all other values to r-values. 10893 if (Input.isInvalid()) return ExprError(); 10894 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 10895 if (Input.get()->getValueKind() != VK_RValue && 10896 Input.get()->getObjectKind() == OK_Ordinary) 10897 VK = Input.get()->getValueKind(); 10898 } else if (!getLangOpts().CPlusPlus) { 10899 // In C, a volatile scalar is read by __imag. In C++, it is not. 10900 Input = DefaultLvalueConversion(Input.get()); 10901 } 10902 break; 10903 case UO_Extension: 10904 case UO_Coawait: 10905 resultType = Input.get()->getType(); 10906 VK = Input.get()->getValueKind(); 10907 OK = Input.get()->getObjectKind(); 10908 break; 10909 } 10910 if (resultType.isNull() || Input.isInvalid()) 10911 return ExprError(); 10912 10913 // Check for array bounds violations in the operand of the UnaryOperator, 10914 // except for the '*' and '&' operators that have to be handled specially 10915 // by CheckArrayAccess (as there are special cases like &array[arraysize] 10916 // that are explicitly defined as valid by the standard). 10917 if (Opc != UO_AddrOf && Opc != UO_Deref) 10918 CheckArrayAccess(Input.get()); 10919 10920 return new (Context) 10921 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 10922 } 10923 10924 /// \brief Determine whether the given expression is a qualified member 10925 /// access expression, of a form that could be turned into a pointer to member 10926 /// with the address-of operator. 10927 static bool isQualifiedMemberAccess(Expr *E) { 10928 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10929 if (!DRE->getQualifier()) 10930 return false; 10931 10932 ValueDecl *VD = DRE->getDecl(); 10933 if (!VD->isCXXClassMember()) 10934 return false; 10935 10936 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 10937 return true; 10938 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 10939 return Method->isInstance(); 10940 10941 return false; 10942 } 10943 10944 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 10945 if (!ULE->getQualifier()) 10946 return false; 10947 10948 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 10949 DEnd = ULE->decls_end(); 10950 D != DEnd; ++D) { 10951 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 10952 if (Method->isInstance()) 10953 return true; 10954 } else { 10955 // Overload set does not contain methods. 10956 break; 10957 } 10958 } 10959 10960 return false; 10961 } 10962 10963 return false; 10964 } 10965 10966 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 10967 UnaryOperatorKind Opc, Expr *Input) { 10968 // First things first: handle placeholders so that the 10969 // overloaded-operator check considers the right type. 10970 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 10971 // Increment and decrement of pseudo-object references. 10972 if (pty->getKind() == BuiltinType::PseudoObject && 10973 UnaryOperator::isIncrementDecrementOp(Opc)) 10974 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 10975 10976 // extension is always a builtin operator. 10977 if (Opc == UO_Extension) 10978 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10979 10980 // & gets special logic for several kinds of placeholder. 10981 // The builtin code knows what to do. 10982 if (Opc == UO_AddrOf && 10983 (pty->getKind() == BuiltinType::Overload || 10984 pty->getKind() == BuiltinType::UnknownAny || 10985 pty->getKind() == BuiltinType::BoundMember)) 10986 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10987 10988 // Anything else needs to be handled now. 10989 ExprResult Result = CheckPlaceholderExpr(Input); 10990 if (Result.isInvalid()) return ExprError(); 10991 Input = Result.get(); 10992 } 10993 10994 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 10995 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 10996 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 10997 // Find all of the overloaded operators visible from this 10998 // point. We perform both an operator-name lookup from the local 10999 // scope and an argument-dependent lookup based on the types of 11000 // the arguments. 11001 UnresolvedSet<16> Functions; 11002 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11003 if (S && OverOp != OO_None) 11004 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11005 Functions); 11006 11007 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11008 } 11009 11010 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11011 } 11012 11013 // Unary Operators. 'Tok' is the token for the operator. 11014 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11015 tok::TokenKind Op, Expr *Input) { 11016 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11017 } 11018 11019 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11020 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11021 LabelDecl *TheDecl) { 11022 TheDecl->markUsed(Context); 11023 // Create the AST node. The address of a label always has type 'void*'. 11024 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11025 Context.getPointerType(Context.VoidTy)); 11026 } 11027 11028 /// Given the last statement in a statement-expression, check whether 11029 /// the result is a producing expression (like a call to an 11030 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11031 /// release out of the full-expression. Otherwise, return null. 11032 /// Cannot fail. 11033 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11034 // Should always be wrapped with one of these. 11035 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11036 if (!cleanups) return nullptr; 11037 11038 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11039 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11040 return nullptr; 11041 11042 // Splice out the cast. This shouldn't modify any interesting 11043 // features of the statement. 11044 Expr *producer = cast->getSubExpr(); 11045 assert(producer->getType() == cast->getType()); 11046 assert(producer->getValueKind() == cast->getValueKind()); 11047 cleanups->setSubExpr(producer); 11048 return cleanups; 11049 } 11050 11051 void Sema::ActOnStartStmtExpr() { 11052 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11053 } 11054 11055 void Sema::ActOnStmtExprError() { 11056 // Note that function is also called by TreeTransform when leaving a 11057 // StmtExpr scope without rebuilding anything. 11058 11059 DiscardCleanupsInEvaluationContext(); 11060 PopExpressionEvaluationContext(); 11061 } 11062 11063 ExprResult 11064 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11065 SourceLocation RPLoc) { // "({..})" 11066 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11067 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11068 11069 if (hasAnyUnrecoverableErrorsInThisFunction()) 11070 DiscardCleanupsInEvaluationContext(); 11071 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11072 PopExpressionEvaluationContext(); 11073 11074 // FIXME: there are a variety of strange constraints to enforce here, for 11075 // example, it is not possible to goto into a stmt expression apparently. 11076 // More semantic analysis is needed. 11077 11078 // If there are sub-stmts in the compound stmt, take the type of the last one 11079 // as the type of the stmtexpr. 11080 QualType Ty = Context.VoidTy; 11081 bool StmtExprMayBindToTemp = false; 11082 if (!Compound->body_empty()) { 11083 Stmt *LastStmt = Compound->body_back(); 11084 LabelStmt *LastLabelStmt = nullptr; 11085 // If LastStmt is a label, skip down through into the body. 11086 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11087 LastLabelStmt = Label; 11088 LastStmt = Label->getSubStmt(); 11089 } 11090 11091 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11092 // Do function/array conversion on the last expression, but not 11093 // lvalue-to-rvalue. However, initialize an unqualified type. 11094 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11095 if (LastExpr.isInvalid()) 11096 return ExprError(); 11097 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11098 11099 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11100 // In ARC, if the final expression ends in a consume, splice 11101 // the consume out and bind it later. In the alternate case 11102 // (when dealing with a retainable type), the result 11103 // initialization will create a produce. In both cases the 11104 // result will be +1, and we'll need to balance that out with 11105 // a bind. 11106 if (Expr *rebuiltLastStmt 11107 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11108 LastExpr = rebuiltLastStmt; 11109 } else { 11110 LastExpr = PerformCopyInitialization( 11111 InitializedEntity::InitializeResult(LPLoc, 11112 Ty, 11113 false), 11114 SourceLocation(), 11115 LastExpr); 11116 } 11117 11118 if (LastExpr.isInvalid()) 11119 return ExprError(); 11120 if (LastExpr.get() != nullptr) { 11121 if (!LastLabelStmt) 11122 Compound->setLastStmt(LastExpr.get()); 11123 else 11124 LastLabelStmt->setSubStmt(LastExpr.get()); 11125 StmtExprMayBindToTemp = true; 11126 } 11127 } 11128 } 11129 } 11130 11131 // FIXME: Check that expression type is complete/non-abstract; statement 11132 // expressions are not lvalues. 11133 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11134 if (StmtExprMayBindToTemp) 11135 return MaybeBindToTemporary(ResStmtExpr); 11136 return ResStmtExpr; 11137 } 11138 11139 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11140 TypeSourceInfo *TInfo, 11141 ArrayRef<OffsetOfComponent> Components, 11142 SourceLocation RParenLoc) { 11143 QualType ArgTy = TInfo->getType(); 11144 bool Dependent = ArgTy->isDependentType(); 11145 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11146 11147 // We must have at least one component that refers to the type, and the first 11148 // one is known to be a field designator. Verify that the ArgTy represents 11149 // a struct/union/class. 11150 if (!Dependent && !ArgTy->isRecordType()) 11151 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11152 << ArgTy << TypeRange); 11153 11154 // Type must be complete per C99 7.17p3 because a declaring a variable 11155 // with an incomplete type would be ill-formed. 11156 if (!Dependent 11157 && RequireCompleteType(BuiltinLoc, ArgTy, 11158 diag::err_offsetof_incomplete_type, TypeRange)) 11159 return ExprError(); 11160 11161 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11162 // GCC extension, diagnose them. 11163 // FIXME: This diagnostic isn't actually visible because the location is in 11164 // a system header! 11165 if (Components.size() != 1) 11166 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11167 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11168 11169 bool DidWarnAboutNonPOD = false; 11170 QualType CurrentType = ArgTy; 11171 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 11172 SmallVector<OffsetOfNode, 4> Comps; 11173 SmallVector<Expr*, 4> Exprs; 11174 for (const OffsetOfComponent &OC : Components) { 11175 if (OC.isBrackets) { 11176 // Offset of an array sub-field. TODO: Should we allow vector elements? 11177 if (!CurrentType->isDependentType()) { 11178 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11179 if(!AT) 11180 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11181 << CurrentType); 11182 CurrentType = AT->getElementType(); 11183 } else 11184 CurrentType = Context.DependentTy; 11185 11186 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11187 if (IdxRval.isInvalid()) 11188 return ExprError(); 11189 Expr *Idx = IdxRval.get(); 11190 11191 // The expression must be an integral expression. 11192 // FIXME: An integral constant expression? 11193 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11194 !Idx->getType()->isIntegerType()) 11195 return ExprError(Diag(Idx->getLocStart(), 11196 diag::err_typecheck_subscript_not_integer) 11197 << Idx->getSourceRange()); 11198 11199 // Record this array index. 11200 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11201 Exprs.push_back(Idx); 11202 continue; 11203 } 11204 11205 // Offset of a field. 11206 if (CurrentType->isDependentType()) { 11207 // We have the offset of a field, but we can't look into the dependent 11208 // type. Just record the identifier of the field. 11209 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11210 CurrentType = Context.DependentTy; 11211 continue; 11212 } 11213 11214 // We need to have a complete type to look into. 11215 if (RequireCompleteType(OC.LocStart, CurrentType, 11216 diag::err_offsetof_incomplete_type)) 11217 return ExprError(); 11218 11219 // Look for the designated field. 11220 const RecordType *RC = CurrentType->getAs<RecordType>(); 11221 if (!RC) 11222 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11223 << CurrentType); 11224 RecordDecl *RD = RC->getDecl(); 11225 11226 // C++ [lib.support.types]p5: 11227 // The macro offsetof accepts a restricted set of type arguments in this 11228 // International Standard. type shall be a POD structure or a POD union 11229 // (clause 9). 11230 // C++11 [support.types]p4: 11231 // If type is not a standard-layout class (Clause 9), the results are 11232 // undefined. 11233 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11234 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11235 unsigned DiagID = 11236 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11237 : diag::ext_offsetof_non_pod_type; 11238 11239 if (!IsSafe && !DidWarnAboutNonPOD && 11240 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11241 PDiag(DiagID) 11242 << SourceRange(Components[0].LocStart, OC.LocEnd) 11243 << CurrentType)) 11244 DidWarnAboutNonPOD = true; 11245 } 11246 11247 // Look for the field. 11248 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11249 LookupQualifiedName(R, RD); 11250 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11251 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11252 if (!MemberDecl) { 11253 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11254 MemberDecl = IndirectMemberDecl->getAnonField(); 11255 } 11256 11257 if (!MemberDecl) 11258 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11259 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11260 OC.LocEnd)); 11261 11262 // C99 7.17p3: 11263 // (If the specified member is a bit-field, the behavior is undefined.) 11264 // 11265 // We diagnose this as an error. 11266 if (MemberDecl->isBitField()) { 11267 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11268 << MemberDecl->getDeclName() 11269 << SourceRange(BuiltinLoc, RParenLoc); 11270 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11271 return ExprError(); 11272 } 11273 11274 RecordDecl *Parent = MemberDecl->getParent(); 11275 if (IndirectMemberDecl) 11276 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11277 11278 // If the member was found in a base class, introduce OffsetOfNodes for 11279 // the base class indirections. 11280 CXXBasePaths Paths; 11281 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 11282 if (Paths.getDetectedVirtual()) { 11283 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11284 << MemberDecl->getDeclName() 11285 << SourceRange(BuiltinLoc, RParenLoc); 11286 return ExprError(); 11287 } 11288 11289 CXXBasePath &Path = Paths.front(); 11290 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 11291 B != BEnd; ++B) 11292 Comps.push_back(OffsetOfNode(B->Base)); 11293 } 11294 11295 if (IndirectMemberDecl) { 11296 for (auto *FI : IndirectMemberDecl->chain()) { 11297 assert(isa<FieldDecl>(FI)); 11298 Comps.push_back(OffsetOfNode(OC.LocStart, 11299 cast<FieldDecl>(FI), OC.LocEnd)); 11300 } 11301 } else 11302 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11303 11304 CurrentType = MemberDecl->getType().getNonReferenceType(); 11305 } 11306 11307 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11308 Comps, Exprs, RParenLoc); 11309 } 11310 11311 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11312 SourceLocation BuiltinLoc, 11313 SourceLocation TypeLoc, 11314 ParsedType ParsedArgTy, 11315 ArrayRef<OffsetOfComponent> Components, 11316 SourceLocation RParenLoc) { 11317 11318 TypeSourceInfo *ArgTInfo; 11319 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11320 if (ArgTy.isNull()) 11321 return ExprError(); 11322 11323 if (!ArgTInfo) 11324 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11325 11326 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11327 } 11328 11329 11330 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11331 Expr *CondExpr, 11332 Expr *LHSExpr, Expr *RHSExpr, 11333 SourceLocation RPLoc) { 11334 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11335 11336 ExprValueKind VK = VK_RValue; 11337 ExprObjectKind OK = OK_Ordinary; 11338 QualType resType; 11339 bool ValueDependent = false; 11340 bool CondIsTrue = false; 11341 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11342 resType = Context.DependentTy; 11343 ValueDependent = true; 11344 } else { 11345 // The conditional expression is required to be a constant expression. 11346 llvm::APSInt condEval(32); 11347 ExprResult CondICE 11348 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11349 diag::err_typecheck_choose_expr_requires_constant, false); 11350 if (CondICE.isInvalid()) 11351 return ExprError(); 11352 CondExpr = CondICE.get(); 11353 CondIsTrue = condEval.getZExtValue(); 11354 11355 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11356 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11357 11358 resType = ActiveExpr->getType(); 11359 ValueDependent = ActiveExpr->isValueDependent(); 11360 VK = ActiveExpr->getValueKind(); 11361 OK = ActiveExpr->getObjectKind(); 11362 } 11363 11364 return new (Context) 11365 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11366 CondIsTrue, resType->isDependentType(), ValueDependent); 11367 } 11368 11369 //===----------------------------------------------------------------------===// 11370 // Clang Extensions. 11371 //===----------------------------------------------------------------------===// 11372 11373 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11374 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11375 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11376 11377 if (LangOpts.CPlusPlus) { 11378 Decl *ManglingContextDecl; 11379 if (MangleNumberingContext *MCtx = 11380 getCurrentMangleNumberContext(Block->getDeclContext(), 11381 ManglingContextDecl)) { 11382 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11383 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11384 } 11385 } 11386 11387 PushBlockScope(CurScope, Block); 11388 CurContext->addDecl(Block); 11389 if (CurScope) 11390 PushDeclContext(CurScope, Block); 11391 else 11392 CurContext = Block; 11393 11394 getCurBlock()->HasImplicitReturnType = true; 11395 11396 // Enter a new evaluation context to insulate the block from any 11397 // cleanups from the enclosing full-expression. 11398 PushExpressionEvaluationContext(PotentiallyEvaluated); 11399 } 11400 11401 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11402 Scope *CurScope) { 11403 assert(ParamInfo.getIdentifier() == nullptr && 11404 "block-id should have no identifier!"); 11405 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11406 BlockScopeInfo *CurBlock = getCurBlock(); 11407 11408 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11409 QualType T = Sig->getType(); 11410 11411 // FIXME: We should allow unexpanded parameter packs here, but that would, 11412 // in turn, make the block expression contain unexpanded parameter packs. 11413 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11414 // Drop the parameters. 11415 FunctionProtoType::ExtProtoInfo EPI; 11416 EPI.HasTrailingReturn = false; 11417 EPI.TypeQuals |= DeclSpec::TQ_const; 11418 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11419 Sig = Context.getTrivialTypeSourceInfo(T); 11420 } 11421 11422 // GetTypeForDeclarator always produces a function type for a block 11423 // literal signature. Furthermore, it is always a FunctionProtoType 11424 // unless the function was written with a typedef. 11425 assert(T->isFunctionType() && 11426 "GetTypeForDeclarator made a non-function block signature"); 11427 11428 // Look for an explicit signature in that function type. 11429 FunctionProtoTypeLoc ExplicitSignature; 11430 11431 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11432 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11433 11434 // Check whether that explicit signature was synthesized by 11435 // GetTypeForDeclarator. If so, don't save that as part of the 11436 // written signature. 11437 if (ExplicitSignature.getLocalRangeBegin() == 11438 ExplicitSignature.getLocalRangeEnd()) { 11439 // This would be much cheaper if we stored TypeLocs instead of 11440 // TypeSourceInfos. 11441 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11442 unsigned Size = Result.getFullDataSize(); 11443 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11444 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11445 11446 ExplicitSignature = FunctionProtoTypeLoc(); 11447 } 11448 } 11449 11450 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11451 CurBlock->FunctionType = T; 11452 11453 const FunctionType *Fn = T->getAs<FunctionType>(); 11454 QualType RetTy = Fn->getReturnType(); 11455 bool isVariadic = 11456 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11457 11458 CurBlock->TheDecl->setIsVariadic(isVariadic); 11459 11460 // Context.DependentTy is used as a placeholder for a missing block 11461 // return type. TODO: what should we do with declarators like: 11462 // ^ * { ... } 11463 // If the answer is "apply template argument deduction".... 11464 if (RetTy != Context.DependentTy) { 11465 CurBlock->ReturnType = RetTy; 11466 CurBlock->TheDecl->setBlockMissingReturnType(false); 11467 CurBlock->HasImplicitReturnType = false; 11468 } 11469 11470 // Push block parameters from the declarator if we had them. 11471 SmallVector<ParmVarDecl*, 8> Params; 11472 if (ExplicitSignature) { 11473 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11474 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11475 if (Param->getIdentifier() == nullptr && 11476 !Param->isImplicit() && 11477 !Param->isInvalidDecl() && 11478 !getLangOpts().CPlusPlus) 11479 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11480 Params.push_back(Param); 11481 } 11482 11483 // Fake up parameter variables if we have a typedef, like 11484 // ^ fntype { ... } 11485 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11486 for (const auto &I : Fn->param_types()) { 11487 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11488 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11489 Params.push_back(Param); 11490 } 11491 } 11492 11493 // Set the parameters on the block decl. 11494 if (!Params.empty()) { 11495 CurBlock->TheDecl->setParams(Params); 11496 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11497 CurBlock->TheDecl->param_end(), 11498 /*CheckParameterNames=*/false); 11499 } 11500 11501 // Finally we can process decl attributes. 11502 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11503 11504 // Put the parameter variables in scope. 11505 for (auto AI : CurBlock->TheDecl->params()) { 11506 AI->setOwningFunction(CurBlock->TheDecl); 11507 11508 // If this has an identifier, add it to the scope stack. 11509 if (AI->getIdentifier()) { 11510 CheckShadow(CurBlock->TheScope, AI); 11511 11512 PushOnScopeChains(AI, CurBlock->TheScope); 11513 } 11514 } 11515 } 11516 11517 /// ActOnBlockError - If there is an error parsing a block, this callback 11518 /// is invoked to pop the information about the block from the action impl. 11519 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11520 // Leave the expression-evaluation context. 11521 DiscardCleanupsInEvaluationContext(); 11522 PopExpressionEvaluationContext(); 11523 11524 // Pop off CurBlock, handle nested blocks. 11525 PopDeclContext(); 11526 PopFunctionScopeInfo(); 11527 } 11528 11529 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11530 /// literal was successfully completed. ^(int x){...} 11531 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11532 Stmt *Body, Scope *CurScope) { 11533 // If blocks are disabled, emit an error. 11534 if (!LangOpts.Blocks) 11535 Diag(CaretLoc, diag::err_blocks_disable); 11536 11537 // Leave the expression-evaluation context. 11538 if (hasAnyUnrecoverableErrorsInThisFunction()) 11539 DiscardCleanupsInEvaluationContext(); 11540 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11541 PopExpressionEvaluationContext(); 11542 11543 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11544 11545 if (BSI->HasImplicitReturnType) 11546 deduceClosureReturnType(*BSI); 11547 11548 PopDeclContext(); 11549 11550 QualType RetTy = Context.VoidTy; 11551 if (!BSI->ReturnType.isNull()) 11552 RetTy = BSI->ReturnType; 11553 11554 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11555 QualType BlockTy; 11556 11557 // Set the captured variables on the block. 11558 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11559 SmallVector<BlockDecl::Capture, 4> Captures; 11560 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 11561 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 11562 if (Cap.isThisCapture()) 11563 continue; 11564 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11565 Cap.isNested(), Cap.getInitExpr()); 11566 Captures.push_back(NewCap); 11567 } 11568 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 11569 11570 // If the user wrote a function type in some form, try to use that. 11571 if (!BSI->FunctionType.isNull()) { 11572 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11573 11574 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11575 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11576 11577 // Turn protoless block types into nullary block types. 11578 if (isa<FunctionNoProtoType>(FTy)) { 11579 FunctionProtoType::ExtProtoInfo EPI; 11580 EPI.ExtInfo = Ext; 11581 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11582 11583 // Otherwise, if we don't need to change anything about the function type, 11584 // preserve its sugar structure. 11585 } else if (FTy->getReturnType() == RetTy && 11586 (!NoReturn || FTy->getNoReturnAttr())) { 11587 BlockTy = BSI->FunctionType; 11588 11589 // Otherwise, make the minimal modifications to the function type. 11590 } else { 11591 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11592 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11593 EPI.TypeQuals = 0; // FIXME: silently? 11594 EPI.ExtInfo = Ext; 11595 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11596 } 11597 11598 // If we don't have a function type, just build one from nothing. 11599 } else { 11600 FunctionProtoType::ExtProtoInfo EPI; 11601 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11602 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11603 } 11604 11605 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11606 BSI->TheDecl->param_end()); 11607 BlockTy = Context.getBlockPointerType(BlockTy); 11608 11609 // If needed, diagnose invalid gotos and switches in the block. 11610 if (getCurFunction()->NeedsScopeChecking() && 11611 !PP.isCodeCompletionEnabled()) 11612 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11613 11614 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11615 11616 // Try to apply the named return value optimization. We have to check again 11617 // if we can do this, though, because blocks keep return statements around 11618 // to deduce an implicit return type. 11619 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11620 !BSI->TheDecl->isDependentContext()) 11621 computeNRVO(Body, BSI); 11622 11623 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11624 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11625 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11626 11627 // If the block isn't obviously global, i.e. it captures anything at 11628 // all, then we need to do a few things in the surrounding context: 11629 if (Result->getBlockDecl()->hasCaptures()) { 11630 // First, this expression has a new cleanup object. 11631 ExprCleanupObjects.push_back(Result->getBlockDecl()); 11632 ExprNeedsCleanups = true; 11633 11634 // It also gets a branch-protected scope if any of the captured 11635 // variables needs destruction. 11636 for (const auto &CI : Result->getBlockDecl()->captures()) { 11637 const VarDecl *var = CI.getVariable(); 11638 if (var->getType().isDestructedType() != QualType::DK_none) { 11639 getCurFunction()->setHasBranchProtectedScope(); 11640 break; 11641 } 11642 } 11643 } 11644 11645 return Result; 11646 } 11647 11648 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 11649 Expr *E, ParsedType Ty, 11650 SourceLocation RPLoc) { 11651 TypeSourceInfo *TInfo; 11652 GetTypeFromParser(Ty, &TInfo); 11653 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 11654 } 11655 11656 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 11657 Expr *E, TypeSourceInfo *TInfo, 11658 SourceLocation RPLoc) { 11659 Expr *OrigExpr = E; 11660 bool IsMS = false; 11661 11662 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 11663 // as Microsoft ABI on an actual Microsoft platform, where 11664 // __builtin_ms_va_list and __builtin_va_list are the same.) 11665 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 11666 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 11667 QualType MSVaListType = Context.getBuiltinMSVaListType(); 11668 if (Context.hasSameType(MSVaListType, E->getType())) { 11669 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11670 return ExprError(); 11671 IsMS = true; 11672 } 11673 } 11674 11675 // Get the va_list type 11676 QualType VaListType = Context.getBuiltinVaListType(); 11677 if (!IsMS) { 11678 if (VaListType->isArrayType()) { 11679 // Deal with implicit array decay; for example, on x86-64, 11680 // va_list is an array, but it's supposed to decay to 11681 // a pointer for va_arg. 11682 VaListType = Context.getArrayDecayedType(VaListType); 11683 // Make sure the input expression also decays appropriately. 11684 ExprResult Result = UsualUnaryConversions(E); 11685 if (Result.isInvalid()) 11686 return ExprError(); 11687 E = Result.get(); 11688 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 11689 // If va_list is a record type and we are compiling in C++ mode, 11690 // check the argument using reference binding. 11691 InitializedEntity Entity = InitializedEntity::InitializeParameter( 11692 Context, Context.getLValueReferenceType(VaListType), false); 11693 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 11694 if (Init.isInvalid()) 11695 return ExprError(); 11696 E = Init.getAs<Expr>(); 11697 } else { 11698 // Otherwise, the va_list argument must be an l-value because 11699 // it is modified by va_arg. 11700 if (!E->isTypeDependent() && 11701 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11702 return ExprError(); 11703 } 11704 } 11705 11706 if (!IsMS && !E->isTypeDependent() && 11707 !Context.hasSameType(VaListType, E->getType())) 11708 return ExprError(Diag(E->getLocStart(), 11709 diag::err_first_argument_to_va_arg_not_of_type_va_list) 11710 << OrigExpr->getType() << E->getSourceRange()); 11711 11712 if (!TInfo->getType()->isDependentType()) { 11713 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 11714 diag::err_second_parameter_to_va_arg_incomplete, 11715 TInfo->getTypeLoc())) 11716 return ExprError(); 11717 11718 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 11719 TInfo->getType(), 11720 diag::err_second_parameter_to_va_arg_abstract, 11721 TInfo->getTypeLoc())) 11722 return ExprError(); 11723 11724 if (!TInfo->getType().isPODType(Context)) { 11725 Diag(TInfo->getTypeLoc().getBeginLoc(), 11726 TInfo->getType()->isObjCLifetimeType() 11727 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 11728 : diag::warn_second_parameter_to_va_arg_not_pod) 11729 << TInfo->getType() 11730 << TInfo->getTypeLoc().getSourceRange(); 11731 } 11732 11733 // Check for va_arg where arguments of the given type will be promoted 11734 // (i.e. this va_arg is guaranteed to have undefined behavior). 11735 QualType PromoteType; 11736 if (TInfo->getType()->isPromotableIntegerType()) { 11737 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 11738 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 11739 PromoteType = QualType(); 11740 } 11741 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 11742 PromoteType = Context.DoubleTy; 11743 if (!PromoteType.isNull()) 11744 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 11745 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 11746 << TInfo->getType() 11747 << PromoteType 11748 << TInfo->getTypeLoc().getSourceRange()); 11749 } 11750 11751 QualType T = TInfo->getType().getNonLValueExprType(Context); 11752 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 11753 } 11754 11755 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 11756 // The type of __null will be int or long, depending on the size of 11757 // pointers on the target. 11758 QualType Ty; 11759 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 11760 if (pw == Context.getTargetInfo().getIntWidth()) 11761 Ty = Context.IntTy; 11762 else if (pw == Context.getTargetInfo().getLongWidth()) 11763 Ty = Context.LongTy; 11764 else if (pw == Context.getTargetInfo().getLongLongWidth()) 11765 Ty = Context.LongLongTy; 11766 else { 11767 llvm_unreachable("I don't know size of pointer!"); 11768 } 11769 11770 return new (Context) GNUNullExpr(Ty, TokenLoc); 11771 } 11772 11773 bool 11774 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 11775 if (!getLangOpts().ObjC1) 11776 return false; 11777 11778 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 11779 if (!PT) 11780 return false; 11781 11782 if (!PT->isObjCIdType()) { 11783 // Check if the destination is the 'NSString' interface. 11784 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 11785 if (!ID || !ID->getIdentifier()->isStr("NSString")) 11786 return false; 11787 } 11788 11789 // Ignore any parens, implicit casts (should only be 11790 // array-to-pointer decays), and not-so-opaque values. The last is 11791 // important for making this trigger for property assignments. 11792 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 11793 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 11794 if (OV->getSourceExpr()) 11795 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 11796 11797 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 11798 if (!SL || !SL->isAscii()) 11799 return false; 11800 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 11801 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 11802 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 11803 return true; 11804 } 11805 11806 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 11807 SourceLocation Loc, 11808 QualType DstType, QualType SrcType, 11809 Expr *SrcExpr, AssignmentAction Action, 11810 bool *Complained) { 11811 if (Complained) 11812 *Complained = false; 11813 11814 // Decode the result (notice that AST's are still created for extensions). 11815 bool CheckInferredResultType = false; 11816 bool isInvalid = false; 11817 unsigned DiagKind = 0; 11818 FixItHint Hint; 11819 ConversionFixItGenerator ConvHints; 11820 bool MayHaveConvFixit = false; 11821 bool MayHaveFunctionDiff = false; 11822 const ObjCInterfaceDecl *IFace = nullptr; 11823 const ObjCProtocolDecl *PDecl = nullptr; 11824 11825 switch (ConvTy) { 11826 case Compatible: 11827 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 11828 return false; 11829 11830 case PointerToInt: 11831 DiagKind = diag::ext_typecheck_convert_pointer_int; 11832 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11833 MayHaveConvFixit = true; 11834 break; 11835 case IntToPointer: 11836 DiagKind = diag::ext_typecheck_convert_int_pointer; 11837 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11838 MayHaveConvFixit = true; 11839 break; 11840 case IncompatiblePointer: 11841 DiagKind = 11842 (Action == AA_Passing_CFAudited ? 11843 diag::err_arc_typecheck_convert_incompatible_pointer : 11844 diag::ext_typecheck_convert_incompatible_pointer); 11845 CheckInferredResultType = DstType->isObjCObjectPointerType() && 11846 SrcType->isObjCObjectPointerType(); 11847 if (Hint.isNull() && !CheckInferredResultType) { 11848 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11849 } 11850 else if (CheckInferredResultType) { 11851 SrcType = SrcType.getUnqualifiedType(); 11852 DstType = DstType.getUnqualifiedType(); 11853 } 11854 MayHaveConvFixit = true; 11855 break; 11856 case IncompatiblePointerSign: 11857 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 11858 break; 11859 case FunctionVoidPointer: 11860 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 11861 break; 11862 case IncompatiblePointerDiscardsQualifiers: { 11863 // Perform array-to-pointer decay if necessary. 11864 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 11865 11866 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 11867 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 11868 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 11869 DiagKind = diag::err_typecheck_incompatible_address_space; 11870 break; 11871 11872 11873 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 11874 DiagKind = diag::err_typecheck_incompatible_ownership; 11875 break; 11876 } 11877 11878 llvm_unreachable("unknown error case for discarding qualifiers!"); 11879 // fallthrough 11880 } 11881 case CompatiblePointerDiscardsQualifiers: 11882 // If the qualifiers lost were because we were applying the 11883 // (deprecated) C++ conversion from a string literal to a char* 11884 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 11885 // Ideally, this check would be performed in 11886 // checkPointerTypesForAssignment. However, that would require a 11887 // bit of refactoring (so that the second argument is an 11888 // expression, rather than a type), which should be done as part 11889 // of a larger effort to fix checkPointerTypesForAssignment for 11890 // C++ semantics. 11891 if (getLangOpts().CPlusPlus && 11892 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 11893 return false; 11894 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 11895 break; 11896 case IncompatibleNestedPointerQualifiers: 11897 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 11898 break; 11899 case IntToBlockPointer: 11900 DiagKind = diag::err_int_to_block_pointer; 11901 break; 11902 case IncompatibleBlockPointer: 11903 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 11904 break; 11905 case IncompatibleObjCQualifiedId: { 11906 if (SrcType->isObjCQualifiedIdType()) { 11907 const ObjCObjectPointerType *srcOPT = 11908 SrcType->getAs<ObjCObjectPointerType>(); 11909 for (auto *srcProto : srcOPT->quals()) { 11910 PDecl = srcProto; 11911 break; 11912 } 11913 if (const ObjCInterfaceType *IFaceT = 11914 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11915 IFace = IFaceT->getDecl(); 11916 } 11917 else if (DstType->isObjCQualifiedIdType()) { 11918 const ObjCObjectPointerType *dstOPT = 11919 DstType->getAs<ObjCObjectPointerType>(); 11920 for (auto *dstProto : dstOPT->quals()) { 11921 PDecl = dstProto; 11922 break; 11923 } 11924 if (const ObjCInterfaceType *IFaceT = 11925 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11926 IFace = IFaceT->getDecl(); 11927 } 11928 DiagKind = diag::warn_incompatible_qualified_id; 11929 break; 11930 } 11931 case IncompatibleVectors: 11932 DiagKind = diag::warn_incompatible_vectors; 11933 break; 11934 case IncompatibleObjCWeakRef: 11935 DiagKind = diag::err_arc_weak_unavailable_assign; 11936 break; 11937 case Incompatible: 11938 DiagKind = diag::err_typecheck_convert_incompatible; 11939 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11940 MayHaveConvFixit = true; 11941 isInvalid = true; 11942 MayHaveFunctionDiff = true; 11943 break; 11944 } 11945 11946 QualType FirstType, SecondType; 11947 switch (Action) { 11948 case AA_Assigning: 11949 case AA_Initializing: 11950 // The destination type comes first. 11951 FirstType = DstType; 11952 SecondType = SrcType; 11953 break; 11954 11955 case AA_Returning: 11956 case AA_Passing: 11957 case AA_Passing_CFAudited: 11958 case AA_Converting: 11959 case AA_Sending: 11960 case AA_Casting: 11961 // The source type comes first. 11962 FirstType = SrcType; 11963 SecondType = DstType; 11964 break; 11965 } 11966 11967 PartialDiagnostic FDiag = PDiag(DiagKind); 11968 if (Action == AA_Passing_CFAudited) 11969 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 11970 else 11971 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 11972 11973 // If we can fix the conversion, suggest the FixIts. 11974 assert(ConvHints.isNull() || Hint.isNull()); 11975 if (!ConvHints.isNull()) { 11976 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 11977 HE = ConvHints.Hints.end(); HI != HE; ++HI) 11978 FDiag << *HI; 11979 } else { 11980 FDiag << Hint; 11981 } 11982 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 11983 11984 if (MayHaveFunctionDiff) 11985 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 11986 11987 Diag(Loc, FDiag); 11988 if (DiagKind == diag::warn_incompatible_qualified_id && 11989 PDecl && IFace && !IFace->hasDefinition()) 11990 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 11991 << IFace->getName() << PDecl->getName(); 11992 11993 if (SecondType == Context.OverloadTy) 11994 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 11995 FirstType, /*TakingAddress=*/true); 11996 11997 if (CheckInferredResultType) 11998 EmitRelatedResultTypeNote(SrcExpr); 11999 12000 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12001 EmitRelatedResultTypeNoteForReturn(DstType); 12002 12003 if (Complained) 12004 *Complained = true; 12005 return isInvalid; 12006 } 12007 12008 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12009 llvm::APSInt *Result) { 12010 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12011 public: 12012 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12013 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12014 } 12015 } Diagnoser; 12016 12017 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12018 } 12019 12020 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12021 llvm::APSInt *Result, 12022 unsigned DiagID, 12023 bool AllowFold) { 12024 class IDDiagnoser : public VerifyICEDiagnoser { 12025 unsigned DiagID; 12026 12027 public: 12028 IDDiagnoser(unsigned DiagID) 12029 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12030 12031 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12032 S.Diag(Loc, DiagID) << SR; 12033 } 12034 } Diagnoser(DiagID); 12035 12036 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12037 } 12038 12039 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12040 SourceRange SR) { 12041 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12042 } 12043 12044 ExprResult 12045 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12046 VerifyICEDiagnoser &Diagnoser, 12047 bool AllowFold) { 12048 SourceLocation DiagLoc = E->getLocStart(); 12049 12050 if (getLangOpts().CPlusPlus11) { 12051 // C++11 [expr.const]p5: 12052 // If an expression of literal class type is used in a context where an 12053 // integral constant expression is required, then that class type shall 12054 // have a single non-explicit conversion function to an integral or 12055 // unscoped enumeration type 12056 ExprResult Converted; 12057 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12058 public: 12059 CXX11ConvertDiagnoser(bool Silent) 12060 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12061 Silent, true) {} 12062 12063 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12064 QualType T) override { 12065 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12066 } 12067 12068 SemaDiagnosticBuilder diagnoseIncomplete( 12069 Sema &S, SourceLocation Loc, QualType T) override { 12070 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12071 } 12072 12073 SemaDiagnosticBuilder diagnoseExplicitConv( 12074 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12075 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12076 } 12077 12078 SemaDiagnosticBuilder noteExplicitConv( 12079 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12080 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12081 << ConvTy->isEnumeralType() << ConvTy; 12082 } 12083 12084 SemaDiagnosticBuilder diagnoseAmbiguous( 12085 Sema &S, SourceLocation Loc, QualType T) override { 12086 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12087 } 12088 12089 SemaDiagnosticBuilder noteAmbiguous( 12090 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12091 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12092 << ConvTy->isEnumeralType() << ConvTy; 12093 } 12094 12095 SemaDiagnosticBuilder diagnoseConversion( 12096 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12097 llvm_unreachable("conversion functions are permitted"); 12098 } 12099 } ConvertDiagnoser(Diagnoser.Suppress); 12100 12101 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12102 ConvertDiagnoser); 12103 if (Converted.isInvalid()) 12104 return Converted; 12105 E = Converted.get(); 12106 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12107 return ExprError(); 12108 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12109 // An ICE must be of integral or unscoped enumeration type. 12110 if (!Diagnoser.Suppress) 12111 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12112 return ExprError(); 12113 } 12114 12115 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12116 // in the non-ICE case. 12117 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12118 if (Result) 12119 *Result = E->EvaluateKnownConstInt(Context); 12120 return E; 12121 } 12122 12123 Expr::EvalResult EvalResult; 12124 SmallVector<PartialDiagnosticAt, 8> Notes; 12125 EvalResult.Diag = &Notes; 12126 12127 // Try to evaluate the expression, and produce diagnostics explaining why it's 12128 // not a constant expression as a side-effect. 12129 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12130 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12131 12132 // In C++11, we can rely on diagnostics being produced for any expression 12133 // which is not a constant expression. If no diagnostics were produced, then 12134 // this is a constant expression. 12135 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12136 if (Result) 12137 *Result = EvalResult.Val.getInt(); 12138 return E; 12139 } 12140 12141 // If our only note is the usual "invalid subexpression" note, just point 12142 // the caret at its location rather than producing an essentially 12143 // redundant note. 12144 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12145 diag::note_invalid_subexpr_in_const_expr) { 12146 DiagLoc = Notes[0].first; 12147 Notes.clear(); 12148 } 12149 12150 if (!Folded || !AllowFold) { 12151 if (!Diagnoser.Suppress) { 12152 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12153 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12154 Diag(Notes[I].first, Notes[I].second); 12155 } 12156 12157 return ExprError(); 12158 } 12159 12160 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12161 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12162 Diag(Notes[I].first, Notes[I].second); 12163 12164 if (Result) 12165 *Result = EvalResult.Val.getInt(); 12166 return E; 12167 } 12168 12169 namespace { 12170 // Handle the case where we conclude a expression which we speculatively 12171 // considered to be unevaluated is actually evaluated. 12172 class TransformToPE : public TreeTransform<TransformToPE> { 12173 typedef TreeTransform<TransformToPE> BaseTransform; 12174 12175 public: 12176 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12177 12178 // Make sure we redo semantic analysis 12179 bool AlwaysRebuild() { return true; } 12180 12181 // Make sure we handle LabelStmts correctly. 12182 // FIXME: This does the right thing, but maybe we need a more general 12183 // fix to TreeTransform? 12184 StmtResult TransformLabelStmt(LabelStmt *S) { 12185 S->getDecl()->setStmt(nullptr); 12186 return BaseTransform::TransformLabelStmt(S); 12187 } 12188 12189 // We need to special-case DeclRefExprs referring to FieldDecls which 12190 // are not part of a member pointer formation; normal TreeTransforming 12191 // doesn't catch this case because of the way we represent them in the AST. 12192 // FIXME: This is a bit ugly; is it really the best way to handle this 12193 // case? 12194 // 12195 // Error on DeclRefExprs referring to FieldDecls. 12196 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12197 if (isa<FieldDecl>(E->getDecl()) && 12198 !SemaRef.isUnevaluatedContext()) 12199 return SemaRef.Diag(E->getLocation(), 12200 diag::err_invalid_non_static_member_use) 12201 << E->getDecl() << E->getSourceRange(); 12202 12203 return BaseTransform::TransformDeclRefExpr(E); 12204 } 12205 12206 // Exception: filter out member pointer formation 12207 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12208 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12209 return E; 12210 12211 return BaseTransform::TransformUnaryOperator(E); 12212 } 12213 12214 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12215 // Lambdas never need to be transformed. 12216 return E; 12217 } 12218 }; 12219 } 12220 12221 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12222 assert(isUnevaluatedContext() && 12223 "Should only transform unevaluated expressions"); 12224 ExprEvalContexts.back().Context = 12225 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12226 if (isUnevaluatedContext()) 12227 return E; 12228 return TransformToPE(*this).TransformExpr(E); 12229 } 12230 12231 void 12232 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12233 Decl *LambdaContextDecl, 12234 bool IsDecltype) { 12235 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12236 ExprNeedsCleanups, LambdaContextDecl, 12237 IsDecltype); 12238 ExprNeedsCleanups = false; 12239 if (!MaybeODRUseExprs.empty()) 12240 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12241 } 12242 12243 void 12244 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12245 ReuseLambdaContextDecl_t, 12246 bool IsDecltype) { 12247 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12248 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12249 } 12250 12251 void Sema::PopExpressionEvaluationContext() { 12252 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12253 unsigned NumTypos = Rec.NumTypos; 12254 12255 if (!Rec.Lambdas.empty()) { 12256 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12257 unsigned D; 12258 if (Rec.isUnevaluated()) { 12259 // C++11 [expr.prim.lambda]p2: 12260 // A lambda-expression shall not appear in an unevaluated operand 12261 // (Clause 5). 12262 D = diag::err_lambda_unevaluated_operand; 12263 } else { 12264 // C++1y [expr.const]p2: 12265 // A conditional-expression e is a core constant expression unless the 12266 // evaluation of e, following the rules of the abstract machine, would 12267 // evaluate [...] a lambda-expression. 12268 D = diag::err_lambda_in_constant_expression; 12269 } 12270 for (const auto *L : Rec.Lambdas) 12271 Diag(L->getLocStart(), D); 12272 } else { 12273 // Mark the capture expressions odr-used. This was deferred 12274 // during lambda expression creation. 12275 for (auto *Lambda : Rec.Lambdas) { 12276 for (auto *C : Lambda->capture_inits()) 12277 MarkDeclarationsReferencedInExpr(C); 12278 } 12279 } 12280 } 12281 12282 // When are coming out of an unevaluated context, clear out any 12283 // temporaries that we may have created as part of the evaluation of 12284 // the expression in that context: they aren't relevant because they 12285 // will never be constructed. 12286 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12287 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12288 ExprCleanupObjects.end()); 12289 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12290 CleanupVarDeclMarking(); 12291 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12292 // Otherwise, merge the contexts together. 12293 } else { 12294 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12295 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12296 Rec.SavedMaybeODRUseExprs.end()); 12297 } 12298 12299 // Pop the current expression evaluation context off the stack. 12300 ExprEvalContexts.pop_back(); 12301 12302 if (!ExprEvalContexts.empty()) 12303 ExprEvalContexts.back().NumTypos += NumTypos; 12304 else 12305 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12306 "last ExpressionEvaluationContextRecord"); 12307 } 12308 12309 void Sema::DiscardCleanupsInEvaluationContext() { 12310 ExprCleanupObjects.erase( 12311 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12312 ExprCleanupObjects.end()); 12313 ExprNeedsCleanups = false; 12314 MaybeODRUseExprs.clear(); 12315 } 12316 12317 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12318 if (!E->getType()->isVariablyModifiedType()) 12319 return E; 12320 return TransformToPotentiallyEvaluated(E); 12321 } 12322 12323 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12324 // Do not mark anything as "used" within a dependent context; wait for 12325 // an instantiation. 12326 if (SemaRef.CurContext->isDependentContext()) 12327 return false; 12328 12329 switch (SemaRef.ExprEvalContexts.back().Context) { 12330 case Sema::Unevaluated: 12331 case Sema::UnevaluatedAbstract: 12332 // We are in an expression that is not potentially evaluated; do nothing. 12333 // (Depending on how you read the standard, we actually do need to do 12334 // something here for null pointer constants, but the standard's 12335 // definition of a null pointer constant is completely crazy.) 12336 return false; 12337 12338 case Sema::ConstantEvaluated: 12339 case Sema::PotentiallyEvaluated: 12340 // We are in a potentially evaluated expression (or a constant-expression 12341 // in C++03); we need to do implicit template instantiation, implicitly 12342 // define class members, and mark most declarations as used. 12343 return true; 12344 12345 case Sema::PotentiallyEvaluatedIfUsed: 12346 // Referenced declarations will only be used if the construct in the 12347 // containing expression is used. 12348 return false; 12349 } 12350 llvm_unreachable("Invalid context"); 12351 } 12352 12353 /// \brief Mark a function referenced, and check whether it is odr-used 12354 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12355 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12356 bool OdrUse) { 12357 assert(Func && "No function?"); 12358 12359 Func->setReferenced(); 12360 12361 // C++11 [basic.def.odr]p3: 12362 // A function whose name appears as a potentially-evaluated expression is 12363 // odr-used if it is the unique lookup result or the selected member of a 12364 // set of overloaded functions [...]. 12365 // 12366 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12367 // can just check that here. Skip the rest of this function if we've already 12368 // marked the function as used. 12369 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12370 !IsPotentiallyEvaluatedContext(*this)) { 12371 // C++11 [temp.inst]p3: 12372 // Unless a function template specialization has been explicitly 12373 // instantiated or explicitly specialized, the function template 12374 // specialization is implicitly instantiated when the specialization is 12375 // referenced in a context that requires a function definition to exist. 12376 // 12377 // We consider constexpr function templates to be referenced in a context 12378 // that requires a definition to exist whenever they are referenced. 12379 // 12380 // FIXME: This instantiates constexpr functions too frequently. If this is 12381 // really an unevaluated context (and we're not just in the definition of a 12382 // function template or overload resolution or other cases which we 12383 // incorrectly consider to be unevaluated contexts), and we're not in a 12384 // subexpression which we actually need to evaluate (for instance, a 12385 // template argument, array bound or an expression in a braced-init-list), 12386 // we are not permitted to instantiate this constexpr function definition. 12387 // 12388 // FIXME: This also implicitly defines special members too frequently. They 12389 // are only supposed to be implicitly defined if they are odr-used, but they 12390 // are not odr-used from constant expressions in unevaluated contexts. 12391 // However, they cannot be referenced if they are deleted, and they are 12392 // deleted whenever the implicit definition of the special member would 12393 // fail. 12394 if (!Func->isConstexpr() || Func->getBody()) 12395 return; 12396 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12397 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12398 return; 12399 } 12400 12401 // Note that this declaration has been used. 12402 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12403 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12404 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12405 if (Constructor->isDefaultConstructor()) { 12406 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12407 return; 12408 DefineImplicitDefaultConstructor(Loc, Constructor); 12409 } else if (Constructor->isCopyConstructor()) { 12410 DefineImplicitCopyConstructor(Loc, Constructor); 12411 } else if (Constructor->isMoveConstructor()) { 12412 DefineImplicitMoveConstructor(Loc, Constructor); 12413 } 12414 } else if (Constructor->getInheritedConstructor()) { 12415 DefineInheritingConstructor(Loc, Constructor); 12416 } 12417 } else if (CXXDestructorDecl *Destructor = 12418 dyn_cast<CXXDestructorDecl>(Func)) { 12419 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12420 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12421 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12422 return; 12423 DefineImplicitDestructor(Loc, Destructor); 12424 } 12425 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12426 MarkVTableUsed(Loc, Destructor->getParent()); 12427 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12428 if (MethodDecl->isOverloadedOperator() && 12429 MethodDecl->getOverloadedOperator() == OO_Equal) { 12430 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12431 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12432 if (MethodDecl->isCopyAssignmentOperator()) 12433 DefineImplicitCopyAssignment(Loc, MethodDecl); 12434 else 12435 DefineImplicitMoveAssignment(Loc, MethodDecl); 12436 } 12437 } else if (isa<CXXConversionDecl>(MethodDecl) && 12438 MethodDecl->getParent()->isLambda()) { 12439 CXXConversionDecl *Conversion = 12440 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12441 if (Conversion->isLambdaToBlockPointerConversion()) 12442 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12443 else 12444 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12445 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12446 MarkVTableUsed(Loc, MethodDecl->getParent()); 12447 } 12448 12449 // Recursive functions should be marked when used from another function. 12450 // FIXME: Is this really right? 12451 if (CurContext == Func) return; 12452 12453 // Resolve the exception specification for any function which is 12454 // used: CodeGen will need it. 12455 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12456 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12457 ResolveExceptionSpec(Loc, FPT); 12458 12459 if (!OdrUse) return; 12460 12461 // Implicit instantiation of function templates and member functions of 12462 // class templates. 12463 if (Func->isImplicitlyInstantiable()) { 12464 bool AlreadyInstantiated = false; 12465 SourceLocation PointOfInstantiation = Loc; 12466 if (FunctionTemplateSpecializationInfo *SpecInfo 12467 = Func->getTemplateSpecializationInfo()) { 12468 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12469 SpecInfo->setPointOfInstantiation(Loc); 12470 else if (SpecInfo->getTemplateSpecializationKind() 12471 == TSK_ImplicitInstantiation) { 12472 AlreadyInstantiated = true; 12473 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12474 } 12475 } else if (MemberSpecializationInfo *MSInfo 12476 = Func->getMemberSpecializationInfo()) { 12477 if (MSInfo->getPointOfInstantiation().isInvalid()) 12478 MSInfo->setPointOfInstantiation(Loc); 12479 else if (MSInfo->getTemplateSpecializationKind() 12480 == TSK_ImplicitInstantiation) { 12481 AlreadyInstantiated = true; 12482 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12483 } 12484 } 12485 12486 if (!AlreadyInstantiated || Func->isConstexpr()) { 12487 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12488 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12489 ActiveTemplateInstantiations.size()) 12490 PendingLocalImplicitInstantiations.push_back( 12491 std::make_pair(Func, PointOfInstantiation)); 12492 else if (Func->isConstexpr()) 12493 // Do not defer instantiations of constexpr functions, to avoid the 12494 // expression evaluator needing to call back into Sema if it sees a 12495 // call to such a function. 12496 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12497 else { 12498 PendingInstantiations.push_back(std::make_pair(Func, 12499 PointOfInstantiation)); 12500 // Notify the consumer that a function was implicitly instantiated. 12501 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12502 } 12503 } 12504 } else { 12505 // Walk redefinitions, as some of them may be instantiable. 12506 for (auto i : Func->redecls()) { 12507 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12508 MarkFunctionReferenced(Loc, i); 12509 } 12510 } 12511 12512 // Keep track of used but undefined functions. 12513 if (!Func->isDefined()) { 12514 if (mightHaveNonExternalLinkage(Func)) 12515 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12516 else if (Func->getMostRecentDecl()->isInlined() && 12517 !LangOpts.GNUInline && 12518 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12519 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12520 } 12521 12522 // Normally the most current decl is marked used while processing the use and 12523 // any subsequent decls are marked used by decl merging. This fails with 12524 // template instantiation since marking can happen at the end of the file 12525 // and, because of the two phase lookup, this function is called with at 12526 // decl in the middle of a decl chain. We loop to maintain the invariant 12527 // that once a decl is used, all decls after it are also used. 12528 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12529 F->markUsed(Context); 12530 if (F == Func) 12531 break; 12532 } 12533 } 12534 12535 static void 12536 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12537 VarDecl *var, DeclContext *DC) { 12538 DeclContext *VarDC = var->getDeclContext(); 12539 12540 // If the parameter still belongs to the translation unit, then 12541 // we're actually just using one parameter in the declaration of 12542 // the next. 12543 if (isa<ParmVarDecl>(var) && 12544 isa<TranslationUnitDecl>(VarDC)) 12545 return; 12546 12547 // For C code, don't diagnose about capture if we're not actually in code 12548 // right now; it's impossible to write a non-constant expression outside of 12549 // function context, so we'll get other (more useful) diagnostics later. 12550 // 12551 // For C++, things get a bit more nasty... it would be nice to suppress this 12552 // diagnostic for certain cases like using a local variable in an array bound 12553 // for a member of a local class, but the correct predicate is not obvious. 12554 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12555 return; 12556 12557 if (isa<CXXMethodDecl>(VarDC) && 12558 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12559 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12560 << var->getIdentifier(); 12561 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12562 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12563 << var->getIdentifier() << fn->getDeclName(); 12564 } else if (isa<BlockDecl>(VarDC)) { 12565 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12566 << var->getIdentifier(); 12567 } else { 12568 // FIXME: Is there any other context where a local variable can be 12569 // declared? 12570 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12571 << var->getIdentifier(); 12572 } 12573 12574 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12575 << var->getIdentifier(); 12576 12577 // FIXME: Add additional diagnostic info about class etc. which prevents 12578 // capture. 12579 } 12580 12581 12582 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12583 bool &SubCapturesAreNested, 12584 QualType &CaptureType, 12585 QualType &DeclRefType) { 12586 // Check whether we've already captured it. 12587 if (CSI->CaptureMap.count(Var)) { 12588 // If we found a capture, any subcaptures are nested. 12589 SubCapturesAreNested = true; 12590 12591 // Retrieve the capture type for this variable. 12592 CaptureType = CSI->getCapture(Var).getCaptureType(); 12593 12594 // Compute the type of an expression that refers to this variable. 12595 DeclRefType = CaptureType.getNonReferenceType(); 12596 12597 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 12598 if (Cap.isCopyCapture() && 12599 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 12600 DeclRefType.addConst(); 12601 return true; 12602 } 12603 return false; 12604 } 12605 12606 // Only block literals, captured statements, and lambda expressions can 12607 // capture; other scopes don't work. 12608 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 12609 SourceLocation Loc, 12610 const bool Diagnose, Sema &S) { 12611 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 12612 return getLambdaAwareParentOfDeclContext(DC); 12613 else if (Var->hasLocalStorage()) { 12614 if (Diagnose) 12615 diagnoseUncapturableValueReference(S, Loc, Var, DC); 12616 } 12617 return nullptr; 12618 } 12619 12620 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12621 // certain types of variables (unnamed, variably modified types etc.) 12622 // so check for eligibility. 12623 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 12624 SourceLocation Loc, 12625 const bool Diagnose, Sema &S) { 12626 12627 bool IsBlock = isa<BlockScopeInfo>(CSI); 12628 bool IsLambda = isa<LambdaScopeInfo>(CSI); 12629 12630 // Lambdas are not allowed to capture unnamed variables 12631 // (e.g. anonymous unions). 12632 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 12633 // assuming that's the intent. 12634 if (IsLambda && !Var->getDeclName()) { 12635 if (Diagnose) { 12636 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 12637 S.Diag(Var->getLocation(), diag::note_declared_at); 12638 } 12639 return false; 12640 } 12641 12642 // Prohibit variably-modified types in blocks; they're difficult to deal with. 12643 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 12644 if (Diagnose) { 12645 S.Diag(Loc, diag::err_ref_vm_type); 12646 S.Diag(Var->getLocation(), diag::note_previous_decl) 12647 << Var->getDeclName(); 12648 } 12649 return false; 12650 } 12651 // Prohibit structs with flexible array members too. 12652 // We cannot capture what is in the tail end of the struct. 12653 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 12654 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 12655 if (Diagnose) { 12656 if (IsBlock) 12657 S.Diag(Loc, diag::err_ref_flexarray_type); 12658 else 12659 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 12660 << Var->getDeclName(); 12661 S.Diag(Var->getLocation(), diag::note_previous_decl) 12662 << Var->getDeclName(); 12663 } 12664 return false; 12665 } 12666 } 12667 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12668 // Lambdas and captured statements are not allowed to capture __block 12669 // variables; they don't support the expected semantics. 12670 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 12671 if (Diagnose) { 12672 S.Diag(Loc, diag::err_capture_block_variable) 12673 << Var->getDeclName() << !IsLambda; 12674 S.Diag(Var->getLocation(), diag::note_previous_decl) 12675 << Var->getDeclName(); 12676 } 12677 return false; 12678 } 12679 12680 return true; 12681 } 12682 12683 // Returns true if the capture by block was successful. 12684 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 12685 SourceLocation Loc, 12686 const bool BuildAndDiagnose, 12687 QualType &CaptureType, 12688 QualType &DeclRefType, 12689 const bool Nested, 12690 Sema &S) { 12691 Expr *CopyExpr = nullptr; 12692 bool ByRef = false; 12693 12694 // Blocks are not allowed to capture arrays. 12695 if (CaptureType->isArrayType()) { 12696 if (BuildAndDiagnose) { 12697 S.Diag(Loc, diag::err_ref_array_type); 12698 S.Diag(Var->getLocation(), diag::note_previous_decl) 12699 << Var->getDeclName(); 12700 } 12701 return false; 12702 } 12703 12704 // Forbid the block-capture of autoreleasing variables. 12705 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12706 if (BuildAndDiagnose) { 12707 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 12708 << /*block*/ 0; 12709 S.Diag(Var->getLocation(), diag::note_previous_decl) 12710 << Var->getDeclName(); 12711 } 12712 return false; 12713 } 12714 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12715 if (HasBlocksAttr || CaptureType->isReferenceType()) { 12716 // Block capture by reference does not change the capture or 12717 // declaration reference types. 12718 ByRef = true; 12719 } else { 12720 // Block capture by copy introduces 'const'. 12721 CaptureType = CaptureType.getNonReferenceType().withConst(); 12722 DeclRefType = CaptureType; 12723 12724 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 12725 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 12726 // The capture logic needs the destructor, so make sure we mark it. 12727 // Usually this is unnecessary because most local variables have 12728 // their destructors marked at declaration time, but parameters are 12729 // an exception because it's technically only the call site that 12730 // actually requires the destructor. 12731 if (isa<ParmVarDecl>(Var)) 12732 S.FinalizeVarWithDestructor(Var, Record); 12733 12734 // Enter a new evaluation context to insulate the copy 12735 // full-expression. 12736 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 12737 12738 // According to the blocks spec, the capture of a variable from 12739 // the stack requires a const copy constructor. This is not true 12740 // of the copy/move done to move a __block variable to the heap. 12741 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 12742 DeclRefType.withConst(), 12743 VK_LValue, Loc); 12744 12745 ExprResult Result 12746 = S.PerformCopyInitialization( 12747 InitializedEntity::InitializeBlock(Var->getLocation(), 12748 CaptureType, false), 12749 Loc, DeclRef); 12750 12751 // Build a full-expression copy expression if initialization 12752 // succeeded and used a non-trivial constructor. Recover from 12753 // errors by pretending that the copy isn't necessary. 12754 if (!Result.isInvalid() && 12755 !cast<CXXConstructExpr>(Result.get())->getConstructor() 12756 ->isTrivial()) { 12757 Result = S.MaybeCreateExprWithCleanups(Result); 12758 CopyExpr = Result.get(); 12759 } 12760 } 12761 } 12762 } 12763 12764 // Actually capture the variable. 12765 if (BuildAndDiagnose) 12766 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 12767 SourceLocation(), CaptureType, CopyExpr); 12768 12769 return true; 12770 12771 } 12772 12773 12774 /// \brief Capture the given variable in the captured region. 12775 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 12776 VarDecl *Var, 12777 SourceLocation Loc, 12778 const bool BuildAndDiagnose, 12779 QualType &CaptureType, 12780 QualType &DeclRefType, 12781 const bool RefersToCapturedVariable, 12782 Sema &S) { 12783 12784 // By default, capture variables by reference. 12785 bool ByRef = true; 12786 // Using an LValue reference type is consistent with Lambdas (see below). 12787 if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var)) 12788 DeclRefType = DeclRefType.getUnqualifiedType(); 12789 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12790 Expr *CopyExpr = nullptr; 12791 if (BuildAndDiagnose) { 12792 // The current implementation assumes that all variables are captured 12793 // by references. Since there is no capture by copy, no expression 12794 // evaluation will be needed. 12795 RecordDecl *RD = RSI->TheRecordDecl; 12796 12797 FieldDecl *Field 12798 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 12799 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 12800 nullptr, false, ICIS_NoInit); 12801 Field->setImplicit(true); 12802 Field->setAccess(AS_private); 12803 RD->addDecl(Field); 12804 12805 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 12806 DeclRefType, VK_LValue, Loc); 12807 Var->setReferenced(true); 12808 Var->markUsed(S.Context); 12809 } 12810 12811 // Actually capture the variable. 12812 if (BuildAndDiagnose) 12813 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 12814 SourceLocation(), CaptureType, CopyExpr); 12815 12816 12817 return true; 12818 } 12819 12820 /// \brief Create a field within the lambda class for the variable 12821 /// being captured. 12822 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 12823 QualType FieldType, QualType DeclRefType, 12824 SourceLocation Loc, 12825 bool RefersToCapturedVariable) { 12826 CXXRecordDecl *Lambda = LSI->Lambda; 12827 12828 // Build the non-static data member. 12829 FieldDecl *Field 12830 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 12831 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 12832 nullptr, false, ICIS_NoInit); 12833 Field->setImplicit(true); 12834 Field->setAccess(AS_private); 12835 Lambda->addDecl(Field); 12836 } 12837 12838 /// \brief Capture the given variable in the lambda. 12839 static bool captureInLambda(LambdaScopeInfo *LSI, 12840 VarDecl *Var, 12841 SourceLocation Loc, 12842 const bool BuildAndDiagnose, 12843 QualType &CaptureType, 12844 QualType &DeclRefType, 12845 const bool RefersToCapturedVariable, 12846 const Sema::TryCaptureKind Kind, 12847 SourceLocation EllipsisLoc, 12848 const bool IsTopScope, 12849 Sema &S) { 12850 12851 // Determine whether we are capturing by reference or by value. 12852 bool ByRef = false; 12853 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 12854 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 12855 } else { 12856 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 12857 } 12858 12859 // Compute the type of the field that will capture this variable. 12860 if (ByRef) { 12861 // C++11 [expr.prim.lambda]p15: 12862 // An entity is captured by reference if it is implicitly or 12863 // explicitly captured but not captured by copy. It is 12864 // unspecified whether additional unnamed non-static data 12865 // members are declared in the closure type for entities 12866 // captured by reference. 12867 // 12868 // FIXME: It is not clear whether we want to build an lvalue reference 12869 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 12870 // to do the former, while EDG does the latter. Core issue 1249 will 12871 // clarify, but for now we follow GCC because it's a more permissive and 12872 // easily defensible position. 12873 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12874 } else { 12875 // C++11 [expr.prim.lambda]p14: 12876 // For each entity captured by copy, an unnamed non-static 12877 // data member is declared in the closure type. The 12878 // declaration order of these members is unspecified. The type 12879 // of such a data member is the type of the corresponding 12880 // captured entity if the entity is not a reference to an 12881 // object, or the referenced type otherwise. [Note: If the 12882 // captured entity is a reference to a function, the 12883 // corresponding data member is also a reference to a 12884 // function. - end note ] 12885 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 12886 if (!RefType->getPointeeType()->isFunctionType()) 12887 CaptureType = RefType->getPointeeType(); 12888 } 12889 12890 // Forbid the lambda copy-capture of autoreleasing variables. 12891 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12892 if (BuildAndDiagnose) { 12893 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 12894 S.Diag(Var->getLocation(), diag::note_previous_decl) 12895 << Var->getDeclName(); 12896 } 12897 return false; 12898 } 12899 12900 // Make sure that by-copy captures are of a complete and non-abstract type. 12901 if (BuildAndDiagnose) { 12902 if (!CaptureType->isDependentType() && 12903 S.RequireCompleteType(Loc, CaptureType, 12904 diag::err_capture_of_incomplete_type, 12905 Var->getDeclName())) 12906 return false; 12907 12908 if (S.RequireNonAbstractType(Loc, CaptureType, 12909 diag::err_capture_of_abstract_type)) 12910 return false; 12911 } 12912 } 12913 12914 // Capture this variable in the lambda. 12915 if (BuildAndDiagnose) 12916 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 12917 RefersToCapturedVariable); 12918 12919 // Compute the type of a reference to this captured variable. 12920 if (ByRef) 12921 DeclRefType = CaptureType.getNonReferenceType(); 12922 else { 12923 // C++ [expr.prim.lambda]p5: 12924 // The closure type for a lambda-expression has a public inline 12925 // function call operator [...]. This function call operator is 12926 // declared const (9.3.1) if and only if the lambda-expression’s 12927 // parameter-declaration-clause is not followed by mutable. 12928 DeclRefType = CaptureType.getNonReferenceType(); 12929 if (!LSI->Mutable && !CaptureType->isReferenceType()) 12930 DeclRefType.addConst(); 12931 } 12932 12933 // Add the capture. 12934 if (BuildAndDiagnose) 12935 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 12936 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 12937 12938 return true; 12939 } 12940 12941 bool Sema::tryCaptureVariable( 12942 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 12943 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 12944 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 12945 // An init-capture is notionally from the context surrounding its 12946 // declaration, but its parent DC is the lambda class. 12947 DeclContext *VarDC = Var->getDeclContext(); 12948 if (Var->isInitCapture()) 12949 VarDC = VarDC->getParent(); 12950 12951 DeclContext *DC = CurContext; 12952 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12953 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 12954 // We need to sync up the Declaration Context with the 12955 // FunctionScopeIndexToStopAt 12956 if (FunctionScopeIndexToStopAt) { 12957 unsigned FSIndex = FunctionScopes.size() - 1; 12958 while (FSIndex != MaxFunctionScopesIndex) { 12959 DC = getLambdaAwareParentOfDeclContext(DC); 12960 --FSIndex; 12961 } 12962 } 12963 12964 12965 // If the variable is declared in the current context, there is no need to 12966 // capture it. 12967 if (VarDC == DC) return true; 12968 12969 // Capture global variables if it is required to use private copy of this 12970 // variable. 12971 bool IsGlobal = !Var->hasLocalStorage(); 12972 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var))) 12973 return true; 12974 12975 // Walk up the stack to determine whether we can capture the variable, 12976 // performing the "simple" checks that don't depend on type. We stop when 12977 // we've either hit the declared scope of the variable or find an existing 12978 // capture of that variable. We start from the innermost capturing-entity 12979 // (the DC) and ensure that all intervening capturing-entities 12980 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 12981 // declcontext can either capture the variable or have already captured 12982 // the variable. 12983 CaptureType = Var->getType(); 12984 DeclRefType = CaptureType.getNonReferenceType(); 12985 bool Nested = false; 12986 bool Explicit = (Kind != TryCapture_Implicit); 12987 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 12988 unsigned OpenMPLevel = 0; 12989 do { 12990 // Only block literals, captured statements, and lambda expressions can 12991 // capture; other scopes don't work. 12992 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 12993 ExprLoc, 12994 BuildAndDiagnose, 12995 *this); 12996 // We need to check for the parent *first* because, if we *have* 12997 // private-captured a global variable, we need to recursively capture it in 12998 // intermediate blocks, lambdas, etc. 12999 if (!ParentDC) { 13000 if (IsGlobal) { 13001 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13002 break; 13003 } 13004 return true; 13005 } 13006 13007 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13008 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13009 13010 13011 // Check whether we've already captured it. 13012 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13013 DeclRefType)) 13014 break; 13015 // If we are instantiating a generic lambda call operator body, 13016 // we do not want to capture new variables. What was captured 13017 // during either a lambdas transformation or initial parsing 13018 // should be used. 13019 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13020 if (BuildAndDiagnose) { 13021 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13022 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13023 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13024 Diag(Var->getLocation(), diag::note_previous_decl) 13025 << Var->getDeclName(); 13026 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13027 } else 13028 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13029 } 13030 return true; 13031 } 13032 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13033 // certain types of variables (unnamed, variably modified types etc.) 13034 // so check for eligibility. 13035 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13036 return true; 13037 13038 // Try to capture variable-length arrays types. 13039 if (Var->getType()->isVariablyModifiedType()) { 13040 // We're going to walk down into the type and look for VLA 13041 // expressions. 13042 QualType QTy = Var->getType(); 13043 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13044 QTy = PVD->getOriginalType(); 13045 do { 13046 const Type *Ty = QTy.getTypePtr(); 13047 switch (Ty->getTypeClass()) { 13048 #define TYPE(Class, Base) 13049 #define ABSTRACT_TYPE(Class, Base) 13050 #define NON_CANONICAL_TYPE(Class, Base) 13051 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 13052 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 13053 #include "clang/AST/TypeNodes.def" 13054 QTy = QualType(); 13055 break; 13056 // These types are never variably-modified. 13057 case Type::Builtin: 13058 case Type::Complex: 13059 case Type::Vector: 13060 case Type::ExtVector: 13061 case Type::Record: 13062 case Type::Enum: 13063 case Type::Elaborated: 13064 case Type::TemplateSpecialization: 13065 case Type::ObjCObject: 13066 case Type::ObjCInterface: 13067 case Type::ObjCObjectPointer: 13068 llvm_unreachable("type class is never variably-modified!"); 13069 case Type::Adjusted: 13070 QTy = cast<AdjustedType>(Ty)->getOriginalType(); 13071 break; 13072 case Type::Decayed: 13073 QTy = cast<DecayedType>(Ty)->getPointeeType(); 13074 break; 13075 case Type::Pointer: 13076 QTy = cast<PointerType>(Ty)->getPointeeType(); 13077 break; 13078 case Type::BlockPointer: 13079 QTy = cast<BlockPointerType>(Ty)->getPointeeType(); 13080 break; 13081 case Type::LValueReference: 13082 case Type::RValueReference: 13083 QTy = cast<ReferenceType>(Ty)->getPointeeType(); 13084 break; 13085 case Type::MemberPointer: 13086 QTy = cast<MemberPointerType>(Ty)->getPointeeType(); 13087 break; 13088 case Type::ConstantArray: 13089 case Type::IncompleteArray: 13090 // Losing element qualification here is fine. 13091 QTy = cast<ArrayType>(Ty)->getElementType(); 13092 break; 13093 case Type::VariableArray: { 13094 // Losing element qualification here is fine. 13095 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 13096 13097 // Unknown size indication requires no size computation. 13098 // Otherwise, evaluate and record it. 13099 if (auto Size = VAT->getSizeExpr()) { 13100 if (!CSI->isVLATypeCaptured(VAT)) { 13101 RecordDecl *CapRecord = nullptr; 13102 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 13103 CapRecord = LSI->Lambda; 13104 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13105 CapRecord = CRSI->TheRecordDecl; 13106 } 13107 if (CapRecord) { 13108 auto ExprLoc = Size->getExprLoc(); 13109 auto SizeType = Context.getSizeType(); 13110 // Build the non-static data member. 13111 auto Field = FieldDecl::Create( 13112 Context, CapRecord, ExprLoc, ExprLoc, 13113 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 13114 /*BW*/ nullptr, /*Mutable*/ false, 13115 /*InitStyle*/ ICIS_NoInit); 13116 Field->setImplicit(true); 13117 Field->setAccess(AS_private); 13118 Field->setCapturedVLAType(VAT); 13119 CapRecord->addDecl(Field); 13120 13121 CSI->addVLATypeCapture(ExprLoc, SizeType); 13122 } 13123 } 13124 } 13125 QTy = VAT->getElementType(); 13126 break; 13127 } 13128 case Type::FunctionProto: 13129 case Type::FunctionNoProto: 13130 QTy = cast<FunctionType>(Ty)->getReturnType(); 13131 break; 13132 case Type::Paren: 13133 case Type::TypeOf: 13134 case Type::UnaryTransform: 13135 case Type::Attributed: 13136 case Type::SubstTemplateTypeParm: 13137 case Type::PackExpansion: 13138 // Keep walking after single level desugaring. 13139 QTy = QTy.getSingleStepDesugaredType(getASTContext()); 13140 break; 13141 case Type::Typedef: 13142 QTy = cast<TypedefType>(Ty)->desugar(); 13143 break; 13144 case Type::Decltype: 13145 QTy = cast<DecltypeType>(Ty)->desugar(); 13146 break; 13147 case Type::Auto: 13148 QTy = cast<AutoType>(Ty)->getDeducedType(); 13149 break; 13150 case Type::TypeOfExpr: 13151 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 13152 break; 13153 case Type::Atomic: 13154 QTy = cast<AtomicType>(Ty)->getValueType(); 13155 break; 13156 } 13157 } while (!QTy.isNull() && QTy->isVariablyModifiedType()); 13158 } 13159 13160 if (getLangOpts().OpenMP) { 13161 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13162 // OpenMP private variables should not be captured in outer scope, so 13163 // just break here. Similarly, global variables that are captured in a 13164 // target region should not be captured outside the scope of the region. 13165 if (RSI->CapRegionKind == CR_OpenMP) { 13166 auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel); 13167 // When we detect target captures we are looking from inside the 13168 // target region, therefore we need to propagate the capture from the 13169 // enclosing region. Therefore, the capture is not initially nested. 13170 if (isTargetCap) 13171 FunctionScopesIndex--; 13172 13173 if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) { 13174 Nested = !isTargetCap; 13175 DeclRefType = DeclRefType.getUnqualifiedType(); 13176 CaptureType = Context.getLValueReferenceType(DeclRefType); 13177 break; 13178 } 13179 ++OpenMPLevel; 13180 } 13181 } 13182 } 13183 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13184 // No capture-default, and this is not an explicit capture 13185 // so cannot capture this variable. 13186 if (BuildAndDiagnose) { 13187 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13188 Diag(Var->getLocation(), diag::note_previous_decl) 13189 << Var->getDeclName(); 13190 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13191 diag::note_lambda_decl); 13192 // FIXME: If we error out because an outer lambda can not implicitly 13193 // capture a variable that an inner lambda explicitly captures, we 13194 // should have the inner lambda do the explicit capture - because 13195 // it makes for cleaner diagnostics later. This would purely be done 13196 // so that the diagnostic does not misleadingly claim that a variable 13197 // can not be captured by a lambda implicitly even though it is captured 13198 // explicitly. Suggestion: 13199 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13200 // at the function head 13201 // - cache the StartingDeclContext - this must be a lambda 13202 // - captureInLambda in the innermost lambda the variable. 13203 } 13204 return true; 13205 } 13206 13207 FunctionScopesIndex--; 13208 DC = ParentDC; 13209 Explicit = false; 13210 } while (!VarDC->Equals(DC)); 13211 13212 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13213 // computing the type of the capture at each step, checking type-specific 13214 // requirements, and adding captures if requested. 13215 // If the variable had already been captured previously, we start capturing 13216 // at the lambda nested within that one. 13217 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13218 ++I) { 13219 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13220 13221 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13222 if (!captureInBlock(BSI, Var, ExprLoc, 13223 BuildAndDiagnose, CaptureType, 13224 DeclRefType, Nested, *this)) 13225 return true; 13226 Nested = true; 13227 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13228 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13229 BuildAndDiagnose, CaptureType, 13230 DeclRefType, Nested, *this)) 13231 return true; 13232 Nested = true; 13233 } else { 13234 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13235 if (!captureInLambda(LSI, Var, ExprLoc, 13236 BuildAndDiagnose, CaptureType, 13237 DeclRefType, Nested, Kind, EllipsisLoc, 13238 /*IsTopScope*/I == N - 1, *this)) 13239 return true; 13240 Nested = true; 13241 } 13242 } 13243 return false; 13244 } 13245 13246 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13247 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13248 QualType CaptureType; 13249 QualType DeclRefType; 13250 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13251 /*BuildAndDiagnose=*/true, CaptureType, 13252 DeclRefType, nullptr); 13253 } 13254 13255 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13256 QualType CaptureType; 13257 QualType DeclRefType; 13258 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13259 /*BuildAndDiagnose=*/false, CaptureType, 13260 DeclRefType, nullptr); 13261 } 13262 13263 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13264 QualType CaptureType; 13265 QualType DeclRefType; 13266 13267 // Determine whether we can capture this variable. 13268 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13269 /*BuildAndDiagnose=*/false, CaptureType, 13270 DeclRefType, nullptr)) 13271 return QualType(); 13272 13273 return DeclRefType; 13274 } 13275 13276 13277 13278 // If either the type of the variable or the initializer is dependent, 13279 // return false. Otherwise, determine whether the variable is a constant 13280 // expression. Use this if you need to know if a variable that might or 13281 // might not be dependent is truly a constant expression. 13282 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13283 ASTContext &Context) { 13284 13285 if (Var->getType()->isDependentType()) 13286 return false; 13287 const VarDecl *DefVD = nullptr; 13288 Var->getAnyInitializer(DefVD); 13289 if (!DefVD) 13290 return false; 13291 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13292 Expr *Init = cast<Expr>(Eval->Value); 13293 if (Init->isValueDependent()) 13294 return false; 13295 return IsVariableAConstantExpression(Var, Context); 13296 } 13297 13298 13299 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13300 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13301 // an object that satisfies the requirements for appearing in a 13302 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13303 // is immediately applied." This function handles the lvalue-to-rvalue 13304 // conversion part. 13305 MaybeODRUseExprs.erase(E->IgnoreParens()); 13306 13307 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13308 // to a variable that is a constant expression, and if so, identify it as 13309 // a reference to a variable that does not involve an odr-use of that 13310 // variable. 13311 if (LambdaScopeInfo *LSI = getCurLambda()) { 13312 Expr *SansParensExpr = E->IgnoreParens(); 13313 VarDecl *Var = nullptr; 13314 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13315 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13316 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13317 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13318 13319 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13320 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13321 } 13322 } 13323 13324 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13325 Res = CorrectDelayedTyposInExpr(Res); 13326 13327 if (!Res.isUsable()) 13328 return Res; 13329 13330 // If a constant-expression is a reference to a variable where we delay 13331 // deciding whether it is an odr-use, just assume we will apply the 13332 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13333 // (a non-type template argument), we have special handling anyway. 13334 UpdateMarkingForLValueToRValue(Res.get()); 13335 return Res; 13336 } 13337 13338 void Sema::CleanupVarDeclMarking() { 13339 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 13340 e = MaybeODRUseExprs.end(); 13341 i != e; ++i) { 13342 VarDecl *Var; 13343 SourceLocation Loc; 13344 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 13345 Var = cast<VarDecl>(DRE->getDecl()); 13346 Loc = DRE->getLocation(); 13347 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 13348 Var = cast<VarDecl>(ME->getMemberDecl()); 13349 Loc = ME->getMemberLoc(); 13350 } else { 13351 llvm_unreachable("Unexpected expression"); 13352 } 13353 13354 MarkVarDeclODRUsed(Var, Loc, *this, 13355 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13356 } 13357 13358 MaybeODRUseExprs.clear(); 13359 } 13360 13361 13362 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13363 VarDecl *Var, Expr *E) { 13364 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13365 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13366 Var->setReferenced(); 13367 13368 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13369 bool MarkODRUsed = true; 13370 13371 // If the context is not potentially evaluated, this is not an odr-use and 13372 // does not trigger instantiation. 13373 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13374 if (SemaRef.isUnevaluatedContext()) 13375 return; 13376 13377 // If we don't yet know whether this context is going to end up being an 13378 // evaluated context, and we're referencing a variable from an enclosing 13379 // scope, add a potential capture. 13380 // 13381 // FIXME: Is this necessary? These contexts are only used for default 13382 // arguments, where local variables can't be used. 13383 const bool RefersToEnclosingScope = 13384 (SemaRef.CurContext != Var->getDeclContext() && 13385 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13386 if (RefersToEnclosingScope) { 13387 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13388 // If a variable could potentially be odr-used, defer marking it so 13389 // until we finish analyzing the full expression for any 13390 // lvalue-to-rvalue 13391 // or discarded value conversions that would obviate odr-use. 13392 // Add it to the list of potential captures that will be analyzed 13393 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13394 // unless the variable is a reference that was initialized by a constant 13395 // expression (this will never need to be captured or odr-used). 13396 assert(E && "Capture variable should be used in an expression."); 13397 if (!Var->getType()->isReferenceType() || 13398 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13399 LSI->addPotentialCapture(E->IgnoreParens()); 13400 } 13401 } 13402 13403 if (!isTemplateInstantiation(TSK)) 13404 return; 13405 13406 // Instantiate, but do not mark as odr-used, variable templates. 13407 MarkODRUsed = false; 13408 } 13409 13410 VarTemplateSpecializationDecl *VarSpec = 13411 dyn_cast<VarTemplateSpecializationDecl>(Var); 13412 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13413 "Can't instantiate a partial template specialization."); 13414 13415 // Perform implicit instantiation of static data members, static data member 13416 // templates of class templates, and variable template specializations. Delay 13417 // instantiations of variable templates, except for those that could be used 13418 // in a constant expression. 13419 if (isTemplateInstantiation(TSK)) { 13420 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13421 13422 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13423 if (Var->getPointOfInstantiation().isInvalid()) { 13424 // This is a modification of an existing AST node. Notify listeners. 13425 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13426 L->StaticDataMemberInstantiated(Var); 13427 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13428 // Don't bother trying to instantiate it again, unless we might need 13429 // its initializer before we get to the end of the TU. 13430 TryInstantiating = false; 13431 } 13432 13433 if (Var->getPointOfInstantiation().isInvalid()) 13434 Var->setTemplateSpecializationKind(TSK, Loc); 13435 13436 if (TryInstantiating) { 13437 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13438 bool InstantiationDependent = false; 13439 bool IsNonDependent = 13440 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13441 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13442 : true; 13443 13444 // Do not instantiate specializations that are still type-dependent. 13445 if (IsNonDependent) { 13446 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13447 // Do not defer instantiations of variables which could be used in a 13448 // constant expression. 13449 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13450 } else { 13451 SemaRef.PendingInstantiations 13452 .push_back(std::make_pair(Var, PointOfInstantiation)); 13453 } 13454 } 13455 } 13456 } 13457 13458 if(!MarkODRUsed) return; 13459 13460 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13461 // the requirements for appearing in a constant expression (5.19) and, if 13462 // it is an object, the lvalue-to-rvalue conversion (4.1) 13463 // is immediately applied." We check the first part here, and 13464 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13465 // Note that we use the C++11 definition everywhere because nothing in 13466 // C++03 depends on whether we get the C++03 version correct. The second 13467 // part does not apply to references, since they are not objects. 13468 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13469 // A reference initialized by a constant expression can never be 13470 // odr-used, so simply ignore it. 13471 if (!Var->getType()->isReferenceType()) 13472 SemaRef.MaybeODRUseExprs.insert(E); 13473 } else 13474 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13475 /*MaxFunctionScopeIndex ptr*/ nullptr); 13476 } 13477 13478 /// \brief Mark a variable referenced, and check whether it is odr-used 13479 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13480 /// used directly for normal expressions referring to VarDecl. 13481 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13482 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13483 } 13484 13485 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13486 Decl *D, Expr *E, bool OdrUse) { 13487 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13488 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13489 return; 13490 } 13491 13492 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13493 13494 // If this is a call to a method via a cast, also mark the method in the 13495 // derived class used in case codegen can devirtualize the call. 13496 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13497 if (!ME) 13498 return; 13499 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13500 if (!MD) 13501 return; 13502 // Only attempt to devirtualize if this is truly a virtual call. 13503 bool IsVirtualCall = MD->isVirtual() && 13504 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13505 if (!IsVirtualCall) 13506 return; 13507 const Expr *Base = ME->getBase(); 13508 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13509 if (!MostDerivedClassDecl) 13510 return; 13511 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13512 if (!DM || DM->isPure()) 13513 return; 13514 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13515 } 13516 13517 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13518 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13519 // TODO: update this with DR# once a defect report is filed. 13520 // C++11 defect. The address of a pure member should not be an ODR use, even 13521 // if it's a qualified reference. 13522 bool OdrUse = true; 13523 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13524 if (Method->isVirtual()) 13525 OdrUse = false; 13526 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13527 } 13528 13529 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13530 void Sema::MarkMemberReferenced(MemberExpr *E) { 13531 // C++11 [basic.def.odr]p2: 13532 // A non-overloaded function whose name appears as a potentially-evaluated 13533 // expression or a member of a set of candidate functions, if selected by 13534 // overload resolution when referred to from a potentially-evaluated 13535 // expression, is odr-used, unless it is a pure virtual function and its 13536 // name is not explicitly qualified. 13537 bool OdrUse = true; 13538 if (E->performsVirtualDispatch(getLangOpts())) { 13539 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13540 if (Method->isPure()) 13541 OdrUse = false; 13542 } 13543 SourceLocation Loc = E->getMemberLoc().isValid() ? 13544 E->getMemberLoc() : E->getLocStart(); 13545 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13546 } 13547 13548 /// \brief Perform marking for a reference to an arbitrary declaration. It 13549 /// marks the declaration referenced, and performs odr-use checking for 13550 /// functions and variables. This method should not be used when building a 13551 /// normal expression which refers to a variable. 13552 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13553 if (OdrUse) { 13554 if (auto *VD = dyn_cast<VarDecl>(D)) { 13555 MarkVariableReferenced(Loc, VD); 13556 return; 13557 } 13558 } 13559 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13560 MarkFunctionReferenced(Loc, FD, OdrUse); 13561 return; 13562 } 13563 D->setReferenced(); 13564 } 13565 13566 namespace { 13567 // Mark all of the declarations referenced 13568 // FIXME: Not fully implemented yet! We need to have a better understanding 13569 // of when we're entering 13570 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13571 Sema &S; 13572 SourceLocation Loc; 13573 13574 public: 13575 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13576 13577 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13578 13579 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13580 bool TraverseRecordType(RecordType *T); 13581 }; 13582 } 13583 13584 bool MarkReferencedDecls::TraverseTemplateArgument( 13585 const TemplateArgument &Arg) { 13586 if (Arg.getKind() == TemplateArgument::Declaration) { 13587 if (Decl *D = Arg.getAsDecl()) 13588 S.MarkAnyDeclReferenced(Loc, D, true); 13589 } 13590 13591 return Inherited::TraverseTemplateArgument(Arg); 13592 } 13593 13594 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13595 if (ClassTemplateSpecializationDecl *Spec 13596 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13597 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13598 return TraverseTemplateArguments(Args.data(), Args.size()); 13599 } 13600 13601 return true; 13602 } 13603 13604 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13605 MarkReferencedDecls Marker(*this, Loc); 13606 Marker.TraverseType(Context.getCanonicalType(T)); 13607 } 13608 13609 namespace { 13610 /// \brief Helper class that marks all of the declarations referenced by 13611 /// potentially-evaluated subexpressions as "referenced". 13612 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13613 Sema &S; 13614 bool SkipLocalVariables; 13615 13616 public: 13617 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13618 13619 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13620 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13621 13622 void VisitDeclRefExpr(DeclRefExpr *E) { 13623 // If we were asked not to visit local variables, don't. 13624 if (SkipLocalVariables) { 13625 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13626 if (VD->hasLocalStorage()) 13627 return; 13628 } 13629 13630 S.MarkDeclRefReferenced(E); 13631 } 13632 13633 void VisitMemberExpr(MemberExpr *E) { 13634 S.MarkMemberReferenced(E); 13635 Inherited::VisitMemberExpr(E); 13636 } 13637 13638 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13639 S.MarkFunctionReferenced(E->getLocStart(), 13640 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13641 Visit(E->getSubExpr()); 13642 } 13643 13644 void VisitCXXNewExpr(CXXNewExpr *E) { 13645 if (E->getOperatorNew()) 13646 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13647 if (E->getOperatorDelete()) 13648 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13649 Inherited::VisitCXXNewExpr(E); 13650 } 13651 13652 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13653 if (E->getOperatorDelete()) 13654 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13655 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13656 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13657 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13658 S.MarkFunctionReferenced(E->getLocStart(), 13659 S.LookupDestructor(Record)); 13660 } 13661 13662 Inherited::VisitCXXDeleteExpr(E); 13663 } 13664 13665 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13666 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13667 Inherited::VisitCXXConstructExpr(E); 13668 } 13669 13670 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13671 Visit(E->getExpr()); 13672 } 13673 13674 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13675 Inherited::VisitImplicitCastExpr(E); 13676 13677 if (E->getCastKind() == CK_LValueToRValue) 13678 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13679 } 13680 }; 13681 } 13682 13683 /// \brief Mark any declarations that appear within this expression or any 13684 /// potentially-evaluated subexpressions as "referenced". 13685 /// 13686 /// \param SkipLocalVariables If true, don't mark local variables as 13687 /// 'referenced'. 13688 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13689 bool SkipLocalVariables) { 13690 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13691 } 13692 13693 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 13694 /// of the program being compiled. 13695 /// 13696 /// This routine emits the given diagnostic when the code currently being 13697 /// type-checked is "potentially evaluated", meaning that there is a 13698 /// possibility that the code will actually be executable. Code in sizeof() 13699 /// expressions, code used only during overload resolution, etc., are not 13700 /// potentially evaluated. This routine will suppress such diagnostics or, 13701 /// in the absolutely nutty case of potentially potentially evaluated 13702 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 13703 /// later. 13704 /// 13705 /// This routine should be used for all diagnostics that describe the run-time 13706 /// behavior of a program, such as passing a non-POD value through an ellipsis. 13707 /// Failure to do so will likely result in spurious diagnostics or failures 13708 /// during overload resolution or within sizeof/alignof/typeof/typeid. 13709 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 13710 const PartialDiagnostic &PD) { 13711 switch (ExprEvalContexts.back().Context) { 13712 case Unevaluated: 13713 case UnevaluatedAbstract: 13714 // The argument will never be evaluated, so don't complain. 13715 break; 13716 13717 case ConstantEvaluated: 13718 // Relevant diagnostics should be produced by constant evaluation. 13719 break; 13720 13721 case PotentiallyEvaluated: 13722 case PotentiallyEvaluatedIfUsed: 13723 if (Statement && getCurFunctionOrMethodDecl()) { 13724 FunctionScopes.back()->PossiblyUnreachableDiags. 13725 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 13726 } 13727 else 13728 Diag(Loc, PD); 13729 13730 return true; 13731 } 13732 13733 return false; 13734 } 13735 13736 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 13737 CallExpr *CE, FunctionDecl *FD) { 13738 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 13739 return false; 13740 13741 // If we're inside a decltype's expression, don't check for a valid return 13742 // type or construct temporaries until we know whether this is the last call. 13743 if (ExprEvalContexts.back().IsDecltype) { 13744 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 13745 return false; 13746 } 13747 13748 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 13749 FunctionDecl *FD; 13750 CallExpr *CE; 13751 13752 public: 13753 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 13754 : FD(FD), CE(CE) { } 13755 13756 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 13757 if (!FD) { 13758 S.Diag(Loc, diag::err_call_incomplete_return) 13759 << T << CE->getSourceRange(); 13760 return; 13761 } 13762 13763 S.Diag(Loc, diag::err_call_function_incomplete_return) 13764 << CE->getSourceRange() << FD->getDeclName() << T; 13765 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 13766 << FD->getDeclName(); 13767 } 13768 } Diagnoser(FD, CE); 13769 13770 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 13771 return true; 13772 13773 return false; 13774 } 13775 13776 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 13777 // will prevent this condition from triggering, which is what we want. 13778 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 13779 SourceLocation Loc; 13780 13781 unsigned diagnostic = diag::warn_condition_is_assignment; 13782 bool IsOrAssign = false; 13783 13784 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 13785 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 13786 return; 13787 13788 IsOrAssign = Op->getOpcode() == BO_OrAssign; 13789 13790 // Greylist some idioms by putting them into a warning subcategory. 13791 if (ObjCMessageExpr *ME 13792 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 13793 Selector Sel = ME->getSelector(); 13794 13795 // self = [<foo> init...] 13796 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 13797 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13798 13799 // <foo> = [<bar> nextObject] 13800 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 13801 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13802 } 13803 13804 Loc = Op->getOperatorLoc(); 13805 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 13806 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 13807 return; 13808 13809 IsOrAssign = Op->getOperator() == OO_PipeEqual; 13810 Loc = Op->getOperatorLoc(); 13811 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 13812 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 13813 else { 13814 // Not an assignment. 13815 return; 13816 } 13817 13818 Diag(Loc, diagnostic) << E->getSourceRange(); 13819 13820 SourceLocation Open = E->getLocStart(); 13821 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 13822 Diag(Loc, diag::note_condition_assign_silence) 13823 << FixItHint::CreateInsertion(Open, "(") 13824 << FixItHint::CreateInsertion(Close, ")"); 13825 13826 if (IsOrAssign) 13827 Diag(Loc, diag::note_condition_or_assign_to_comparison) 13828 << FixItHint::CreateReplacement(Loc, "!="); 13829 else 13830 Diag(Loc, diag::note_condition_assign_to_comparison) 13831 << FixItHint::CreateReplacement(Loc, "=="); 13832 } 13833 13834 /// \brief Redundant parentheses over an equality comparison can indicate 13835 /// that the user intended an assignment used as condition. 13836 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 13837 // Don't warn if the parens came from a macro. 13838 SourceLocation parenLoc = ParenE->getLocStart(); 13839 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 13840 return; 13841 // Don't warn for dependent expressions. 13842 if (ParenE->isTypeDependent()) 13843 return; 13844 13845 Expr *E = ParenE->IgnoreParens(); 13846 13847 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 13848 if (opE->getOpcode() == BO_EQ && 13849 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 13850 == Expr::MLV_Valid) { 13851 SourceLocation Loc = opE->getOperatorLoc(); 13852 13853 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 13854 SourceRange ParenERange = ParenE->getSourceRange(); 13855 Diag(Loc, diag::note_equality_comparison_silence) 13856 << FixItHint::CreateRemoval(ParenERange.getBegin()) 13857 << FixItHint::CreateRemoval(ParenERange.getEnd()); 13858 Diag(Loc, diag::note_equality_comparison_to_assign) 13859 << FixItHint::CreateReplacement(Loc, "="); 13860 } 13861 } 13862 13863 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 13864 DiagnoseAssignmentAsCondition(E); 13865 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 13866 DiagnoseEqualityWithExtraParens(parenE); 13867 13868 ExprResult result = CheckPlaceholderExpr(E); 13869 if (result.isInvalid()) return ExprError(); 13870 E = result.get(); 13871 13872 if (!E->isTypeDependent()) { 13873 if (getLangOpts().CPlusPlus) 13874 return CheckCXXBooleanCondition(E); // C++ 6.4p4 13875 13876 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 13877 if (ERes.isInvalid()) 13878 return ExprError(); 13879 E = ERes.get(); 13880 13881 QualType T = E->getType(); 13882 if (!T->isScalarType()) { // C99 6.8.4.1p1 13883 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 13884 << T << E->getSourceRange(); 13885 return ExprError(); 13886 } 13887 CheckBoolLikeConversion(E, Loc); 13888 } 13889 13890 return E; 13891 } 13892 13893 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 13894 Expr *SubExpr) { 13895 if (!SubExpr) 13896 return ExprError(); 13897 13898 return CheckBooleanCondition(SubExpr, Loc); 13899 } 13900 13901 namespace { 13902 /// A visitor for rebuilding a call to an __unknown_any expression 13903 /// to have an appropriate type. 13904 struct RebuildUnknownAnyFunction 13905 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 13906 13907 Sema &S; 13908 13909 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 13910 13911 ExprResult VisitStmt(Stmt *S) { 13912 llvm_unreachable("unexpected statement!"); 13913 } 13914 13915 ExprResult VisitExpr(Expr *E) { 13916 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 13917 << E->getSourceRange(); 13918 return ExprError(); 13919 } 13920 13921 /// Rebuild an expression which simply semantically wraps another 13922 /// expression which it shares the type and value kind of. 13923 template <class T> ExprResult rebuildSugarExpr(T *E) { 13924 ExprResult SubResult = Visit(E->getSubExpr()); 13925 if (SubResult.isInvalid()) return ExprError(); 13926 13927 Expr *SubExpr = SubResult.get(); 13928 E->setSubExpr(SubExpr); 13929 E->setType(SubExpr->getType()); 13930 E->setValueKind(SubExpr->getValueKind()); 13931 assert(E->getObjectKind() == OK_Ordinary); 13932 return E; 13933 } 13934 13935 ExprResult VisitParenExpr(ParenExpr *E) { 13936 return rebuildSugarExpr(E); 13937 } 13938 13939 ExprResult VisitUnaryExtension(UnaryOperator *E) { 13940 return rebuildSugarExpr(E); 13941 } 13942 13943 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 13944 ExprResult SubResult = Visit(E->getSubExpr()); 13945 if (SubResult.isInvalid()) return ExprError(); 13946 13947 Expr *SubExpr = SubResult.get(); 13948 E->setSubExpr(SubExpr); 13949 E->setType(S.Context.getPointerType(SubExpr->getType())); 13950 assert(E->getValueKind() == VK_RValue); 13951 assert(E->getObjectKind() == OK_Ordinary); 13952 return E; 13953 } 13954 13955 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 13956 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 13957 13958 E->setType(VD->getType()); 13959 13960 assert(E->getValueKind() == VK_RValue); 13961 if (S.getLangOpts().CPlusPlus && 13962 !(isa<CXXMethodDecl>(VD) && 13963 cast<CXXMethodDecl>(VD)->isInstance())) 13964 E->setValueKind(VK_LValue); 13965 13966 return E; 13967 } 13968 13969 ExprResult VisitMemberExpr(MemberExpr *E) { 13970 return resolveDecl(E, E->getMemberDecl()); 13971 } 13972 13973 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 13974 return resolveDecl(E, E->getDecl()); 13975 } 13976 }; 13977 } 13978 13979 /// Given a function expression of unknown-any type, try to rebuild it 13980 /// to have a function type. 13981 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 13982 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 13983 if (Result.isInvalid()) return ExprError(); 13984 return S.DefaultFunctionArrayConversion(Result.get()); 13985 } 13986 13987 namespace { 13988 /// A visitor for rebuilding an expression of type __unknown_anytype 13989 /// into one which resolves the type directly on the referring 13990 /// expression. Strict preservation of the original source 13991 /// structure is not a goal. 13992 struct RebuildUnknownAnyExpr 13993 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 13994 13995 Sema &S; 13996 13997 /// The current destination type. 13998 QualType DestType; 13999 14000 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14001 : S(S), DestType(CastType) {} 14002 14003 ExprResult VisitStmt(Stmt *S) { 14004 llvm_unreachable("unexpected statement!"); 14005 } 14006 14007 ExprResult VisitExpr(Expr *E) { 14008 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14009 << E->getSourceRange(); 14010 return ExprError(); 14011 } 14012 14013 ExprResult VisitCallExpr(CallExpr *E); 14014 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14015 14016 /// Rebuild an expression which simply semantically wraps another 14017 /// expression which it shares the type and value kind of. 14018 template <class T> ExprResult rebuildSugarExpr(T *E) { 14019 ExprResult SubResult = Visit(E->getSubExpr()); 14020 if (SubResult.isInvalid()) return ExprError(); 14021 Expr *SubExpr = SubResult.get(); 14022 E->setSubExpr(SubExpr); 14023 E->setType(SubExpr->getType()); 14024 E->setValueKind(SubExpr->getValueKind()); 14025 assert(E->getObjectKind() == OK_Ordinary); 14026 return E; 14027 } 14028 14029 ExprResult VisitParenExpr(ParenExpr *E) { 14030 return rebuildSugarExpr(E); 14031 } 14032 14033 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14034 return rebuildSugarExpr(E); 14035 } 14036 14037 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14038 const PointerType *Ptr = DestType->getAs<PointerType>(); 14039 if (!Ptr) { 14040 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14041 << E->getSourceRange(); 14042 return ExprError(); 14043 } 14044 assert(E->getValueKind() == VK_RValue); 14045 assert(E->getObjectKind() == OK_Ordinary); 14046 E->setType(DestType); 14047 14048 // Build the sub-expression as if it were an object of the pointee type. 14049 DestType = Ptr->getPointeeType(); 14050 ExprResult SubResult = Visit(E->getSubExpr()); 14051 if (SubResult.isInvalid()) return ExprError(); 14052 E->setSubExpr(SubResult.get()); 14053 return E; 14054 } 14055 14056 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14057 14058 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14059 14060 ExprResult VisitMemberExpr(MemberExpr *E) { 14061 return resolveDecl(E, E->getMemberDecl()); 14062 } 14063 14064 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14065 return resolveDecl(E, E->getDecl()); 14066 } 14067 }; 14068 } 14069 14070 /// Rebuilds a call expression which yielded __unknown_anytype. 14071 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14072 Expr *CalleeExpr = E->getCallee(); 14073 14074 enum FnKind { 14075 FK_MemberFunction, 14076 FK_FunctionPointer, 14077 FK_BlockPointer 14078 }; 14079 14080 FnKind Kind; 14081 QualType CalleeType = CalleeExpr->getType(); 14082 if (CalleeType == S.Context.BoundMemberTy) { 14083 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14084 Kind = FK_MemberFunction; 14085 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14086 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14087 CalleeType = Ptr->getPointeeType(); 14088 Kind = FK_FunctionPointer; 14089 } else { 14090 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14091 Kind = FK_BlockPointer; 14092 } 14093 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14094 14095 // Verify that this is a legal result type of a function. 14096 if (DestType->isArrayType() || DestType->isFunctionType()) { 14097 unsigned diagID = diag::err_func_returning_array_function; 14098 if (Kind == FK_BlockPointer) 14099 diagID = diag::err_block_returning_array_function; 14100 14101 S.Diag(E->getExprLoc(), diagID) 14102 << DestType->isFunctionType() << DestType; 14103 return ExprError(); 14104 } 14105 14106 // Otherwise, go ahead and set DestType as the call's result. 14107 E->setType(DestType.getNonLValueExprType(S.Context)); 14108 E->setValueKind(Expr::getValueKindForType(DestType)); 14109 assert(E->getObjectKind() == OK_Ordinary); 14110 14111 // Rebuild the function type, replacing the result type with DestType. 14112 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14113 if (Proto) { 14114 // __unknown_anytype(...) is a special case used by the debugger when 14115 // it has no idea what a function's signature is. 14116 // 14117 // We want to build this call essentially under the K&R 14118 // unprototyped rules, but making a FunctionNoProtoType in C++ 14119 // would foul up all sorts of assumptions. However, we cannot 14120 // simply pass all arguments as variadic arguments, nor can we 14121 // portably just call the function under a non-variadic type; see 14122 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14123 // However, it turns out that in practice it is generally safe to 14124 // call a function declared as "A foo(B,C,D);" under the prototype 14125 // "A foo(B,C,D,...);". The only known exception is with the 14126 // Windows ABI, where any variadic function is implicitly cdecl 14127 // regardless of its normal CC. Therefore we change the parameter 14128 // types to match the types of the arguments. 14129 // 14130 // This is a hack, but it is far superior to moving the 14131 // corresponding target-specific code from IR-gen to Sema/AST. 14132 14133 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14134 SmallVector<QualType, 8> ArgTypes; 14135 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14136 ArgTypes.reserve(E->getNumArgs()); 14137 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14138 Expr *Arg = E->getArg(i); 14139 QualType ArgType = Arg->getType(); 14140 if (E->isLValue()) { 14141 ArgType = S.Context.getLValueReferenceType(ArgType); 14142 } else if (E->isXValue()) { 14143 ArgType = S.Context.getRValueReferenceType(ArgType); 14144 } 14145 ArgTypes.push_back(ArgType); 14146 } 14147 ParamTypes = ArgTypes; 14148 } 14149 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14150 Proto->getExtProtoInfo()); 14151 } else { 14152 DestType = S.Context.getFunctionNoProtoType(DestType, 14153 FnType->getExtInfo()); 14154 } 14155 14156 // Rebuild the appropriate pointer-to-function type. 14157 switch (Kind) { 14158 case FK_MemberFunction: 14159 // Nothing to do. 14160 break; 14161 14162 case FK_FunctionPointer: 14163 DestType = S.Context.getPointerType(DestType); 14164 break; 14165 14166 case FK_BlockPointer: 14167 DestType = S.Context.getBlockPointerType(DestType); 14168 break; 14169 } 14170 14171 // Finally, we can recurse. 14172 ExprResult CalleeResult = Visit(CalleeExpr); 14173 if (!CalleeResult.isUsable()) return ExprError(); 14174 E->setCallee(CalleeResult.get()); 14175 14176 // Bind a temporary if necessary. 14177 return S.MaybeBindToTemporary(E); 14178 } 14179 14180 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14181 // Verify that this is a legal result type of a call. 14182 if (DestType->isArrayType() || DestType->isFunctionType()) { 14183 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14184 << DestType->isFunctionType() << DestType; 14185 return ExprError(); 14186 } 14187 14188 // Rewrite the method result type if available. 14189 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14190 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14191 Method->setReturnType(DestType); 14192 } 14193 14194 // Change the type of the message. 14195 E->setType(DestType.getNonReferenceType()); 14196 E->setValueKind(Expr::getValueKindForType(DestType)); 14197 14198 return S.MaybeBindToTemporary(E); 14199 } 14200 14201 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14202 // The only case we should ever see here is a function-to-pointer decay. 14203 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14204 assert(E->getValueKind() == VK_RValue); 14205 assert(E->getObjectKind() == OK_Ordinary); 14206 14207 E->setType(DestType); 14208 14209 // Rebuild the sub-expression as the pointee (function) type. 14210 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14211 14212 ExprResult Result = Visit(E->getSubExpr()); 14213 if (!Result.isUsable()) return ExprError(); 14214 14215 E->setSubExpr(Result.get()); 14216 return E; 14217 } else if (E->getCastKind() == CK_LValueToRValue) { 14218 assert(E->getValueKind() == VK_RValue); 14219 assert(E->getObjectKind() == OK_Ordinary); 14220 14221 assert(isa<BlockPointerType>(E->getType())); 14222 14223 E->setType(DestType); 14224 14225 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14226 DestType = S.Context.getLValueReferenceType(DestType); 14227 14228 ExprResult Result = Visit(E->getSubExpr()); 14229 if (!Result.isUsable()) return ExprError(); 14230 14231 E->setSubExpr(Result.get()); 14232 return E; 14233 } else { 14234 llvm_unreachable("Unhandled cast type!"); 14235 } 14236 } 14237 14238 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14239 ExprValueKind ValueKind = VK_LValue; 14240 QualType Type = DestType; 14241 14242 // We know how to make this work for certain kinds of decls: 14243 14244 // - functions 14245 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14246 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14247 DestType = Ptr->getPointeeType(); 14248 ExprResult Result = resolveDecl(E, VD); 14249 if (Result.isInvalid()) return ExprError(); 14250 return S.ImpCastExprToType(Result.get(), Type, 14251 CK_FunctionToPointerDecay, VK_RValue); 14252 } 14253 14254 if (!Type->isFunctionType()) { 14255 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14256 << VD << E->getSourceRange(); 14257 return ExprError(); 14258 } 14259 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14260 // We must match the FunctionDecl's type to the hack introduced in 14261 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14262 // type. See the lengthy commentary in that routine. 14263 QualType FDT = FD->getType(); 14264 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14265 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14266 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14267 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14268 SourceLocation Loc = FD->getLocation(); 14269 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14270 FD->getDeclContext(), 14271 Loc, Loc, FD->getNameInfo().getName(), 14272 DestType, FD->getTypeSourceInfo(), 14273 SC_None, false/*isInlineSpecified*/, 14274 FD->hasPrototype(), 14275 false/*isConstexprSpecified*/); 14276 14277 if (FD->getQualifier()) 14278 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14279 14280 SmallVector<ParmVarDecl*, 16> Params; 14281 for (const auto &AI : FT->param_types()) { 14282 ParmVarDecl *Param = 14283 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14284 Param->setScopeInfo(0, Params.size()); 14285 Params.push_back(Param); 14286 } 14287 NewFD->setParams(Params); 14288 DRE->setDecl(NewFD); 14289 VD = DRE->getDecl(); 14290 } 14291 } 14292 14293 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14294 if (MD->isInstance()) { 14295 ValueKind = VK_RValue; 14296 Type = S.Context.BoundMemberTy; 14297 } 14298 14299 // Function references aren't l-values in C. 14300 if (!S.getLangOpts().CPlusPlus) 14301 ValueKind = VK_RValue; 14302 14303 // - variables 14304 } else if (isa<VarDecl>(VD)) { 14305 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14306 Type = RefTy->getPointeeType(); 14307 } else if (Type->isFunctionType()) { 14308 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14309 << VD << E->getSourceRange(); 14310 return ExprError(); 14311 } 14312 14313 // - nothing else 14314 } else { 14315 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14316 << VD << E->getSourceRange(); 14317 return ExprError(); 14318 } 14319 14320 // Modifying the declaration like this is friendly to IR-gen but 14321 // also really dangerous. 14322 VD->setType(DestType); 14323 E->setType(Type); 14324 E->setValueKind(ValueKind); 14325 return E; 14326 } 14327 14328 /// Check a cast of an unknown-any type. We intentionally only 14329 /// trigger this for C-style casts. 14330 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14331 Expr *CastExpr, CastKind &CastKind, 14332 ExprValueKind &VK, CXXCastPath &Path) { 14333 // Rewrite the casted expression from scratch. 14334 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14335 if (!result.isUsable()) return ExprError(); 14336 14337 CastExpr = result.get(); 14338 VK = CastExpr->getValueKind(); 14339 CastKind = CK_NoOp; 14340 14341 return CastExpr; 14342 } 14343 14344 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14345 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14346 } 14347 14348 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14349 Expr *arg, QualType ¶mType) { 14350 // If the syntactic form of the argument is not an explicit cast of 14351 // any sort, just do default argument promotion. 14352 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14353 if (!castArg) { 14354 ExprResult result = DefaultArgumentPromotion(arg); 14355 if (result.isInvalid()) return ExprError(); 14356 paramType = result.get()->getType(); 14357 return result; 14358 } 14359 14360 // Otherwise, use the type that was written in the explicit cast. 14361 assert(!arg->hasPlaceholderType()); 14362 paramType = castArg->getTypeAsWritten(); 14363 14364 // Copy-initialize a parameter of that type. 14365 InitializedEntity entity = 14366 InitializedEntity::InitializeParameter(Context, paramType, 14367 /*consumed*/ false); 14368 return PerformCopyInitialization(entity, callLoc, arg); 14369 } 14370 14371 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14372 Expr *orig = E; 14373 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14374 while (true) { 14375 E = E->IgnoreParenImpCasts(); 14376 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14377 E = call->getCallee(); 14378 diagID = diag::err_uncasted_call_of_unknown_any; 14379 } else { 14380 break; 14381 } 14382 } 14383 14384 SourceLocation loc; 14385 NamedDecl *d; 14386 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14387 loc = ref->getLocation(); 14388 d = ref->getDecl(); 14389 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14390 loc = mem->getMemberLoc(); 14391 d = mem->getMemberDecl(); 14392 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14393 diagID = diag::err_uncasted_call_of_unknown_any; 14394 loc = msg->getSelectorStartLoc(); 14395 d = msg->getMethodDecl(); 14396 if (!d) { 14397 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14398 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14399 << orig->getSourceRange(); 14400 return ExprError(); 14401 } 14402 } else { 14403 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14404 << E->getSourceRange(); 14405 return ExprError(); 14406 } 14407 14408 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14409 14410 // Never recoverable. 14411 return ExprError(); 14412 } 14413 14414 /// Check for operands with placeholder types and complain if found. 14415 /// Returns true if there was an error and no recovery was possible. 14416 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14417 if (!getLangOpts().CPlusPlus) { 14418 // C cannot handle TypoExpr nodes on either side of a binop because it 14419 // doesn't handle dependent types properly, so make sure any TypoExprs have 14420 // been dealt with before checking the operands. 14421 ExprResult Result = CorrectDelayedTyposInExpr(E); 14422 if (!Result.isUsable()) return ExprError(); 14423 E = Result.get(); 14424 } 14425 14426 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14427 if (!placeholderType) return E; 14428 14429 switch (placeholderType->getKind()) { 14430 14431 // Overloaded expressions. 14432 case BuiltinType::Overload: { 14433 // Try to resolve a single function template specialization. 14434 // This is obligatory. 14435 ExprResult result = E; 14436 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14437 return result; 14438 14439 // If that failed, try to recover with a call. 14440 } else { 14441 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14442 /*complain*/ true); 14443 return result; 14444 } 14445 } 14446 14447 // Bound member functions. 14448 case BuiltinType::BoundMember: { 14449 ExprResult result = E; 14450 const Expr *BME = E->IgnoreParens(); 14451 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14452 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14453 if (isa<CXXPseudoDestructorExpr>(BME)) { 14454 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14455 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14456 if (ME->getMemberNameInfo().getName().getNameKind() == 14457 DeclarationName::CXXDestructorName) 14458 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14459 } 14460 tryToRecoverWithCall(result, PD, 14461 /*complain*/ true); 14462 return result; 14463 } 14464 14465 // ARC unbridged casts. 14466 case BuiltinType::ARCUnbridgedCast: { 14467 Expr *realCast = stripARCUnbridgedCast(E); 14468 diagnoseARCUnbridgedCast(realCast); 14469 return realCast; 14470 } 14471 14472 // Expressions of unknown type. 14473 case BuiltinType::UnknownAny: 14474 return diagnoseUnknownAnyExpr(*this, E); 14475 14476 // Pseudo-objects. 14477 case BuiltinType::PseudoObject: 14478 return checkPseudoObjectRValue(E); 14479 14480 case BuiltinType::BuiltinFn: { 14481 // Accept __noop without parens by implicitly converting it to a call expr. 14482 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14483 if (DRE) { 14484 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14485 if (FD->getBuiltinID() == Builtin::BI__noop) { 14486 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14487 CK_BuiltinFnToFnPtr).get(); 14488 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14489 VK_RValue, SourceLocation()); 14490 } 14491 } 14492 14493 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14494 return ExprError(); 14495 } 14496 14497 // Expressions of unknown type. 14498 case BuiltinType::OMPArraySection: 14499 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14500 return ExprError(); 14501 14502 // Everything else should be impossible. 14503 #define BUILTIN_TYPE(Id, SingletonId) \ 14504 case BuiltinType::Id: 14505 #define PLACEHOLDER_TYPE(Id, SingletonId) 14506 #include "clang/AST/BuiltinTypes.def" 14507 break; 14508 } 14509 14510 llvm_unreachable("invalid placeholder type!"); 14511 } 14512 14513 bool Sema::CheckCaseExpression(Expr *E) { 14514 if (E->isTypeDependent()) 14515 return true; 14516 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14517 return E->getType()->isIntegralOrEnumerationType(); 14518 return false; 14519 } 14520 14521 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14522 ExprResult 14523 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14524 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14525 "Unknown Objective-C Boolean value!"); 14526 QualType BoolT = Context.ObjCBuiltinBoolTy; 14527 if (!Context.getBOOLDecl()) { 14528 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14529 Sema::LookupOrdinaryName); 14530 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14531 NamedDecl *ND = Result.getFoundDecl(); 14532 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14533 Context.setBOOLDecl(TD); 14534 } 14535 } 14536 if (Context.getBOOLDecl()) 14537 BoolT = Context.getBOOLType(); 14538 return new (Context) 14539 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14540 } 14541