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 Result == 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 // With nopartial, the compiler will emit delayed error just like how 163 // "deprecated, unavailable" are handled. 164 AvailabilityAttr *AA = D->getAttr<AvailabilityAttr>(); 165 if (AA && AA->getNopartial() && 166 S.getCurContextAvailability() != AR_NotYetIntroduced) 167 S.EmitAvailabilityWarning(Sema::AD_NotYetIntroduced, 168 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 169 ObjCPropertyAccess); 170 171 // Don't do this for enums, they can't be redeclared. 172 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 173 break; 174 175 bool Warn = !AA->isInherited(); 176 // Objective-C method declarations in categories are not modelled as 177 // redeclarations, so manually look for a redeclaration in a category 178 // if necessary. 179 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 180 Warn = false; 181 // In general, D will point to the most recent redeclaration. However, 182 // for `@class A;` decls, this isn't true -- manually go through the 183 // redecl chain in that case. 184 if (Warn && isa<ObjCInterfaceDecl>(D)) 185 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 186 Redecl = Redecl->getPreviousDecl()) 187 if (!Redecl->hasAttr<AvailabilityAttr>() || 188 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 189 Warn = false; 190 191 if (Warn) 192 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 193 UnknownObjCClass, ObjCPDecl, 194 ObjCPropertyAccess); 195 break; 196 } 197 198 case AR_Unavailable: 199 if (S.getCurContextAvailability() != AR_Unavailable) 200 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 201 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 202 ObjCPropertyAccess); 203 break; 204 205 } 206 return Result; 207 } 208 209 /// \brief Emit a note explaining that this function is deleted. 210 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 211 assert(Decl->isDeleted()); 212 213 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 214 215 if (Method && Method->isDeleted() && Method->isDefaulted()) { 216 // If the method was explicitly defaulted, point at that declaration. 217 if (!Method->isImplicit()) 218 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 219 220 // Try to diagnose why this special member function was implicitly 221 // deleted. This might fail, if that reason no longer applies. 222 CXXSpecialMember CSM = getSpecialMember(Method); 223 if (CSM != CXXInvalid) 224 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 225 226 return; 227 } 228 229 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 230 if (CXXConstructorDecl *BaseCD = 231 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 232 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 233 if (BaseCD->isDeleted()) { 234 NoteDeletedFunction(BaseCD); 235 } else { 236 // FIXME: An explanation of why exactly it can't be inherited 237 // would be nice. 238 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 239 } 240 return; 241 } 242 } 243 244 Diag(Decl->getLocation(), diag::note_availability_specified_here) 245 << Decl << true; 246 } 247 248 /// \brief Determine whether a FunctionDecl was ever declared with an 249 /// explicit storage class. 250 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 251 for (auto I : D->redecls()) { 252 if (I->getStorageClass() != SC_None) 253 return true; 254 } 255 return false; 256 } 257 258 /// \brief Check whether we're in an extern inline function and referring to a 259 /// variable or function with internal linkage (C11 6.7.4p3). 260 /// 261 /// This is only a warning because we used to silently accept this code, but 262 /// in many cases it will not behave correctly. This is not enabled in C++ mode 263 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 264 /// and so while there may still be user mistakes, most of the time we can't 265 /// prove that there are errors. 266 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 267 const NamedDecl *D, 268 SourceLocation Loc) { 269 // This is disabled under C++; there are too many ways for this to fire in 270 // contexts where the warning is a false positive, or where it is technically 271 // correct but benign. 272 if (S.getLangOpts().CPlusPlus) 273 return; 274 275 // Check if this is an inlined function or method. 276 FunctionDecl *Current = S.getCurFunctionDecl(); 277 if (!Current) 278 return; 279 if (!Current->isInlined()) 280 return; 281 if (!Current->isExternallyVisible()) 282 return; 283 284 // Check if the decl has internal linkage. 285 if (D->getFormalLinkage() != InternalLinkage) 286 return; 287 288 // Downgrade from ExtWarn to Extension if 289 // (1) the supposedly external inline function is in the main file, 290 // and probably won't be included anywhere else. 291 // (2) the thing we're referencing is a pure function. 292 // (3) the thing we're referencing is another inline function. 293 // This last can give us false negatives, but it's better than warning on 294 // wrappers for simple C library functions. 295 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 296 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 297 if (!DowngradeWarning && UsedFn) 298 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 299 300 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 301 : diag::ext_internal_in_extern_inline) 302 << /*IsVar=*/!UsedFn << D; 303 304 S.MaybeSuggestAddingStaticToDecl(Current); 305 306 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 307 << D; 308 } 309 310 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 311 const FunctionDecl *First = Cur->getFirstDecl(); 312 313 // Suggest "static" on the function, if possible. 314 if (!hasAnyExplicitStorageClass(First)) { 315 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 316 Diag(DeclBegin, diag::note_convert_inline_to_static) 317 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 318 } 319 } 320 321 /// \brief Determine whether the use of this declaration is valid, and 322 /// emit any corresponding diagnostics. 323 /// 324 /// This routine diagnoses various problems with referencing 325 /// declarations that can occur when using a declaration. For example, 326 /// it might warn if a deprecated or unavailable declaration is being 327 /// used, or produce an error (and return true) if a C++0x deleted 328 /// function is being used. 329 /// 330 /// \returns true if there was an error (this declaration cannot be 331 /// referenced), false otherwise. 332 /// 333 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 334 const ObjCInterfaceDecl *UnknownObjCClass, 335 bool ObjCPropertyAccess) { 336 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 337 // If there were any diagnostics suppressed by template argument deduction, 338 // emit them now. 339 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 340 if (Pos != SuppressedDiagnostics.end()) { 341 for (const PartialDiagnosticAt &Suppressed : Pos->second) 342 Diag(Suppressed.first, Suppressed.second); 343 344 // Clear out the list of suppressed diagnostics, so that we don't emit 345 // them again for this specialization. However, we don't obsolete this 346 // entry from the table, because we want to avoid ever emitting these 347 // diagnostics again. 348 Pos->second.clear(); 349 } 350 351 // C++ [basic.start.main]p3: 352 // The function 'main' shall not be used within a program. 353 if (cast<FunctionDecl>(D)->isMain()) 354 Diag(Loc, diag::ext_main_used); 355 } 356 357 // See if this is an auto-typed variable whose initializer we are parsing. 358 if (ParsingInitForAutoVars.count(D)) { 359 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 360 361 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 362 << D->getDeclName() << (unsigned)AT->getKeyword(); 363 return true; 364 } 365 366 // See if this is a deleted function. 367 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 368 if (FD->isDeleted()) { 369 Diag(Loc, diag::err_deleted_function_use); 370 NoteDeletedFunction(FD); 371 return true; 372 } 373 374 // If the function has a deduced return type, and we can't deduce it, 375 // then we can't use it either. 376 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 377 DeduceReturnType(FD, Loc)) 378 return true; 379 } 380 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 381 ObjCPropertyAccess); 382 383 DiagnoseUnusedOfDecl(*this, D, Loc); 384 385 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 386 387 return false; 388 } 389 390 /// \brief Retrieve the message suffix that should be added to a 391 /// diagnostic complaining about the given function being deleted or 392 /// unavailable. 393 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 394 std::string Message; 395 if (FD->getAvailability(&Message)) 396 return ": " + Message; 397 398 return std::string(); 399 } 400 401 /// DiagnoseSentinelCalls - This routine checks whether a call or 402 /// message-send is to a declaration with the sentinel attribute, and 403 /// if so, it checks that the requirements of the sentinel are 404 /// satisfied. 405 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 406 ArrayRef<Expr *> Args) { 407 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 408 if (!attr) 409 return; 410 411 // The number of formal parameters of the declaration. 412 unsigned numFormalParams; 413 414 // The kind of declaration. This is also an index into a %select in 415 // the diagnostic. 416 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 417 418 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 419 numFormalParams = MD->param_size(); 420 calleeType = CT_Method; 421 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 422 numFormalParams = FD->param_size(); 423 calleeType = CT_Function; 424 } else if (isa<VarDecl>(D)) { 425 QualType type = cast<ValueDecl>(D)->getType(); 426 const FunctionType *fn = nullptr; 427 if (const PointerType *ptr = type->getAs<PointerType>()) { 428 fn = ptr->getPointeeType()->getAs<FunctionType>(); 429 if (!fn) return; 430 calleeType = CT_Function; 431 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 432 fn = ptr->getPointeeType()->castAs<FunctionType>(); 433 calleeType = CT_Block; 434 } else { 435 return; 436 } 437 438 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 439 numFormalParams = proto->getNumParams(); 440 } else { 441 numFormalParams = 0; 442 } 443 } else { 444 return; 445 } 446 447 // "nullPos" is the number of formal parameters at the end which 448 // effectively count as part of the variadic arguments. This is 449 // useful if you would prefer to not have *any* formal parameters, 450 // but the language forces you to have at least one. 451 unsigned nullPos = attr->getNullPos(); 452 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 453 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 454 455 // The number of arguments which should follow the sentinel. 456 unsigned numArgsAfterSentinel = attr->getSentinel(); 457 458 // If there aren't enough arguments for all the formal parameters, 459 // the sentinel, and the args after the sentinel, complain. 460 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 462 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 463 return; 464 } 465 466 // Otherwise, find the sentinel expression. 467 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 468 if (!sentinelExpr) return; 469 if (sentinelExpr->isValueDependent()) return; 470 if (Context.isSentinelNullExpr(sentinelExpr)) return; 471 472 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 473 // or 'NULL' if those are actually defined in the context. Only use 474 // 'nil' for ObjC methods, where it's much more likely that the 475 // variadic arguments form a list of object pointers. 476 SourceLocation MissingNilLoc 477 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 478 std::string NullValue; 479 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 480 NullValue = "nil"; 481 else if (getLangOpts().CPlusPlus11) 482 NullValue = "nullptr"; 483 else if (PP.isMacroDefined("NULL")) 484 NullValue = "NULL"; 485 else 486 NullValue = "(void*) 0"; 487 488 if (MissingNilLoc.isInvalid()) 489 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 490 else 491 Diag(MissingNilLoc, diag::warn_missing_sentinel) 492 << int(calleeType) 493 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 494 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 495 } 496 497 SourceRange Sema::getExprRange(Expr *E) const { 498 return E ? E->getSourceRange() : SourceRange(); 499 } 500 501 //===----------------------------------------------------------------------===// 502 // Standard Promotions and Conversions 503 //===----------------------------------------------------------------------===// 504 505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 506 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 507 // Handle any placeholder expressions which made it here. 508 if (E->getType()->isPlaceholderType()) { 509 ExprResult result = CheckPlaceholderExpr(E); 510 if (result.isInvalid()) return ExprError(); 511 E = result.get(); 512 } 513 514 QualType Ty = E->getType(); 515 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 516 517 if (Ty->isFunctionType()) { 518 // If we are here, we are not calling a function but taking 519 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 520 if (getLangOpts().OpenCL) { 521 if (Diagnose) 522 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 523 return ExprError(); 524 } 525 526 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 527 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 528 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 529 return ExprError(); 530 531 E = ImpCastExprToType(E, Context.getPointerType(Ty), 532 CK_FunctionToPointerDecay).get(); 533 } else if (Ty->isArrayType()) { 534 // In C90 mode, arrays only promote to pointers if the array expression is 535 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 536 // type 'array of type' is converted to an expression that has type 'pointer 537 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 538 // that has type 'array of type' ...". The relevant change is "an lvalue" 539 // (C90) to "an expression" (C99). 540 // 541 // C++ 4.2p1: 542 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 543 // T" can be converted to an rvalue of type "pointer to T". 544 // 545 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 546 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 547 CK_ArrayToPointerDecay).get(); 548 } 549 return E; 550 } 551 552 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 553 // Check to see if we are dereferencing a null pointer. If so, 554 // and if not volatile-qualified, this is undefined behavior that the 555 // optimizer will delete, so warn about it. People sometimes try to use this 556 // to get a deterministic trap and are surprised by clang's behavior. This 557 // only handles the pattern "*null", which is a very syntactic check. 558 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 559 if (UO->getOpcode() == UO_Deref && 560 UO->getSubExpr()->IgnoreParenCasts()-> 561 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 562 !UO->getType().isVolatileQualified()) { 563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 564 S.PDiag(diag::warn_indirection_through_null) 565 << UO->getSubExpr()->getSourceRange()); 566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 567 S.PDiag(diag::note_indirection_through_null)); 568 } 569 } 570 571 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 572 SourceLocation AssignLoc, 573 const Expr* RHS) { 574 const ObjCIvarDecl *IV = OIRE->getDecl(); 575 if (!IV) 576 return; 577 578 DeclarationName MemberName = IV->getDeclName(); 579 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 580 if (!Member || !Member->isStr("isa")) 581 return; 582 583 const Expr *Base = OIRE->getBase(); 584 QualType BaseType = Base->getType(); 585 if (OIRE->isArrow()) 586 BaseType = BaseType->getPointeeType(); 587 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 588 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 589 ObjCInterfaceDecl *ClassDeclared = nullptr; 590 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 591 if (!ClassDeclared->getSuperClass() 592 && (*ClassDeclared->ivar_begin()) == IV) { 593 if (RHS) { 594 NamedDecl *ObjectSetClass = 595 S.LookupSingleName(S.TUScope, 596 &S.Context.Idents.get("object_setClass"), 597 SourceLocation(), S.LookupOrdinaryName); 598 if (ObjectSetClass) { 599 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 600 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 601 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 602 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 603 AssignLoc), ",") << 604 FixItHint::CreateInsertion(RHSLocEnd, ")"); 605 } 606 else 607 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 608 } else { 609 NamedDecl *ObjectGetClass = 610 S.LookupSingleName(S.TUScope, 611 &S.Context.Idents.get("object_getClass"), 612 SourceLocation(), S.LookupOrdinaryName); 613 if (ObjectGetClass) 614 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 615 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 616 FixItHint::CreateReplacement( 617 SourceRange(OIRE->getOpLoc(), 618 OIRE->getLocEnd()), ")"); 619 else 620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 621 } 622 S.Diag(IV->getLocation(), diag::note_ivar_decl); 623 } 624 } 625 } 626 627 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 628 // Handle any placeholder expressions which made it here. 629 if (E->getType()->isPlaceholderType()) { 630 ExprResult result = CheckPlaceholderExpr(E); 631 if (result.isInvalid()) return ExprError(); 632 E = result.get(); 633 } 634 635 // C++ [conv.lval]p1: 636 // A glvalue of a non-function, non-array type T can be 637 // converted to a prvalue. 638 if (!E->isGLValue()) return E; 639 640 QualType T = E->getType(); 641 assert(!T.isNull() && "r-value conversion on typeless expression?"); 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 674 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 675 FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 UpdateMarkingForLValueToRValue(E); 702 703 // Loading a __weak object implicitly retains the value, so we need a cleanup to 704 // balance that. 705 if (getLangOpts().ObjCAutoRefCount && 706 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 707 ExprNeedsCleanups = true; 708 709 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 710 nullptr, VK_RValue); 711 712 // C11 6.3.2.1p2: 713 // ... if the lvalue has atomic type, the value has the non-atomic version 714 // of the type of the lvalue ... 715 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 716 T = Atomic->getValueType().getUnqualifiedType(); 717 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 718 nullptr, VK_RValue); 719 } 720 721 return Res; 722 } 723 724 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 725 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 726 if (Res.isInvalid()) 727 return ExprError(); 728 Res = DefaultLvalueConversion(Res.get()); 729 if (Res.isInvalid()) 730 return ExprError(); 731 return Res; 732 } 733 734 /// CallExprUnaryConversions - a special case of an unary conversion 735 /// performed on a function designator of a call expression. 736 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 737 QualType Ty = E->getType(); 738 ExprResult Res = E; 739 // Only do implicit cast for a function type, but not for a pointer 740 // to function type. 741 if (Ty->isFunctionType()) { 742 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 743 CK_FunctionToPointerDecay).get(); 744 if (Res.isInvalid()) 745 return ExprError(); 746 } 747 Res = DefaultLvalueConversion(Res.get()); 748 if (Res.isInvalid()) 749 return ExprError(); 750 return Res.get(); 751 } 752 753 /// UsualUnaryConversions - Performs various conversions that are common to most 754 /// operators (C99 6.3). The conversions of array and function types are 755 /// sometimes suppressed. For example, the array->pointer conversion doesn't 756 /// apply if the array is an argument to the sizeof or address (&) operators. 757 /// In these instances, this routine should *not* be called. 758 ExprResult Sema::UsualUnaryConversions(Expr *E) { 759 // First, convert to an r-value. 760 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 761 if (Res.isInvalid()) 762 return ExprError(); 763 E = Res.get(); 764 765 QualType Ty = E->getType(); 766 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 767 768 // Half FP have to be promoted to float unless it is natively supported 769 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 770 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 771 772 // Try to perform integral promotions if the object has a theoretically 773 // promotable type. 774 if (Ty->isIntegralOrUnscopedEnumerationType()) { 775 // C99 6.3.1.1p2: 776 // 777 // The following may be used in an expression wherever an int or 778 // unsigned int may be used: 779 // - an object or expression with an integer type whose integer 780 // conversion rank is less than or equal to the rank of int 781 // and unsigned int. 782 // - A bit-field of type _Bool, int, signed int, or unsigned int. 783 // 784 // If an int can represent all values of the original type, the 785 // value is converted to an int; otherwise, it is converted to an 786 // unsigned int. These are called the integer promotions. All 787 // other types are unchanged by the integer promotions. 788 789 QualType PTy = Context.isPromotableBitField(E); 790 if (!PTy.isNull()) { 791 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 792 return E; 793 } 794 if (Ty->isPromotableIntegerType()) { 795 QualType PT = Context.getPromotedIntegerType(Ty); 796 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 797 return E; 798 } 799 } 800 return E; 801 } 802 803 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 804 /// do not have a prototype. Arguments that have type float or __fp16 805 /// are promoted to double. All other argument types are converted by 806 /// UsualUnaryConversions(). 807 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 808 QualType Ty = E->getType(); 809 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 810 811 ExprResult Res = UsualUnaryConversions(E); 812 if (Res.isInvalid()) 813 return ExprError(); 814 E = Res.get(); 815 816 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 817 // double. 818 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 819 if (BTy && (BTy->getKind() == BuiltinType::Half || 820 BTy->getKind() == BuiltinType::Float)) 821 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 822 823 // C++ performs lvalue-to-rvalue conversion as a default argument 824 // promotion, even on class types, but note: 825 // C++11 [conv.lval]p2: 826 // When an lvalue-to-rvalue conversion occurs in an unevaluated 827 // operand or a subexpression thereof the value contained in the 828 // referenced object is not accessed. Otherwise, if the glvalue 829 // has a class type, the conversion copy-initializes a temporary 830 // of type T from the glvalue and the result of the conversion 831 // is a prvalue for the temporary. 832 // FIXME: add some way to gate this entire thing for correctness in 833 // potentially potentially evaluated contexts. 834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 835 ExprResult Temp = PerformCopyInitialization( 836 InitializedEntity::InitializeTemporary(E->getType()), 837 E->getExprLoc(), E); 838 if (Temp.isInvalid()) 839 return ExprError(); 840 E = Temp.get(); 841 } 842 843 return E; 844 } 845 846 /// Determine the degree of POD-ness for an expression. 847 /// Incomplete types are considered POD, since this check can be performed 848 /// when we're in an unevaluated context. 849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 850 if (Ty->isIncompleteType()) { 851 // C++11 [expr.call]p7: 852 // After these conversions, if the argument does not have arithmetic, 853 // enumeration, pointer, pointer to member, or class type, the program 854 // is ill-formed. 855 // 856 // Since we've already performed array-to-pointer and function-to-pointer 857 // decay, the only such type in C++ is cv void. This also handles 858 // initializer lists as variadic arguments. 859 if (Ty->isVoidType()) 860 return VAK_Invalid; 861 862 if (Ty->isObjCObjectType()) 863 return VAK_Invalid; 864 return VAK_Valid; 865 } 866 867 if (Ty.isCXX98PODType(Context)) 868 return VAK_Valid; 869 870 // C++11 [expr.call]p7: 871 // Passing a potentially-evaluated argument of class type (Clause 9) 872 // having a non-trivial copy constructor, a non-trivial move constructor, 873 // or a non-trivial destructor, with no corresponding parameter, 874 // is conditionally-supported with implementation-defined semantics. 875 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 876 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 877 if (!Record->hasNonTrivialCopyConstructor() && 878 !Record->hasNonTrivialMoveConstructor() && 879 !Record->hasNonTrivialDestructor()) 880 return VAK_ValidInCXX11; 881 882 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 883 return VAK_Valid; 884 885 if (Ty->isObjCObjectType()) 886 return VAK_Invalid; 887 888 if (getLangOpts().MSVCCompat) 889 return VAK_MSVCUndefined; 890 891 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 892 // permitted to reject them. We should consider doing so. 893 return VAK_Undefined; 894 } 895 896 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 897 // Don't allow one to pass an Objective-C interface to a vararg. 898 const QualType &Ty = E->getType(); 899 VarArgKind VAK = isValidVarArgType(Ty); 900 901 // Complain about passing non-POD types through varargs. 902 switch (VAK) { 903 case VAK_ValidInCXX11: 904 DiagRuntimeBehavior( 905 E->getLocStart(), nullptr, 906 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 907 << Ty << CT); 908 // Fall through. 909 case VAK_Valid: 910 if (Ty->isRecordType()) { 911 // This is unlikely to be what the user intended. If the class has a 912 // 'c_str' member function, the user probably meant to call that. 913 DiagRuntimeBehavior(E->getLocStart(), nullptr, 914 PDiag(diag::warn_pass_class_arg_to_vararg) 915 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 916 } 917 break; 918 919 case VAK_Undefined: 920 case VAK_MSVCUndefined: 921 DiagRuntimeBehavior( 922 E->getLocStart(), nullptr, 923 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 924 << getLangOpts().CPlusPlus11 << Ty << CT); 925 break; 926 927 case VAK_Invalid: 928 if (Ty->isObjCObjectType()) 929 DiagRuntimeBehavior( 930 E->getLocStart(), nullptr, 931 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 932 << Ty << CT); 933 else 934 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 935 << isa<InitListExpr>(E) << Ty << CT; 936 break; 937 } 938 } 939 940 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 941 /// will create a trap if the resulting type is not a POD type. 942 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 943 FunctionDecl *FDecl) { 944 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 945 // Strip the unbridged-cast placeholder expression off, if applicable. 946 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 947 (CT == VariadicMethod || 948 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 949 E = stripARCUnbridgedCast(E); 950 951 // Otherwise, do normal placeholder checking. 952 } else { 953 ExprResult ExprRes = CheckPlaceholderExpr(E); 954 if (ExprRes.isInvalid()) 955 return ExprError(); 956 E = ExprRes.get(); 957 } 958 } 959 960 ExprResult ExprRes = DefaultArgumentPromotion(E); 961 if (ExprRes.isInvalid()) 962 return ExprError(); 963 E = ExprRes.get(); 964 965 // Diagnostics regarding non-POD argument types are 966 // emitted along with format string checking in Sema::CheckFunctionCall(). 967 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 968 // Turn this into a trap. 969 CXXScopeSpec SS; 970 SourceLocation TemplateKWLoc; 971 UnqualifiedId Name; 972 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 973 E->getLocStart()); 974 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 975 Name, true, false); 976 if (TrapFn.isInvalid()) 977 return ExprError(); 978 979 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 980 E->getLocStart(), None, 981 E->getLocEnd()); 982 if (Call.isInvalid()) 983 return ExprError(); 984 985 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 986 Call.get(), E); 987 if (Comma.isInvalid()) 988 return ExprError(); 989 return Comma.get(); 990 } 991 992 if (!getLangOpts().CPlusPlus && 993 RequireCompleteType(E->getExprLoc(), E->getType(), 994 diag::err_call_incomplete_argument)) 995 return ExprError(); 996 997 return E; 998 } 999 1000 /// \brief Converts an integer to complex float type. Helper function of 1001 /// UsualArithmeticConversions() 1002 /// 1003 /// \return false if the integer expression is an integer type and is 1004 /// successfully converted to the complex type. 1005 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1006 ExprResult &ComplexExpr, 1007 QualType IntTy, 1008 QualType ComplexTy, 1009 bool SkipCast) { 1010 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1011 if (SkipCast) return false; 1012 if (IntTy->isIntegerType()) { 1013 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1014 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1015 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1016 CK_FloatingRealToComplex); 1017 } else { 1018 assert(IntTy->isComplexIntegerType()); 1019 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1020 CK_IntegralComplexToFloatingComplex); 1021 } 1022 return false; 1023 } 1024 1025 /// \brief Handle arithmetic conversion with complex types. Helper function of 1026 /// UsualArithmeticConversions() 1027 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1028 ExprResult &RHS, QualType LHSType, 1029 QualType RHSType, 1030 bool IsCompAssign) { 1031 // if we have an integer operand, the result is the complex type. 1032 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1033 /*skipCast*/false)) 1034 return LHSType; 1035 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1036 /*skipCast*/IsCompAssign)) 1037 return RHSType; 1038 1039 // This handles complex/complex, complex/float, or float/complex. 1040 // When both operands are complex, the shorter operand is converted to the 1041 // type of the longer, and that is the type of the result. This corresponds 1042 // to what is done when combining two real floating-point operands. 1043 // The fun begins when size promotion occur across type domains. 1044 // From H&S 6.3.4: When one operand is complex and the other is a real 1045 // floating-point type, the less precise type is converted, within it's 1046 // real or complex domain, to the precision of the other type. For example, 1047 // when combining a "long double" with a "double _Complex", the 1048 // "double _Complex" is promoted to "long double _Complex". 1049 1050 // Compute the rank of the two types, regardless of whether they are complex. 1051 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1052 1053 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1054 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1055 QualType LHSElementType = 1056 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1057 QualType RHSElementType = 1058 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1059 1060 QualType ResultType = S.Context.getComplexType(LHSElementType); 1061 if (Order < 0) { 1062 // Promote the precision of the LHS if not an assignment. 1063 ResultType = S.Context.getComplexType(RHSElementType); 1064 if (!IsCompAssign) { 1065 if (LHSComplexType) 1066 LHS = 1067 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1068 else 1069 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1070 } 1071 } else if (Order > 0) { 1072 // Promote the precision of the RHS. 1073 if (RHSComplexType) 1074 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1075 else 1076 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1077 } 1078 return ResultType; 1079 } 1080 1081 /// \brief Hande arithmetic conversion from integer to float. Helper function 1082 /// of UsualArithmeticConversions() 1083 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1084 ExprResult &IntExpr, 1085 QualType FloatTy, QualType IntTy, 1086 bool ConvertFloat, bool ConvertInt) { 1087 if (IntTy->isIntegerType()) { 1088 if (ConvertInt) 1089 // Convert intExpr to the lhs floating point type. 1090 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1091 CK_IntegralToFloating); 1092 return FloatTy; 1093 } 1094 1095 // Convert both sides to the appropriate complex float. 1096 assert(IntTy->isComplexIntegerType()); 1097 QualType result = S.Context.getComplexType(FloatTy); 1098 1099 // _Complex int -> _Complex float 1100 if (ConvertInt) 1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1102 CK_IntegralComplexToFloatingComplex); 1103 1104 // float -> _Complex float 1105 if (ConvertFloat) 1106 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1107 CK_FloatingRealToComplex); 1108 1109 return result; 1110 } 1111 1112 /// \brief Handle arithmethic conversion with floating point types. Helper 1113 /// function of UsualArithmeticConversions() 1114 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1115 ExprResult &RHS, QualType LHSType, 1116 QualType RHSType, bool IsCompAssign) { 1117 bool LHSFloat = LHSType->isRealFloatingType(); 1118 bool RHSFloat = RHSType->isRealFloatingType(); 1119 1120 // If we have two real floating types, convert the smaller operand 1121 // to the bigger result. 1122 if (LHSFloat && RHSFloat) { 1123 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1124 if (order > 0) { 1125 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1126 return LHSType; 1127 } 1128 1129 assert(order < 0 && "illegal float comparison"); 1130 if (!IsCompAssign) 1131 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1132 return RHSType; 1133 } 1134 1135 if (LHSFloat) { 1136 // Half FP has to be promoted to float unless it is natively supported 1137 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1138 LHSType = S.Context.FloatTy; 1139 1140 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1141 /*convertFloat=*/!IsCompAssign, 1142 /*convertInt=*/ true); 1143 } 1144 assert(RHSFloat); 1145 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1146 /*convertInt=*/ true, 1147 /*convertFloat=*/!IsCompAssign); 1148 } 1149 1150 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1151 1152 namespace { 1153 /// These helper callbacks are placed in an anonymous namespace to 1154 /// permit their use as function template parameters. 1155 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1156 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1157 } 1158 1159 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1160 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1161 CK_IntegralComplexCast); 1162 } 1163 } 1164 1165 /// \brief Handle integer arithmetic conversions. Helper function of 1166 /// UsualArithmeticConversions() 1167 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1168 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1169 ExprResult &RHS, QualType LHSType, 1170 QualType RHSType, bool IsCompAssign) { 1171 // The rules for this case are in C99 6.3.1.8 1172 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1173 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1174 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1175 if (LHSSigned == RHSSigned) { 1176 // Same signedness; use the higher-ranked type 1177 if (order >= 0) { 1178 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1179 return LHSType; 1180 } else if (!IsCompAssign) 1181 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1182 return RHSType; 1183 } else if (order != (LHSSigned ? 1 : -1)) { 1184 // The unsigned type has greater than or equal rank to the 1185 // signed type, so use the unsigned type 1186 if (RHSSigned) { 1187 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1188 return LHSType; 1189 } else if (!IsCompAssign) 1190 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1191 return RHSType; 1192 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1193 // The two types are different widths; if we are here, that 1194 // means the signed type is larger than the unsigned type, so 1195 // use the signed type. 1196 if (LHSSigned) { 1197 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1198 return LHSType; 1199 } else if (!IsCompAssign) 1200 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1201 return RHSType; 1202 } else { 1203 // The signed type is higher-ranked than the unsigned type, 1204 // but isn't actually any bigger (like unsigned int and long 1205 // on most 32-bit systems). Use the unsigned type corresponding 1206 // to the signed type. 1207 QualType result = 1208 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1209 RHS = (*doRHSCast)(S, RHS.get(), result); 1210 if (!IsCompAssign) 1211 LHS = (*doLHSCast)(S, LHS.get(), result); 1212 return result; 1213 } 1214 } 1215 1216 /// \brief Handle conversions with GCC complex int extension. Helper function 1217 /// of UsualArithmeticConversions() 1218 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1219 ExprResult &RHS, QualType LHSType, 1220 QualType RHSType, 1221 bool IsCompAssign) { 1222 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1223 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1224 1225 if (LHSComplexInt && RHSComplexInt) { 1226 QualType LHSEltType = LHSComplexInt->getElementType(); 1227 QualType RHSEltType = RHSComplexInt->getElementType(); 1228 QualType ScalarType = 1229 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1230 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1231 1232 return S.Context.getComplexType(ScalarType); 1233 } 1234 1235 if (LHSComplexInt) { 1236 QualType LHSEltType = LHSComplexInt->getElementType(); 1237 QualType ScalarType = 1238 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1239 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1240 QualType ComplexType = S.Context.getComplexType(ScalarType); 1241 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1242 CK_IntegralRealToComplex); 1243 1244 return ComplexType; 1245 } 1246 1247 assert(RHSComplexInt); 1248 1249 QualType RHSEltType = RHSComplexInt->getElementType(); 1250 QualType ScalarType = 1251 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1252 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1253 QualType ComplexType = S.Context.getComplexType(ScalarType); 1254 1255 if (!IsCompAssign) 1256 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1257 CK_IntegralRealToComplex); 1258 return ComplexType; 1259 } 1260 1261 /// UsualArithmeticConversions - Performs various conversions that are common to 1262 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1263 /// routine returns the first non-arithmetic type found. The client is 1264 /// responsible for emitting appropriate error diagnostics. 1265 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1266 bool IsCompAssign) { 1267 if (!IsCompAssign) { 1268 LHS = UsualUnaryConversions(LHS.get()); 1269 if (LHS.isInvalid()) 1270 return QualType(); 1271 } 1272 1273 RHS = UsualUnaryConversions(RHS.get()); 1274 if (RHS.isInvalid()) 1275 return QualType(); 1276 1277 // For conversion purposes, we ignore any qualifiers. 1278 // For example, "const float" and "float" are equivalent. 1279 QualType LHSType = 1280 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1281 QualType RHSType = 1282 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1283 1284 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1285 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1286 LHSType = AtomicLHS->getValueType(); 1287 1288 // If both types are identical, no conversion is needed. 1289 if (LHSType == RHSType) 1290 return LHSType; 1291 1292 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1293 // The caller can deal with this (e.g. pointer + int). 1294 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1295 return QualType(); 1296 1297 // Apply unary and bitfield promotions to the LHS's type. 1298 QualType LHSUnpromotedType = LHSType; 1299 if (LHSType->isPromotableIntegerType()) 1300 LHSType = Context.getPromotedIntegerType(LHSType); 1301 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1302 if (!LHSBitfieldPromoteTy.isNull()) 1303 LHSType = LHSBitfieldPromoteTy; 1304 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1305 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1306 1307 // If both types are identical, no conversion is needed. 1308 if (LHSType == RHSType) 1309 return LHSType; 1310 1311 // At this point, we have two different arithmetic types. 1312 1313 // Handle complex types first (C99 6.3.1.8p1). 1314 if (LHSType->isComplexType() || RHSType->isComplexType()) 1315 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1316 IsCompAssign); 1317 1318 // Now handle "real" floating types (i.e. float, double, long double). 1319 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1320 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1321 IsCompAssign); 1322 1323 // Handle GCC complex int extension. 1324 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1325 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1326 IsCompAssign); 1327 1328 // Finally, we have two differing integer types. 1329 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1330 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1331 } 1332 1333 1334 //===----------------------------------------------------------------------===// 1335 // Semantic Analysis for various Expression Types 1336 //===----------------------------------------------------------------------===// 1337 1338 1339 ExprResult 1340 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1341 SourceLocation DefaultLoc, 1342 SourceLocation RParenLoc, 1343 Expr *ControllingExpr, 1344 ArrayRef<ParsedType> ArgTypes, 1345 ArrayRef<Expr *> ArgExprs) { 1346 unsigned NumAssocs = ArgTypes.size(); 1347 assert(NumAssocs == ArgExprs.size()); 1348 1349 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1350 for (unsigned i = 0; i < NumAssocs; ++i) { 1351 if (ArgTypes[i]) 1352 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1353 else 1354 Types[i] = nullptr; 1355 } 1356 1357 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1358 ControllingExpr, 1359 llvm::makeArrayRef(Types, NumAssocs), 1360 ArgExprs); 1361 delete [] Types; 1362 return ER; 1363 } 1364 1365 ExprResult 1366 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1367 SourceLocation DefaultLoc, 1368 SourceLocation RParenLoc, 1369 Expr *ControllingExpr, 1370 ArrayRef<TypeSourceInfo *> Types, 1371 ArrayRef<Expr *> Exprs) { 1372 unsigned NumAssocs = Types.size(); 1373 assert(NumAssocs == Exprs.size()); 1374 1375 // Decay and strip qualifiers for the controlling expression type, and handle 1376 // placeholder type replacement. See committee discussion from WG14 DR423. 1377 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1378 if (R.isInvalid()) 1379 return ExprError(); 1380 ControllingExpr = R.get(); 1381 1382 // The controlling expression is an unevaluated operand, so side effects are 1383 // likely unintended. 1384 if (ActiveTemplateInstantiations.empty() && 1385 ControllingExpr->HasSideEffects(Context, false)) 1386 Diag(ControllingExpr->getExprLoc(), 1387 diag::warn_side_effects_unevaluated_context); 1388 1389 bool TypeErrorFound = false, 1390 IsResultDependent = ControllingExpr->isTypeDependent(), 1391 ContainsUnexpandedParameterPack 1392 = ControllingExpr->containsUnexpandedParameterPack(); 1393 1394 for (unsigned i = 0; i < NumAssocs; ++i) { 1395 if (Exprs[i]->containsUnexpandedParameterPack()) 1396 ContainsUnexpandedParameterPack = true; 1397 1398 if (Types[i]) { 1399 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1400 ContainsUnexpandedParameterPack = true; 1401 1402 if (Types[i]->getType()->isDependentType()) { 1403 IsResultDependent = true; 1404 } else { 1405 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1406 // complete object type other than a variably modified type." 1407 unsigned D = 0; 1408 if (Types[i]->getType()->isIncompleteType()) 1409 D = diag::err_assoc_type_incomplete; 1410 else if (!Types[i]->getType()->isObjectType()) 1411 D = diag::err_assoc_type_nonobject; 1412 else if (Types[i]->getType()->isVariablyModifiedType()) 1413 D = diag::err_assoc_type_variably_modified; 1414 1415 if (D != 0) { 1416 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1417 << Types[i]->getTypeLoc().getSourceRange() 1418 << Types[i]->getType(); 1419 TypeErrorFound = true; 1420 } 1421 1422 // C11 6.5.1.1p2 "No two generic associations in the same generic 1423 // selection shall specify compatible types." 1424 for (unsigned j = i+1; j < NumAssocs; ++j) 1425 if (Types[j] && !Types[j]->getType()->isDependentType() && 1426 Context.typesAreCompatible(Types[i]->getType(), 1427 Types[j]->getType())) { 1428 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1429 diag::err_assoc_compatible_types) 1430 << Types[j]->getTypeLoc().getSourceRange() 1431 << Types[j]->getType() 1432 << Types[i]->getType(); 1433 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1434 diag::note_compat_assoc) 1435 << Types[i]->getTypeLoc().getSourceRange() 1436 << Types[i]->getType(); 1437 TypeErrorFound = true; 1438 } 1439 } 1440 } 1441 } 1442 if (TypeErrorFound) 1443 return ExprError(); 1444 1445 // If we determined that the generic selection is result-dependent, don't 1446 // try to compute the result expression. 1447 if (IsResultDependent) 1448 return new (Context) GenericSelectionExpr( 1449 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1450 ContainsUnexpandedParameterPack); 1451 1452 SmallVector<unsigned, 1> CompatIndices; 1453 unsigned DefaultIndex = -1U; 1454 for (unsigned i = 0; i < NumAssocs; ++i) { 1455 if (!Types[i]) 1456 DefaultIndex = i; 1457 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1458 Types[i]->getType())) 1459 CompatIndices.push_back(i); 1460 } 1461 1462 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1463 // type compatible with at most one of the types named in its generic 1464 // association list." 1465 if (CompatIndices.size() > 1) { 1466 // We strip parens here because the controlling expression is typically 1467 // parenthesized in macro definitions. 1468 ControllingExpr = ControllingExpr->IgnoreParens(); 1469 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1470 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1471 << (unsigned) CompatIndices.size(); 1472 for (unsigned I : CompatIndices) { 1473 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1474 diag::note_compat_assoc) 1475 << Types[I]->getTypeLoc().getSourceRange() 1476 << Types[I]->getType(); 1477 } 1478 return ExprError(); 1479 } 1480 1481 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1482 // its controlling expression shall have type compatible with exactly one of 1483 // the types named in its generic association list." 1484 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1485 // We strip parens here because the controlling expression is typically 1486 // parenthesized in macro definitions. 1487 ControllingExpr = ControllingExpr->IgnoreParens(); 1488 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1489 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1490 return ExprError(); 1491 } 1492 1493 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1494 // type name that is compatible with the type of the controlling expression, 1495 // then the result expression of the generic selection is the expression 1496 // in that generic association. Otherwise, the result expression of the 1497 // generic selection is the expression in the default generic association." 1498 unsigned ResultIndex = 1499 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1500 1501 return new (Context) GenericSelectionExpr( 1502 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1503 ContainsUnexpandedParameterPack, ResultIndex); 1504 } 1505 1506 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1507 /// location of the token and the offset of the ud-suffix within it. 1508 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1509 unsigned Offset) { 1510 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1511 S.getLangOpts()); 1512 } 1513 1514 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1515 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1516 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1517 IdentifierInfo *UDSuffix, 1518 SourceLocation UDSuffixLoc, 1519 ArrayRef<Expr*> Args, 1520 SourceLocation LitEndLoc) { 1521 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1522 1523 QualType ArgTy[2]; 1524 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1525 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1526 if (ArgTy[ArgIdx]->isArrayType()) 1527 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1528 } 1529 1530 DeclarationName OpName = 1531 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1532 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1533 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1534 1535 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1536 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1537 /*AllowRaw*/false, /*AllowTemplate*/false, 1538 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1539 return ExprError(); 1540 1541 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1542 } 1543 1544 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1545 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1546 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1547 /// multiple tokens. However, the common case is that StringToks points to one 1548 /// string. 1549 /// 1550 ExprResult 1551 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1552 assert(!StringToks.empty() && "Must have at least one string!"); 1553 1554 StringLiteralParser Literal(StringToks, PP); 1555 if (Literal.hadError) 1556 return ExprError(); 1557 1558 SmallVector<SourceLocation, 4> StringTokLocs; 1559 for (const Token &Tok : StringToks) 1560 StringTokLocs.push_back(Tok.getLocation()); 1561 1562 QualType CharTy = Context.CharTy; 1563 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1564 if (Literal.isWide()) { 1565 CharTy = Context.getWideCharType(); 1566 Kind = StringLiteral::Wide; 1567 } else if (Literal.isUTF8()) { 1568 Kind = StringLiteral::UTF8; 1569 } else if (Literal.isUTF16()) { 1570 CharTy = Context.Char16Ty; 1571 Kind = StringLiteral::UTF16; 1572 } else if (Literal.isUTF32()) { 1573 CharTy = Context.Char32Ty; 1574 Kind = StringLiteral::UTF32; 1575 } else if (Literal.isPascal()) { 1576 CharTy = Context.UnsignedCharTy; 1577 } 1578 1579 QualType CharTyConst = CharTy; 1580 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1581 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1582 CharTyConst.addConst(); 1583 1584 // Get an array type for the string, according to C99 6.4.5. This includes 1585 // the nul terminator character as well as the string length for pascal 1586 // strings. 1587 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1588 llvm::APInt(32, Literal.GetNumStringChars()+1), 1589 ArrayType::Normal, 0); 1590 1591 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1592 if (getLangOpts().OpenCL) { 1593 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1594 } 1595 1596 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1597 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1598 Kind, Literal.Pascal, StrTy, 1599 &StringTokLocs[0], 1600 StringTokLocs.size()); 1601 if (Literal.getUDSuffix().empty()) 1602 return Lit; 1603 1604 // We're building a user-defined literal. 1605 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1606 SourceLocation UDSuffixLoc = 1607 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1608 Literal.getUDSuffixOffset()); 1609 1610 // Make sure we're allowed user-defined literals here. 1611 if (!UDLScope) 1612 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1613 1614 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1615 // operator "" X (str, len) 1616 QualType SizeType = Context.getSizeType(); 1617 1618 DeclarationName OpName = 1619 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1620 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1621 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1622 1623 QualType ArgTy[] = { 1624 Context.getArrayDecayedType(StrTy), SizeType 1625 }; 1626 1627 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1628 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1629 /*AllowRaw*/false, /*AllowTemplate*/false, 1630 /*AllowStringTemplate*/true)) { 1631 1632 case LOLR_Cooked: { 1633 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1634 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1635 StringTokLocs[0]); 1636 Expr *Args[] = { Lit, LenArg }; 1637 1638 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1639 } 1640 1641 case LOLR_StringTemplate: { 1642 TemplateArgumentListInfo ExplicitArgs; 1643 1644 unsigned CharBits = Context.getIntWidth(CharTy); 1645 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1646 llvm::APSInt Value(CharBits, CharIsUnsigned); 1647 1648 TemplateArgument TypeArg(CharTy); 1649 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1650 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1651 1652 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1653 Value = Lit->getCodeUnit(I); 1654 TemplateArgument Arg(Context, Value, CharTy); 1655 TemplateArgumentLocInfo ArgInfo; 1656 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1657 } 1658 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1659 &ExplicitArgs); 1660 } 1661 case LOLR_Raw: 1662 case LOLR_Template: 1663 llvm_unreachable("unexpected literal operator lookup result"); 1664 case LOLR_Error: 1665 return ExprError(); 1666 } 1667 llvm_unreachable("unexpected literal operator lookup result"); 1668 } 1669 1670 ExprResult 1671 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1672 SourceLocation Loc, 1673 const CXXScopeSpec *SS) { 1674 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1675 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1676 } 1677 1678 /// BuildDeclRefExpr - Build an expression that references a 1679 /// declaration that does not require a closure capture. 1680 ExprResult 1681 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1682 const DeclarationNameInfo &NameInfo, 1683 const CXXScopeSpec *SS, NamedDecl *FoundD, 1684 const TemplateArgumentListInfo *TemplateArgs) { 1685 if (getLangOpts().CUDA) 1686 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1687 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1688 if (CheckCUDATarget(Caller, Callee)) { 1689 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1690 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1691 << IdentifyCUDATarget(Caller); 1692 Diag(D->getLocation(), diag::note_previous_decl) 1693 << D->getIdentifier(); 1694 return ExprError(); 1695 } 1696 } 1697 1698 bool RefersToCapturedVariable = 1699 isa<VarDecl>(D) && 1700 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1701 1702 DeclRefExpr *E; 1703 if (isa<VarTemplateSpecializationDecl>(D)) { 1704 VarTemplateSpecializationDecl *VarSpec = 1705 cast<VarTemplateSpecializationDecl>(D); 1706 1707 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1708 : NestedNameSpecifierLoc(), 1709 VarSpec->getTemplateKeywordLoc(), D, 1710 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1711 FoundD, TemplateArgs); 1712 } else { 1713 assert(!TemplateArgs && "No template arguments for non-variable" 1714 " template specialization references"); 1715 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1716 : NestedNameSpecifierLoc(), 1717 SourceLocation(), D, RefersToCapturedVariable, 1718 NameInfo, Ty, VK, FoundD); 1719 } 1720 1721 MarkDeclRefReferenced(E); 1722 1723 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1724 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1725 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1726 recordUseOfEvaluatedWeak(E); 1727 1728 // Just in case we're building an illegal pointer-to-member. 1729 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1730 if (FD && FD->isBitField()) 1731 E->setObjectKind(OK_BitField); 1732 1733 return E; 1734 } 1735 1736 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1737 /// possibly a list of template arguments. 1738 /// 1739 /// If this produces template arguments, it is permitted to call 1740 /// DecomposeTemplateName. 1741 /// 1742 /// This actually loses a lot of source location information for 1743 /// non-standard name kinds; we should consider preserving that in 1744 /// some way. 1745 void 1746 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1747 TemplateArgumentListInfo &Buffer, 1748 DeclarationNameInfo &NameInfo, 1749 const TemplateArgumentListInfo *&TemplateArgs) { 1750 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1751 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1752 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1753 1754 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1755 Id.TemplateId->NumArgs); 1756 translateTemplateArguments(TemplateArgsPtr, Buffer); 1757 1758 TemplateName TName = Id.TemplateId->Template.get(); 1759 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1760 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1761 TemplateArgs = &Buffer; 1762 } else { 1763 NameInfo = GetNameFromUnqualifiedId(Id); 1764 TemplateArgs = nullptr; 1765 } 1766 } 1767 1768 static void emitEmptyLookupTypoDiagnostic( 1769 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1770 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1771 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1772 DeclContext *Ctx = 1773 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1774 if (!TC) { 1775 // Emit a special diagnostic for failed member lookups. 1776 // FIXME: computing the declaration context might fail here (?) 1777 if (Ctx) 1778 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1779 << SS.getRange(); 1780 else 1781 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1782 return; 1783 } 1784 1785 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1786 bool DroppedSpecifier = 1787 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1788 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1789 ? diag::note_implicit_param_decl 1790 : diag::note_previous_decl; 1791 if (!Ctx) 1792 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1793 SemaRef.PDiag(NoteID)); 1794 else 1795 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1796 << Typo << Ctx << DroppedSpecifier 1797 << SS.getRange(), 1798 SemaRef.PDiag(NoteID)); 1799 } 1800 1801 /// Diagnose an empty lookup. 1802 /// 1803 /// \return false if new lookup candidates were found 1804 bool 1805 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1806 std::unique_ptr<CorrectionCandidateCallback> CCC, 1807 TemplateArgumentListInfo *ExplicitTemplateArgs, 1808 ArrayRef<Expr *> Args, TypoExpr **Out) { 1809 DeclarationName Name = R.getLookupName(); 1810 1811 unsigned diagnostic = diag::err_undeclared_var_use; 1812 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1813 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1814 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1815 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1816 diagnostic = diag::err_undeclared_use; 1817 diagnostic_suggest = diag::err_undeclared_use_suggest; 1818 } 1819 1820 // If the original lookup was an unqualified lookup, fake an 1821 // unqualified lookup. This is useful when (for example) the 1822 // original lookup would not have found something because it was a 1823 // dependent name. 1824 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1825 while (DC) { 1826 if (isa<CXXRecordDecl>(DC)) { 1827 LookupQualifiedName(R, DC); 1828 1829 if (!R.empty()) { 1830 // Don't give errors about ambiguities in this lookup. 1831 R.suppressDiagnostics(); 1832 1833 // During a default argument instantiation the CurContext points 1834 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1835 // function parameter list, hence add an explicit check. 1836 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1837 ActiveTemplateInstantiations.back().Kind == 1838 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1839 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1840 bool isInstance = CurMethod && 1841 CurMethod->isInstance() && 1842 DC == CurMethod->getParent() && !isDefaultArgument; 1843 1844 // Give a code modification hint to insert 'this->'. 1845 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1846 // Actually quite difficult! 1847 if (getLangOpts().MSVCCompat) 1848 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1849 if (isInstance) { 1850 Diag(R.getNameLoc(), diagnostic) << Name 1851 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1852 CheckCXXThisCapture(R.getNameLoc()); 1853 } else { 1854 Diag(R.getNameLoc(), diagnostic) << Name; 1855 } 1856 1857 // Do we really want to note all of these? 1858 for (NamedDecl *D : R) 1859 Diag(D->getLocation(), diag::note_dependent_var_use); 1860 1861 // Return true if we are inside a default argument instantiation 1862 // and the found name refers to an instance member function, otherwise 1863 // the function calling DiagnoseEmptyLookup will try to create an 1864 // implicit member call and this is wrong for default argument. 1865 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1866 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1867 return true; 1868 } 1869 1870 // Tell the callee to try to recover. 1871 return false; 1872 } 1873 1874 R.clear(); 1875 } 1876 1877 // In Microsoft mode, if we are performing lookup from within a friend 1878 // function definition declared at class scope then we must set 1879 // DC to the lexical parent to be able to search into the parent 1880 // class. 1881 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1882 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1883 DC->getLexicalParent()->isRecord()) 1884 DC = DC->getLexicalParent(); 1885 else 1886 DC = DC->getParent(); 1887 } 1888 1889 // We didn't find anything, so try to correct for a typo. 1890 TypoCorrection Corrected; 1891 if (S && Out) { 1892 SourceLocation TypoLoc = R.getNameLoc(); 1893 assert(!ExplicitTemplateArgs && 1894 "Diagnosing an empty lookup with explicit template args!"); 1895 *Out = CorrectTypoDelayed( 1896 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1897 [=](const TypoCorrection &TC) { 1898 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1899 diagnostic, diagnostic_suggest); 1900 }, 1901 nullptr, CTK_ErrorRecovery); 1902 if (*Out) 1903 return true; 1904 } else if (S && (Corrected = 1905 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1906 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1907 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1908 bool DroppedSpecifier = 1909 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1910 R.setLookupName(Corrected.getCorrection()); 1911 1912 bool AcceptableWithRecovery = false; 1913 bool AcceptableWithoutRecovery = false; 1914 NamedDecl *ND = Corrected.getFoundDecl(); 1915 if (ND) { 1916 if (Corrected.isOverloaded()) { 1917 OverloadCandidateSet OCS(R.getNameLoc(), 1918 OverloadCandidateSet::CSK_Normal); 1919 OverloadCandidateSet::iterator Best; 1920 for (NamedDecl *CD : Corrected) { 1921 if (FunctionTemplateDecl *FTD = 1922 dyn_cast<FunctionTemplateDecl>(CD)) 1923 AddTemplateOverloadCandidate( 1924 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1925 Args, OCS); 1926 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1927 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1928 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1929 Args, OCS); 1930 } 1931 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1932 case OR_Success: 1933 ND = Best->FoundDecl; 1934 Corrected.setCorrectionDecl(ND); 1935 break; 1936 default: 1937 // FIXME: Arbitrarily pick the first declaration for the note. 1938 Corrected.setCorrectionDecl(ND); 1939 break; 1940 } 1941 } 1942 R.addDecl(ND); 1943 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1944 CXXRecordDecl *Record = nullptr; 1945 if (Corrected.getCorrectionSpecifier()) { 1946 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1947 Record = Ty->getAsCXXRecordDecl(); 1948 } 1949 if (!Record) 1950 Record = cast<CXXRecordDecl>( 1951 ND->getDeclContext()->getRedeclContext()); 1952 R.setNamingClass(Record); 1953 } 1954 1955 auto *UnderlyingND = ND->getUnderlyingDecl(); 1956 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1957 isa<FunctionTemplateDecl>(UnderlyingND); 1958 // FIXME: If we ended up with a typo for a type name or 1959 // Objective-C class name, we're in trouble because the parser 1960 // is in the wrong place to recover. Suggest the typo 1961 // correction, but don't make it a fix-it since we're not going 1962 // to recover well anyway. 1963 AcceptableWithoutRecovery = 1964 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1965 } else { 1966 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1967 // because we aren't able to recover. 1968 AcceptableWithoutRecovery = true; 1969 } 1970 1971 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1972 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1973 ? diag::note_implicit_param_decl 1974 : diag::note_previous_decl; 1975 if (SS.isEmpty()) 1976 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1977 PDiag(NoteID), AcceptableWithRecovery); 1978 else 1979 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1980 << Name << computeDeclContext(SS, false) 1981 << DroppedSpecifier << SS.getRange(), 1982 PDiag(NoteID), AcceptableWithRecovery); 1983 1984 // Tell the callee whether to try to recover. 1985 return !AcceptableWithRecovery; 1986 } 1987 } 1988 R.clear(); 1989 1990 // Emit a special diagnostic for failed member lookups. 1991 // FIXME: computing the declaration context might fail here (?) 1992 if (!SS.isEmpty()) { 1993 Diag(R.getNameLoc(), diag::err_no_member) 1994 << Name << computeDeclContext(SS, false) 1995 << SS.getRange(); 1996 return true; 1997 } 1998 1999 // Give up, we can't recover. 2000 Diag(R.getNameLoc(), diagnostic) << Name; 2001 return true; 2002 } 2003 2004 /// In Microsoft mode, if we are inside a template class whose parent class has 2005 /// dependent base classes, and we can't resolve an unqualified identifier, then 2006 /// assume the identifier is a member of a dependent base class. We can only 2007 /// recover successfully in static methods, instance methods, and other contexts 2008 /// where 'this' is available. This doesn't precisely match MSVC's 2009 /// instantiation model, but it's close enough. 2010 static Expr * 2011 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2012 DeclarationNameInfo &NameInfo, 2013 SourceLocation TemplateKWLoc, 2014 const TemplateArgumentListInfo *TemplateArgs) { 2015 // Only try to recover from lookup into dependent bases in static methods or 2016 // contexts where 'this' is available. 2017 QualType ThisType = S.getCurrentThisType(); 2018 const CXXRecordDecl *RD = nullptr; 2019 if (!ThisType.isNull()) 2020 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2021 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2022 RD = MD->getParent(); 2023 if (!RD || !RD->hasAnyDependentBases()) 2024 return nullptr; 2025 2026 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2027 // is available, suggest inserting 'this->' as a fixit. 2028 SourceLocation Loc = NameInfo.getLoc(); 2029 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2030 DB << NameInfo.getName() << RD; 2031 2032 if (!ThisType.isNull()) { 2033 DB << FixItHint::CreateInsertion(Loc, "this->"); 2034 return CXXDependentScopeMemberExpr::Create( 2035 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2036 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2037 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2038 } 2039 2040 // Synthesize a fake NNS that points to the derived class. This will 2041 // perform name lookup during template instantiation. 2042 CXXScopeSpec SS; 2043 auto *NNS = 2044 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2045 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2046 return DependentScopeDeclRefExpr::Create( 2047 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2048 TemplateArgs); 2049 } 2050 2051 ExprResult 2052 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2053 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2054 bool HasTrailingLParen, bool IsAddressOfOperand, 2055 std::unique_ptr<CorrectionCandidateCallback> CCC, 2056 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2057 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2058 "cannot be direct & operand and have a trailing lparen"); 2059 if (SS.isInvalid()) 2060 return ExprError(); 2061 2062 TemplateArgumentListInfo TemplateArgsBuffer; 2063 2064 // Decompose the UnqualifiedId into the following data. 2065 DeclarationNameInfo NameInfo; 2066 const TemplateArgumentListInfo *TemplateArgs; 2067 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2068 2069 DeclarationName Name = NameInfo.getName(); 2070 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2071 SourceLocation NameLoc = NameInfo.getLoc(); 2072 2073 // C++ [temp.dep.expr]p3: 2074 // An id-expression is type-dependent if it contains: 2075 // -- an identifier that was declared with a dependent type, 2076 // (note: handled after lookup) 2077 // -- a template-id that is dependent, 2078 // (note: handled in BuildTemplateIdExpr) 2079 // -- a conversion-function-id that specifies a dependent type, 2080 // -- a nested-name-specifier that contains a class-name that 2081 // names a dependent type. 2082 // Determine whether this is a member of an unknown specialization; 2083 // we need to handle these differently. 2084 bool DependentID = false; 2085 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2086 Name.getCXXNameType()->isDependentType()) { 2087 DependentID = true; 2088 } else if (SS.isSet()) { 2089 if (DeclContext *DC = computeDeclContext(SS, false)) { 2090 if (RequireCompleteDeclContext(SS, DC)) 2091 return ExprError(); 2092 } else { 2093 DependentID = true; 2094 } 2095 } 2096 2097 if (DependentID) 2098 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2099 IsAddressOfOperand, TemplateArgs); 2100 2101 // Perform the required lookup. 2102 LookupResult R(*this, NameInfo, 2103 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2104 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2105 if (TemplateArgs) { 2106 // Lookup the template name again to correctly establish the context in 2107 // which it was found. This is really unfortunate as we already did the 2108 // lookup to determine that it was a template name in the first place. If 2109 // this becomes a performance hit, we can work harder to preserve those 2110 // results until we get here but it's likely not worth it. 2111 bool MemberOfUnknownSpecialization; 2112 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2113 MemberOfUnknownSpecialization); 2114 2115 if (MemberOfUnknownSpecialization || 2116 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2117 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2118 IsAddressOfOperand, TemplateArgs); 2119 } else { 2120 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2121 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2122 2123 // If the result might be in a dependent base class, this is a dependent 2124 // id-expression. 2125 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2126 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2127 IsAddressOfOperand, TemplateArgs); 2128 2129 // If this reference is in an Objective-C method, then we need to do 2130 // some special Objective-C lookup, too. 2131 if (IvarLookupFollowUp) { 2132 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2133 if (E.isInvalid()) 2134 return ExprError(); 2135 2136 if (Expr *Ex = E.getAs<Expr>()) 2137 return Ex; 2138 } 2139 } 2140 2141 if (R.isAmbiguous()) 2142 return ExprError(); 2143 2144 // This could be an implicitly declared function reference (legal in C90, 2145 // extension in C99, forbidden in C++). 2146 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2147 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2148 if (D) R.addDecl(D); 2149 } 2150 2151 // Determine whether this name might be a candidate for 2152 // argument-dependent lookup. 2153 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2154 2155 if (R.empty() && !ADL) { 2156 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2157 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2158 TemplateKWLoc, TemplateArgs)) 2159 return E; 2160 } 2161 2162 // Don't diagnose an empty lookup for inline assembly. 2163 if (IsInlineAsmIdentifier) 2164 return ExprError(); 2165 2166 // If this name wasn't predeclared and if this is not a function 2167 // call, diagnose the problem. 2168 TypoExpr *TE = nullptr; 2169 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2170 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2171 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2172 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2173 "Typo correction callback misconfigured"); 2174 if (CCC) { 2175 // Make sure the callback knows what the typo being diagnosed is. 2176 CCC->setTypoName(II); 2177 if (SS.isValid()) 2178 CCC->setTypoNNS(SS.getScopeRep()); 2179 } 2180 if (DiagnoseEmptyLookup(S, SS, R, 2181 CCC ? std::move(CCC) : std::move(DefaultValidator), 2182 nullptr, None, &TE)) { 2183 if (TE && KeywordReplacement) { 2184 auto &State = getTypoExprState(TE); 2185 auto BestTC = State.Consumer->getNextCorrection(); 2186 if (BestTC.isKeyword()) { 2187 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2188 if (State.DiagHandler) 2189 State.DiagHandler(BestTC); 2190 KeywordReplacement->startToken(); 2191 KeywordReplacement->setKind(II->getTokenID()); 2192 KeywordReplacement->setIdentifierInfo(II); 2193 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2194 // Clean up the state associated with the TypoExpr, since it has 2195 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2196 clearDelayedTypo(TE); 2197 // Signal that a correction to a keyword was performed by returning a 2198 // valid-but-null ExprResult. 2199 return (Expr*)nullptr; 2200 } 2201 State.Consumer->resetCorrectionStream(); 2202 } 2203 return TE ? TE : ExprError(); 2204 } 2205 2206 assert(!R.empty() && 2207 "DiagnoseEmptyLookup returned false but added no results"); 2208 2209 // If we found an Objective-C instance variable, let 2210 // LookupInObjCMethod build the appropriate expression to 2211 // reference the ivar. 2212 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2213 R.clear(); 2214 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2215 // In a hopelessly buggy code, Objective-C instance variable 2216 // lookup fails and no expression will be built to reference it. 2217 if (!E.isInvalid() && !E.get()) 2218 return ExprError(); 2219 return E; 2220 } 2221 } 2222 2223 // This is guaranteed from this point on. 2224 assert(!R.empty() || ADL); 2225 2226 // Check whether this might be a C++ implicit instance member access. 2227 // C++ [class.mfct.non-static]p3: 2228 // When an id-expression that is not part of a class member access 2229 // syntax and not used to form a pointer to member is used in the 2230 // body of a non-static member function of class X, if name lookup 2231 // resolves the name in the id-expression to a non-static non-type 2232 // member of some class C, the id-expression is transformed into a 2233 // class member access expression using (*this) as the 2234 // postfix-expression to the left of the . operator. 2235 // 2236 // But we don't actually need to do this for '&' operands if R 2237 // resolved to a function or overloaded function set, because the 2238 // expression is ill-formed if it actually works out to be a 2239 // non-static member function: 2240 // 2241 // C++ [expr.ref]p4: 2242 // Otherwise, if E1.E2 refers to a non-static member function. . . 2243 // [t]he expression can be used only as the left-hand operand of a 2244 // member function call. 2245 // 2246 // There are other safeguards against such uses, but it's important 2247 // to get this right here so that we don't end up making a 2248 // spuriously dependent expression if we're inside a dependent 2249 // instance method. 2250 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2251 bool MightBeImplicitMember; 2252 if (!IsAddressOfOperand) 2253 MightBeImplicitMember = true; 2254 else if (!SS.isEmpty()) 2255 MightBeImplicitMember = false; 2256 else if (R.isOverloadedResult()) 2257 MightBeImplicitMember = false; 2258 else if (R.isUnresolvableResult()) 2259 MightBeImplicitMember = true; 2260 else 2261 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2262 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2263 isa<MSPropertyDecl>(R.getFoundDecl()); 2264 2265 if (MightBeImplicitMember) 2266 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2267 R, TemplateArgs, S); 2268 } 2269 2270 if (TemplateArgs || TemplateKWLoc.isValid()) { 2271 2272 // In C++1y, if this is a variable template id, then check it 2273 // in BuildTemplateIdExpr(). 2274 // The single lookup result must be a variable template declaration. 2275 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2276 Id.TemplateId->Kind == TNK_Var_template) { 2277 assert(R.getAsSingle<VarTemplateDecl>() && 2278 "There should only be one declaration found."); 2279 } 2280 2281 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2282 } 2283 2284 return BuildDeclarationNameExpr(SS, R, ADL); 2285 } 2286 2287 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2288 /// declaration name, generally during template instantiation. 2289 /// There's a large number of things which don't need to be done along 2290 /// this path. 2291 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2292 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2293 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2294 DeclContext *DC = computeDeclContext(SS, false); 2295 if (!DC) 2296 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2297 NameInfo, /*TemplateArgs=*/nullptr); 2298 2299 if (RequireCompleteDeclContext(SS, DC)) 2300 return ExprError(); 2301 2302 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2303 LookupQualifiedName(R, DC); 2304 2305 if (R.isAmbiguous()) 2306 return ExprError(); 2307 2308 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2309 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2310 NameInfo, /*TemplateArgs=*/nullptr); 2311 2312 if (R.empty()) { 2313 Diag(NameInfo.getLoc(), diag::err_no_member) 2314 << NameInfo.getName() << DC << SS.getRange(); 2315 return ExprError(); 2316 } 2317 2318 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2319 // Diagnose a missing typename if this resolved unambiguously to a type in 2320 // a dependent context. If we can recover with a type, downgrade this to 2321 // a warning in Microsoft compatibility mode. 2322 unsigned DiagID = diag::err_typename_missing; 2323 if (RecoveryTSI && getLangOpts().MSVCCompat) 2324 DiagID = diag::ext_typename_missing; 2325 SourceLocation Loc = SS.getBeginLoc(); 2326 auto D = Diag(Loc, DiagID); 2327 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2328 << SourceRange(Loc, NameInfo.getEndLoc()); 2329 2330 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2331 // context. 2332 if (!RecoveryTSI) 2333 return ExprError(); 2334 2335 // Only issue the fixit if we're prepared to recover. 2336 D << FixItHint::CreateInsertion(Loc, "typename "); 2337 2338 // Recover by pretending this was an elaborated type. 2339 QualType Ty = Context.getTypeDeclType(TD); 2340 TypeLocBuilder TLB; 2341 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2342 2343 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2344 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2345 QTL.setElaboratedKeywordLoc(SourceLocation()); 2346 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2347 2348 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2349 2350 return ExprEmpty(); 2351 } 2352 2353 // Defend against this resolving to an implicit member access. We usually 2354 // won't get here if this might be a legitimate a class member (we end up in 2355 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2356 // a pointer-to-member or in an unevaluated context in C++11. 2357 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2358 return BuildPossibleImplicitMemberExpr(SS, 2359 /*TemplateKWLoc=*/SourceLocation(), 2360 R, /*TemplateArgs=*/nullptr, S); 2361 2362 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2363 } 2364 2365 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2366 /// detected that we're currently inside an ObjC method. Perform some 2367 /// additional lookup. 2368 /// 2369 /// Ideally, most of this would be done by lookup, but there's 2370 /// actually quite a lot of extra work involved. 2371 /// 2372 /// Returns a null sentinel to indicate trivial success. 2373 ExprResult 2374 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2375 IdentifierInfo *II, bool AllowBuiltinCreation) { 2376 SourceLocation Loc = Lookup.getNameLoc(); 2377 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2378 2379 // Check for error condition which is already reported. 2380 if (!CurMethod) 2381 return ExprError(); 2382 2383 // There are two cases to handle here. 1) scoped lookup could have failed, 2384 // in which case we should look for an ivar. 2) scoped lookup could have 2385 // found a decl, but that decl is outside the current instance method (i.e. 2386 // a global variable). In these two cases, we do a lookup for an ivar with 2387 // this name, if the lookup sucedes, we replace it our current decl. 2388 2389 // If we're in a class method, we don't normally want to look for 2390 // ivars. But if we don't find anything else, and there's an 2391 // ivar, that's an error. 2392 bool IsClassMethod = CurMethod->isClassMethod(); 2393 2394 bool LookForIvars; 2395 if (Lookup.empty()) 2396 LookForIvars = true; 2397 else if (IsClassMethod) 2398 LookForIvars = false; 2399 else 2400 LookForIvars = (Lookup.isSingleResult() && 2401 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2402 ObjCInterfaceDecl *IFace = nullptr; 2403 if (LookForIvars) { 2404 IFace = CurMethod->getClassInterface(); 2405 ObjCInterfaceDecl *ClassDeclared; 2406 ObjCIvarDecl *IV = nullptr; 2407 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2408 // Diagnose using an ivar in a class method. 2409 if (IsClassMethod) 2410 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2411 << IV->getDeclName()); 2412 2413 // If we're referencing an invalid decl, just return this as a silent 2414 // error node. The error diagnostic was already emitted on the decl. 2415 if (IV->isInvalidDecl()) 2416 return ExprError(); 2417 2418 // Check if referencing a field with __attribute__((deprecated)). 2419 if (DiagnoseUseOfDecl(IV, Loc)) 2420 return ExprError(); 2421 2422 // Diagnose the use of an ivar outside of the declaring class. 2423 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2424 !declaresSameEntity(ClassDeclared, IFace) && 2425 !getLangOpts().DebuggerSupport) 2426 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2427 2428 // FIXME: This should use a new expr for a direct reference, don't 2429 // turn this into Self->ivar, just return a BareIVarExpr or something. 2430 IdentifierInfo &II = Context.Idents.get("self"); 2431 UnqualifiedId SelfName; 2432 SelfName.setIdentifier(&II, SourceLocation()); 2433 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2434 CXXScopeSpec SelfScopeSpec; 2435 SourceLocation TemplateKWLoc; 2436 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2437 SelfName, false, false); 2438 if (SelfExpr.isInvalid()) 2439 return ExprError(); 2440 2441 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2442 if (SelfExpr.isInvalid()) 2443 return ExprError(); 2444 2445 MarkAnyDeclReferenced(Loc, IV, true); 2446 2447 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2448 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2449 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2450 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2451 2452 ObjCIvarRefExpr *Result = new (Context) 2453 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2454 IV->getLocation(), SelfExpr.get(), true, true); 2455 2456 if (getLangOpts().ObjCAutoRefCount) { 2457 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2458 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2459 recordUseOfEvaluatedWeak(Result); 2460 } 2461 if (CurContext->isClosure()) 2462 Diag(Loc, diag::warn_implicitly_retains_self) 2463 << FixItHint::CreateInsertion(Loc, "self->"); 2464 } 2465 2466 return Result; 2467 } 2468 } else if (CurMethod->isInstanceMethod()) { 2469 // We should warn if a local variable hides an ivar. 2470 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2471 ObjCInterfaceDecl *ClassDeclared; 2472 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2473 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2474 declaresSameEntity(IFace, ClassDeclared)) 2475 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2476 } 2477 } 2478 } else if (Lookup.isSingleResult() && 2479 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2480 // If accessing a stand-alone ivar in a class method, this is an error. 2481 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2482 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2483 << IV->getDeclName()); 2484 } 2485 2486 if (Lookup.empty() && II && AllowBuiltinCreation) { 2487 // FIXME. Consolidate this with similar code in LookupName. 2488 if (unsigned BuiltinID = II->getBuiltinID()) { 2489 if (!(getLangOpts().CPlusPlus && 2490 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2491 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2492 S, Lookup.isForRedeclaration(), 2493 Lookup.getNameLoc()); 2494 if (D) Lookup.addDecl(D); 2495 } 2496 } 2497 } 2498 // Sentinel value saying that we didn't do anything special. 2499 return ExprResult((Expr *)nullptr); 2500 } 2501 2502 /// \brief Cast a base object to a member's actual type. 2503 /// 2504 /// Logically this happens in three phases: 2505 /// 2506 /// * First we cast from the base type to the naming class. 2507 /// The naming class is the class into which we were looking 2508 /// when we found the member; it's the qualifier type if a 2509 /// qualifier was provided, and otherwise it's the base type. 2510 /// 2511 /// * Next we cast from the naming class to the declaring class. 2512 /// If the member we found was brought into a class's scope by 2513 /// a using declaration, this is that class; otherwise it's 2514 /// the class declaring the member. 2515 /// 2516 /// * Finally we cast from the declaring class to the "true" 2517 /// declaring class of the member. This conversion does not 2518 /// obey access control. 2519 ExprResult 2520 Sema::PerformObjectMemberConversion(Expr *From, 2521 NestedNameSpecifier *Qualifier, 2522 NamedDecl *FoundDecl, 2523 NamedDecl *Member) { 2524 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2525 if (!RD) 2526 return From; 2527 2528 QualType DestRecordType; 2529 QualType DestType; 2530 QualType FromRecordType; 2531 QualType FromType = From->getType(); 2532 bool PointerConversions = false; 2533 if (isa<FieldDecl>(Member)) { 2534 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2535 2536 if (FromType->getAs<PointerType>()) { 2537 DestType = Context.getPointerType(DestRecordType); 2538 FromRecordType = FromType->getPointeeType(); 2539 PointerConversions = true; 2540 } else { 2541 DestType = DestRecordType; 2542 FromRecordType = FromType; 2543 } 2544 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2545 if (Method->isStatic()) 2546 return From; 2547 2548 DestType = Method->getThisType(Context); 2549 DestRecordType = DestType->getPointeeType(); 2550 2551 if (FromType->getAs<PointerType>()) { 2552 FromRecordType = FromType->getPointeeType(); 2553 PointerConversions = true; 2554 } else { 2555 FromRecordType = FromType; 2556 DestType = DestRecordType; 2557 } 2558 } else { 2559 // No conversion necessary. 2560 return From; 2561 } 2562 2563 if (DestType->isDependentType() || FromType->isDependentType()) 2564 return From; 2565 2566 // If the unqualified types are the same, no conversion is necessary. 2567 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2568 return From; 2569 2570 SourceRange FromRange = From->getSourceRange(); 2571 SourceLocation FromLoc = FromRange.getBegin(); 2572 2573 ExprValueKind VK = From->getValueKind(); 2574 2575 // C++ [class.member.lookup]p8: 2576 // [...] Ambiguities can often be resolved by qualifying a name with its 2577 // class name. 2578 // 2579 // If the member was a qualified name and the qualified referred to a 2580 // specific base subobject type, we'll cast to that intermediate type 2581 // first and then to the object in which the member is declared. That allows 2582 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2583 // 2584 // class Base { public: int x; }; 2585 // class Derived1 : public Base { }; 2586 // class Derived2 : public Base { }; 2587 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2588 // 2589 // void VeryDerived::f() { 2590 // x = 17; // error: ambiguous base subobjects 2591 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2592 // } 2593 if (Qualifier && Qualifier->getAsType()) { 2594 QualType QType = QualType(Qualifier->getAsType(), 0); 2595 assert(QType->isRecordType() && "lookup done with non-record type"); 2596 2597 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2598 2599 // In C++98, the qualifier type doesn't actually have to be a base 2600 // type of the object type, in which case we just ignore it. 2601 // Otherwise build the appropriate casts. 2602 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2603 CXXCastPath BasePath; 2604 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2605 FromLoc, FromRange, &BasePath)) 2606 return ExprError(); 2607 2608 if (PointerConversions) 2609 QType = Context.getPointerType(QType); 2610 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2611 VK, &BasePath).get(); 2612 2613 FromType = QType; 2614 FromRecordType = QRecordType; 2615 2616 // If the qualifier type was the same as the destination type, 2617 // we're done. 2618 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2619 return From; 2620 } 2621 } 2622 2623 bool IgnoreAccess = false; 2624 2625 // If we actually found the member through a using declaration, cast 2626 // down to the using declaration's type. 2627 // 2628 // Pointer equality is fine here because only one declaration of a 2629 // class ever has member declarations. 2630 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2631 assert(isa<UsingShadowDecl>(FoundDecl)); 2632 QualType URecordType = Context.getTypeDeclType( 2633 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2634 2635 // We only need to do this if the naming-class to declaring-class 2636 // conversion is non-trivial. 2637 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2638 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2639 CXXCastPath BasePath; 2640 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2641 FromLoc, FromRange, &BasePath)) 2642 return ExprError(); 2643 2644 QualType UType = URecordType; 2645 if (PointerConversions) 2646 UType = Context.getPointerType(UType); 2647 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2648 VK, &BasePath).get(); 2649 FromType = UType; 2650 FromRecordType = URecordType; 2651 } 2652 2653 // We don't do access control for the conversion from the 2654 // declaring class to the true declaring class. 2655 IgnoreAccess = true; 2656 } 2657 2658 CXXCastPath BasePath; 2659 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2660 FromLoc, FromRange, &BasePath, 2661 IgnoreAccess)) 2662 return ExprError(); 2663 2664 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2665 VK, &BasePath); 2666 } 2667 2668 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2669 const LookupResult &R, 2670 bool HasTrailingLParen) { 2671 // Only when used directly as the postfix-expression of a call. 2672 if (!HasTrailingLParen) 2673 return false; 2674 2675 // Never if a scope specifier was provided. 2676 if (SS.isSet()) 2677 return false; 2678 2679 // Only in C++ or ObjC++. 2680 if (!getLangOpts().CPlusPlus) 2681 return false; 2682 2683 // Turn off ADL when we find certain kinds of declarations during 2684 // normal lookup: 2685 for (NamedDecl *D : R) { 2686 // C++0x [basic.lookup.argdep]p3: 2687 // -- a declaration of a class member 2688 // Since using decls preserve this property, we check this on the 2689 // original decl. 2690 if (D->isCXXClassMember()) 2691 return false; 2692 2693 // C++0x [basic.lookup.argdep]p3: 2694 // -- a block-scope function declaration that is not a 2695 // using-declaration 2696 // NOTE: we also trigger this for function templates (in fact, we 2697 // don't check the decl type at all, since all other decl types 2698 // turn off ADL anyway). 2699 if (isa<UsingShadowDecl>(D)) 2700 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2701 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2702 return false; 2703 2704 // C++0x [basic.lookup.argdep]p3: 2705 // -- a declaration that is neither a function or a function 2706 // template 2707 // And also for builtin functions. 2708 if (isa<FunctionDecl>(D)) { 2709 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2710 2711 // But also builtin functions. 2712 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2713 return false; 2714 } else if (!isa<FunctionTemplateDecl>(D)) 2715 return false; 2716 } 2717 2718 return true; 2719 } 2720 2721 2722 /// Diagnoses obvious problems with the use of the given declaration 2723 /// as an expression. This is only actually called for lookups that 2724 /// were not overloaded, and it doesn't promise that the declaration 2725 /// will in fact be used. 2726 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2727 if (isa<TypedefNameDecl>(D)) { 2728 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2729 return true; 2730 } 2731 2732 if (isa<ObjCInterfaceDecl>(D)) { 2733 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2734 return true; 2735 } 2736 2737 if (isa<NamespaceDecl>(D)) { 2738 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2739 return true; 2740 } 2741 2742 return false; 2743 } 2744 2745 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2746 LookupResult &R, bool NeedsADL, 2747 bool AcceptInvalidDecl) { 2748 // If this is a single, fully-resolved result and we don't need ADL, 2749 // just build an ordinary singleton decl ref. 2750 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2751 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2752 R.getRepresentativeDecl(), nullptr, 2753 AcceptInvalidDecl); 2754 2755 // We only need to check the declaration if there's exactly one 2756 // result, because in the overloaded case the results can only be 2757 // functions and function templates. 2758 if (R.isSingleResult() && 2759 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2760 return ExprError(); 2761 2762 // Otherwise, just build an unresolved lookup expression. Suppress 2763 // any lookup-related diagnostics; we'll hash these out later, when 2764 // we've picked a target. 2765 R.suppressDiagnostics(); 2766 2767 UnresolvedLookupExpr *ULE 2768 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2769 SS.getWithLocInContext(Context), 2770 R.getLookupNameInfo(), 2771 NeedsADL, R.isOverloadedResult(), 2772 R.begin(), R.end()); 2773 2774 return ULE; 2775 } 2776 2777 /// \brief Complete semantic analysis for a reference to the given declaration. 2778 ExprResult Sema::BuildDeclarationNameExpr( 2779 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2780 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2781 bool AcceptInvalidDecl) { 2782 assert(D && "Cannot refer to a NULL declaration"); 2783 assert(!isa<FunctionTemplateDecl>(D) && 2784 "Cannot refer unambiguously to a function template"); 2785 2786 SourceLocation Loc = NameInfo.getLoc(); 2787 if (CheckDeclInExpr(*this, Loc, D)) 2788 return ExprError(); 2789 2790 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2791 // Specifically diagnose references to class templates that are missing 2792 // a template argument list. 2793 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2794 << Template << SS.getRange(); 2795 Diag(Template->getLocation(), diag::note_template_decl_here); 2796 return ExprError(); 2797 } 2798 2799 // Make sure that we're referring to a value. 2800 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2801 if (!VD) { 2802 Diag(Loc, diag::err_ref_non_value) 2803 << D << SS.getRange(); 2804 Diag(D->getLocation(), diag::note_declared_at); 2805 return ExprError(); 2806 } 2807 2808 // Check whether this declaration can be used. Note that we suppress 2809 // this check when we're going to perform argument-dependent lookup 2810 // on this function name, because this might not be the function 2811 // that overload resolution actually selects. 2812 if (DiagnoseUseOfDecl(VD, Loc)) 2813 return ExprError(); 2814 2815 // Only create DeclRefExpr's for valid Decl's. 2816 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2817 return ExprError(); 2818 2819 // Handle members of anonymous structs and unions. If we got here, 2820 // and the reference is to a class member indirect field, then this 2821 // must be the subject of a pointer-to-member expression. 2822 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2823 if (!indirectField->isCXXClassMember()) 2824 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2825 indirectField); 2826 2827 { 2828 QualType type = VD->getType(); 2829 ExprValueKind valueKind = VK_RValue; 2830 2831 switch (D->getKind()) { 2832 // Ignore all the non-ValueDecl kinds. 2833 #define ABSTRACT_DECL(kind) 2834 #define VALUE(type, base) 2835 #define DECL(type, base) \ 2836 case Decl::type: 2837 #include "clang/AST/DeclNodes.inc" 2838 llvm_unreachable("invalid value decl kind"); 2839 2840 // These shouldn't make it here. 2841 case Decl::ObjCAtDefsField: 2842 case Decl::ObjCIvar: 2843 llvm_unreachable("forming non-member reference to ivar?"); 2844 2845 // Enum constants are always r-values and never references. 2846 // Unresolved using declarations are dependent. 2847 case Decl::EnumConstant: 2848 case Decl::UnresolvedUsingValue: 2849 valueKind = VK_RValue; 2850 break; 2851 2852 // Fields and indirect fields that got here must be for 2853 // pointer-to-member expressions; we just call them l-values for 2854 // internal consistency, because this subexpression doesn't really 2855 // exist in the high-level semantics. 2856 case Decl::Field: 2857 case Decl::IndirectField: 2858 assert(getLangOpts().CPlusPlus && 2859 "building reference to field in C?"); 2860 2861 // These can't have reference type in well-formed programs, but 2862 // for internal consistency we do this anyway. 2863 type = type.getNonReferenceType(); 2864 valueKind = VK_LValue; 2865 break; 2866 2867 // Non-type template parameters are either l-values or r-values 2868 // depending on the type. 2869 case Decl::NonTypeTemplateParm: { 2870 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2871 type = reftype->getPointeeType(); 2872 valueKind = VK_LValue; // even if the parameter is an r-value reference 2873 break; 2874 } 2875 2876 // For non-references, we need to strip qualifiers just in case 2877 // the template parameter was declared as 'const int' or whatever. 2878 valueKind = VK_RValue; 2879 type = type.getUnqualifiedType(); 2880 break; 2881 } 2882 2883 case Decl::Var: 2884 case Decl::VarTemplateSpecialization: 2885 case Decl::VarTemplatePartialSpecialization: 2886 case Decl::OMPCapturedExpr: 2887 // In C, "extern void blah;" is valid and is an r-value. 2888 if (!getLangOpts().CPlusPlus && 2889 !type.hasQualifiers() && 2890 type->isVoidType()) { 2891 valueKind = VK_RValue; 2892 break; 2893 } 2894 // fallthrough 2895 2896 case Decl::ImplicitParam: 2897 case Decl::ParmVar: { 2898 // These are always l-values. 2899 valueKind = VK_LValue; 2900 type = type.getNonReferenceType(); 2901 2902 // FIXME: Does the addition of const really only apply in 2903 // potentially-evaluated contexts? Since the variable isn't actually 2904 // captured in an unevaluated context, it seems that the answer is no. 2905 if (!isUnevaluatedContext()) { 2906 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2907 if (!CapturedType.isNull()) 2908 type = CapturedType; 2909 } 2910 2911 break; 2912 } 2913 2914 case Decl::Function: { 2915 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2916 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2917 type = Context.BuiltinFnTy; 2918 valueKind = VK_RValue; 2919 break; 2920 } 2921 } 2922 2923 const FunctionType *fty = type->castAs<FunctionType>(); 2924 2925 // If we're referring to a function with an __unknown_anytype 2926 // result type, make the entire expression __unknown_anytype. 2927 if (fty->getReturnType() == Context.UnknownAnyTy) { 2928 type = Context.UnknownAnyTy; 2929 valueKind = VK_RValue; 2930 break; 2931 } 2932 2933 // Functions are l-values in C++. 2934 if (getLangOpts().CPlusPlus) { 2935 valueKind = VK_LValue; 2936 break; 2937 } 2938 2939 // C99 DR 316 says that, if a function type comes from a 2940 // function definition (without a prototype), that type is only 2941 // used for checking compatibility. Therefore, when referencing 2942 // the function, we pretend that we don't have the full function 2943 // type. 2944 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2945 isa<FunctionProtoType>(fty)) 2946 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2947 fty->getExtInfo()); 2948 2949 // Functions are r-values in C. 2950 valueKind = VK_RValue; 2951 break; 2952 } 2953 2954 case Decl::MSProperty: 2955 valueKind = VK_LValue; 2956 break; 2957 2958 case Decl::CXXMethod: 2959 // If we're referring to a method with an __unknown_anytype 2960 // result type, make the entire expression __unknown_anytype. 2961 // This should only be possible with a type written directly. 2962 if (const FunctionProtoType *proto 2963 = dyn_cast<FunctionProtoType>(VD->getType())) 2964 if (proto->getReturnType() == Context.UnknownAnyTy) { 2965 type = Context.UnknownAnyTy; 2966 valueKind = VK_RValue; 2967 break; 2968 } 2969 2970 // C++ methods are l-values if static, r-values if non-static. 2971 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2972 valueKind = VK_LValue; 2973 break; 2974 } 2975 // fallthrough 2976 2977 case Decl::CXXConversion: 2978 case Decl::CXXDestructor: 2979 case Decl::CXXConstructor: 2980 valueKind = VK_RValue; 2981 break; 2982 } 2983 2984 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2985 TemplateArgs); 2986 } 2987 } 2988 2989 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2990 SmallString<32> &Target) { 2991 Target.resize(CharByteWidth * (Source.size() + 1)); 2992 char *ResultPtr = &Target[0]; 2993 const UTF8 *ErrorPtr; 2994 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2995 (void)success; 2996 assert(success); 2997 Target.resize(ResultPtr - &Target[0]); 2998 } 2999 3000 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3001 PredefinedExpr::IdentType IT) { 3002 // Pick the current block, lambda, captured statement or function. 3003 Decl *currentDecl = nullptr; 3004 if (const BlockScopeInfo *BSI = getCurBlock()) 3005 currentDecl = BSI->TheDecl; 3006 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3007 currentDecl = LSI->CallOperator; 3008 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3009 currentDecl = CSI->TheCapturedDecl; 3010 else 3011 currentDecl = getCurFunctionOrMethodDecl(); 3012 3013 if (!currentDecl) { 3014 Diag(Loc, diag::ext_predef_outside_function); 3015 currentDecl = Context.getTranslationUnitDecl(); 3016 } 3017 3018 QualType ResTy; 3019 StringLiteral *SL = nullptr; 3020 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3021 ResTy = Context.DependentTy; 3022 else { 3023 // Pre-defined identifiers are of type char[x], where x is the length of 3024 // the string. 3025 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3026 unsigned Length = Str.length(); 3027 3028 llvm::APInt LengthI(32, Length + 1); 3029 if (IT == PredefinedExpr::LFunction) { 3030 ResTy = Context.WideCharTy.withConst(); 3031 SmallString<32> RawChars; 3032 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3033 Str, RawChars); 3034 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3035 /*IndexTypeQuals*/ 0); 3036 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3037 /*Pascal*/ false, ResTy, Loc); 3038 } else { 3039 ResTy = Context.CharTy.withConst(); 3040 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3041 /*IndexTypeQuals*/ 0); 3042 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3043 /*Pascal*/ false, ResTy, Loc); 3044 } 3045 } 3046 3047 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3048 } 3049 3050 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3051 PredefinedExpr::IdentType IT; 3052 3053 switch (Kind) { 3054 default: llvm_unreachable("Unknown simple primary expr!"); 3055 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3056 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3057 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3058 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3059 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3060 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3061 } 3062 3063 return BuildPredefinedExpr(Loc, IT); 3064 } 3065 3066 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3067 SmallString<16> CharBuffer; 3068 bool Invalid = false; 3069 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3070 if (Invalid) 3071 return ExprError(); 3072 3073 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3074 PP, Tok.getKind()); 3075 if (Literal.hadError()) 3076 return ExprError(); 3077 3078 QualType Ty; 3079 if (Literal.isWide()) 3080 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3081 else if (Literal.isUTF16()) 3082 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3083 else if (Literal.isUTF32()) 3084 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3085 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3086 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3087 else 3088 Ty = Context.CharTy; // 'x' -> char in C++ 3089 3090 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3091 if (Literal.isWide()) 3092 Kind = CharacterLiteral::Wide; 3093 else if (Literal.isUTF16()) 3094 Kind = CharacterLiteral::UTF16; 3095 else if (Literal.isUTF32()) 3096 Kind = CharacterLiteral::UTF32; 3097 else if (Literal.isUTF8()) 3098 Kind = CharacterLiteral::UTF8; 3099 3100 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3101 Tok.getLocation()); 3102 3103 if (Literal.getUDSuffix().empty()) 3104 return Lit; 3105 3106 // We're building a user-defined literal. 3107 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3108 SourceLocation UDSuffixLoc = 3109 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3110 3111 // Make sure we're allowed user-defined literals here. 3112 if (!UDLScope) 3113 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3114 3115 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3116 // operator "" X (ch) 3117 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3118 Lit, Tok.getLocation()); 3119 } 3120 3121 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3122 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3123 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3124 Context.IntTy, Loc); 3125 } 3126 3127 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3128 QualType Ty, SourceLocation Loc) { 3129 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3130 3131 using llvm::APFloat; 3132 APFloat Val(Format); 3133 3134 APFloat::opStatus result = Literal.GetFloatValue(Val); 3135 3136 // Overflow is always an error, but underflow is only an error if 3137 // we underflowed to zero (APFloat reports denormals as underflow). 3138 if ((result & APFloat::opOverflow) || 3139 ((result & APFloat::opUnderflow) && Val.isZero())) { 3140 unsigned diagnostic; 3141 SmallString<20> buffer; 3142 if (result & APFloat::opOverflow) { 3143 diagnostic = diag::warn_float_overflow; 3144 APFloat::getLargest(Format).toString(buffer); 3145 } else { 3146 diagnostic = diag::warn_float_underflow; 3147 APFloat::getSmallest(Format).toString(buffer); 3148 } 3149 3150 S.Diag(Loc, diagnostic) 3151 << Ty 3152 << StringRef(buffer.data(), buffer.size()); 3153 } 3154 3155 bool isExact = (result == APFloat::opOK); 3156 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3157 } 3158 3159 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3160 assert(E && "Invalid expression"); 3161 3162 if (E->isValueDependent()) 3163 return false; 3164 3165 QualType QT = E->getType(); 3166 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3167 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3168 return true; 3169 } 3170 3171 llvm::APSInt ValueAPS; 3172 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3173 3174 if (R.isInvalid()) 3175 return true; 3176 3177 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3178 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3179 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3180 << ValueAPS.toString(10) << ValueIsPositive; 3181 return true; 3182 } 3183 3184 return false; 3185 } 3186 3187 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3188 // Fast path for a single digit (which is quite common). A single digit 3189 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3190 if (Tok.getLength() == 1) { 3191 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3192 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3193 } 3194 3195 SmallString<128> SpellingBuffer; 3196 // NumericLiteralParser wants to overread by one character. Add padding to 3197 // the buffer in case the token is copied to the buffer. If getSpelling() 3198 // returns a StringRef to the memory buffer, it should have a null char at 3199 // the EOF, so it is also safe. 3200 SpellingBuffer.resize(Tok.getLength() + 1); 3201 3202 // Get the spelling of the token, which eliminates trigraphs, etc. 3203 bool Invalid = false; 3204 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3205 if (Invalid) 3206 return ExprError(); 3207 3208 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3209 if (Literal.hadError) 3210 return ExprError(); 3211 3212 if (Literal.hasUDSuffix()) { 3213 // We're building a user-defined literal. 3214 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3215 SourceLocation UDSuffixLoc = 3216 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3217 3218 // Make sure we're allowed user-defined literals here. 3219 if (!UDLScope) 3220 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3221 3222 QualType CookedTy; 3223 if (Literal.isFloatingLiteral()) { 3224 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3225 // long double, the literal is treated as a call of the form 3226 // operator "" X (f L) 3227 CookedTy = Context.LongDoubleTy; 3228 } else { 3229 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3230 // unsigned long long, the literal is treated as a call of the form 3231 // operator "" X (n ULL) 3232 CookedTy = Context.UnsignedLongLongTy; 3233 } 3234 3235 DeclarationName OpName = 3236 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3237 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3238 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3239 3240 SourceLocation TokLoc = Tok.getLocation(); 3241 3242 // Perform literal operator lookup to determine if we're building a raw 3243 // literal or a cooked one. 3244 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3245 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3246 /*AllowRaw*/true, /*AllowTemplate*/true, 3247 /*AllowStringTemplate*/false)) { 3248 case LOLR_Error: 3249 return ExprError(); 3250 3251 case LOLR_Cooked: { 3252 Expr *Lit; 3253 if (Literal.isFloatingLiteral()) { 3254 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3255 } else { 3256 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3257 if (Literal.GetIntegerValue(ResultVal)) 3258 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3259 << /* Unsigned */ 1; 3260 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3261 Tok.getLocation()); 3262 } 3263 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3264 } 3265 3266 case LOLR_Raw: { 3267 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3268 // literal is treated as a call of the form 3269 // operator "" X ("n") 3270 unsigned Length = Literal.getUDSuffixOffset(); 3271 QualType StrTy = Context.getConstantArrayType( 3272 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3273 ArrayType::Normal, 0); 3274 Expr *Lit = StringLiteral::Create( 3275 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3276 /*Pascal*/false, StrTy, &TokLoc, 1); 3277 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3278 } 3279 3280 case LOLR_Template: { 3281 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3282 // template), L is treated as a call fo the form 3283 // operator "" X <'c1', 'c2', ... 'ck'>() 3284 // where n is the source character sequence c1 c2 ... ck. 3285 TemplateArgumentListInfo ExplicitArgs; 3286 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3287 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3288 llvm::APSInt Value(CharBits, CharIsUnsigned); 3289 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3290 Value = TokSpelling[I]; 3291 TemplateArgument Arg(Context, Value, Context.CharTy); 3292 TemplateArgumentLocInfo ArgInfo; 3293 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3294 } 3295 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3296 &ExplicitArgs); 3297 } 3298 case LOLR_StringTemplate: 3299 llvm_unreachable("unexpected literal operator lookup result"); 3300 } 3301 } 3302 3303 Expr *Res; 3304 3305 if (Literal.isFloatingLiteral()) { 3306 QualType Ty; 3307 if (Literal.isHalf){ 3308 if (getOpenCLOptions().cl_khr_fp16) 3309 Ty = Context.HalfTy; 3310 else { 3311 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3312 return ExprError(); 3313 } 3314 } else if (Literal.isFloat) 3315 Ty = Context.FloatTy; 3316 else if (!Literal.isLong) 3317 Ty = Context.DoubleTy; 3318 else 3319 Ty = Context.LongDoubleTy; 3320 3321 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3322 3323 if (Ty == Context.DoubleTy) { 3324 if (getLangOpts().SinglePrecisionConstants) { 3325 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3326 } else if (getLangOpts().OpenCL && 3327 !((getLangOpts().OpenCLVersion >= 120) || 3328 getOpenCLOptions().cl_khr_fp64)) { 3329 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3330 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3331 } 3332 } 3333 } else if (!Literal.isIntegerLiteral()) { 3334 return ExprError(); 3335 } else { 3336 QualType Ty; 3337 3338 // 'long long' is a C99 or C++11 feature. 3339 if (!getLangOpts().C99 && Literal.isLongLong) { 3340 if (getLangOpts().CPlusPlus) 3341 Diag(Tok.getLocation(), 3342 getLangOpts().CPlusPlus11 ? 3343 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3344 else 3345 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3346 } 3347 3348 // Get the value in the widest-possible width. 3349 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3350 llvm::APInt ResultVal(MaxWidth, 0); 3351 3352 if (Literal.GetIntegerValue(ResultVal)) { 3353 // If this value didn't fit into uintmax_t, error and force to ull. 3354 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3355 << /* Unsigned */ 1; 3356 Ty = Context.UnsignedLongLongTy; 3357 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3358 "long long is not intmax_t?"); 3359 } else { 3360 // If this value fits into a ULL, try to figure out what else it fits into 3361 // according to the rules of C99 6.4.4.1p5. 3362 3363 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3364 // be an unsigned int. 3365 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3366 3367 // Check from smallest to largest, picking the smallest type we can. 3368 unsigned Width = 0; 3369 3370 // Microsoft specific integer suffixes are explicitly sized. 3371 if (Literal.MicrosoftInteger) { 3372 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3373 Width = 8; 3374 Ty = Context.CharTy; 3375 } else { 3376 Width = Literal.MicrosoftInteger; 3377 Ty = Context.getIntTypeForBitwidth(Width, 3378 /*Signed=*/!Literal.isUnsigned); 3379 } 3380 } 3381 3382 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3383 // Are int/unsigned possibilities? 3384 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3385 3386 // Does it fit in a unsigned int? 3387 if (ResultVal.isIntN(IntSize)) { 3388 // Does it fit in a signed int? 3389 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3390 Ty = Context.IntTy; 3391 else if (AllowUnsigned) 3392 Ty = Context.UnsignedIntTy; 3393 Width = IntSize; 3394 } 3395 } 3396 3397 // Are long/unsigned long possibilities? 3398 if (Ty.isNull() && !Literal.isLongLong) { 3399 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3400 3401 // Does it fit in a unsigned long? 3402 if (ResultVal.isIntN(LongSize)) { 3403 // Does it fit in a signed long? 3404 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3405 Ty = Context.LongTy; 3406 else if (AllowUnsigned) 3407 Ty = Context.UnsignedLongTy; 3408 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3409 // is compatible. 3410 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3411 const unsigned LongLongSize = 3412 Context.getTargetInfo().getLongLongWidth(); 3413 Diag(Tok.getLocation(), 3414 getLangOpts().CPlusPlus 3415 ? Literal.isLong 3416 ? diag::warn_old_implicitly_unsigned_long_cxx 3417 : /*C++98 UB*/ diag:: 3418 ext_old_implicitly_unsigned_long_cxx 3419 : diag::warn_old_implicitly_unsigned_long) 3420 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3421 : /*will be ill-formed*/ 1); 3422 Ty = Context.UnsignedLongTy; 3423 } 3424 Width = LongSize; 3425 } 3426 } 3427 3428 // Check long long if needed. 3429 if (Ty.isNull()) { 3430 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3431 3432 // Does it fit in a unsigned long long? 3433 if (ResultVal.isIntN(LongLongSize)) { 3434 // Does it fit in a signed long long? 3435 // To be compatible with MSVC, hex integer literals ending with the 3436 // LL or i64 suffix are always signed in Microsoft mode. 3437 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3438 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3439 Ty = Context.LongLongTy; 3440 else if (AllowUnsigned) 3441 Ty = Context.UnsignedLongLongTy; 3442 Width = LongLongSize; 3443 } 3444 } 3445 3446 // If we still couldn't decide a type, we probably have something that 3447 // does not fit in a signed long long, but has no U suffix. 3448 if (Ty.isNull()) { 3449 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3450 Ty = Context.UnsignedLongLongTy; 3451 Width = Context.getTargetInfo().getLongLongWidth(); 3452 } 3453 3454 if (ResultVal.getBitWidth() != Width) 3455 ResultVal = ResultVal.trunc(Width); 3456 } 3457 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3458 } 3459 3460 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3461 if (Literal.isImaginary) 3462 Res = new (Context) ImaginaryLiteral(Res, 3463 Context.getComplexType(Res->getType())); 3464 3465 return Res; 3466 } 3467 3468 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3469 assert(E && "ActOnParenExpr() missing expr"); 3470 return new (Context) ParenExpr(L, R, E); 3471 } 3472 3473 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3474 SourceLocation Loc, 3475 SourceRange ArgRange) { 3476 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3477 // scalar or vector data type argument..." 3478 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3479 // type (C99 6.2.5p18) or void. 3480 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3481 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3482 << T << ArgRange; 3483 return true; 3484 } 3485 3486 assert((T->isVoidType() || !T->isIncompleteType()) && 3487 "Scalar types should always be complete"); 3488 return false; 3489 } 3490 3491 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3492 SourceLocation Loc, 3493 SourceRange ArgRange, 3494 UnaryExprOrTypeTrait TraitKind) { 3495 // Invalid types must be hard errors for SFINAE in C++. 3496 if (S.LangOpts.CPlusPlus) 3497 return true; 3498 3499 // C99 6.5.3.4p1: 3500 if (T->isFunctionType() && 3501 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3502 // sizeof(function)/alignof(function) is allowed as an extension. 3503 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3504 << TraitKind << ArgRange; 3505 return false; 3506 } 3507 3508 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3509 // this is an error (OpenCL v1.1 s6.3.k) 3510 if (T->isVoidType()) { 3511 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3512 : diag::ext_sizeof_alignof_void_type; 3513 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3514 return false; 3515 } 3516 3517 return true; 3518 } 3519 3520 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3521 SourceLocation Loc, 3522 SourceRange ArgRange, 3523 UnaryExprOrTypeTrait TraitKind) { 3524 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3525 // runtime doesn't allow it. 3526 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3527 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3528 << T << (TraitKind == UETT_SizeOf) 3529 << ArgRange; 3530 return true; 3531 } 3532 3533 return false; 3534 } 3535 3536 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3537 /// pointer type is equal to T) and emit a warning if it is. 3538 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3539 Expr *E) { 3540 // Don't warn if the operation changed the type. 3541 if (T != E->getType()) 3542 return; 3543 3544 // Now look for array decays. 3545 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3546 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3547 return; 3548 3549 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3550 << ICE->getType() 3551 << ICE->getSubExpr()->getType(); 3552 } 3553 3554 /// \brief Check the constraints on expression operands to unary type expression 3555 /// and type traits. 3556 /// 3557 /// Completes any types necessary and validates the constraints on the operand 3558 /// expression. The logic mostly mirrors the type-based overload, but may modify 3559 /// the expression as it completes the type for that expression through template 3560 /// instantiation, etc. 3561 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3562 UnaryExprOrTypeTrait ExprKind) { 3563 QualType ExprTy = E->getType(); 3564 assert(!ExprTy->isReferenceType()); 3565 3566 if (ExprKind == UETT_VecStep) 3567 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3568 E->getSourceRange()); 3569 3570 // Whitelist some types as extensions 3571 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3572 E->getSourceRange(), ExprKind)) 3573 return false; 3574 3575 // 'alignof' applied to an expression only requires the base element type of 3576 // the expression to be complete. 'sizeof' requires the expression's type to 3577 // be complete (and will attempt to complete it if it's an array of unknown 3578 // bound). 3579 if (ExprKind == UETT_AlignOf) { 3580 if (RequireCompleteType(E->getExprLoc(), 3581 Context.getBaseElementType(E->getType()), 3582 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3583 E->getSourceRange())) 3584 return true; 3585 } else { 3586 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3587 ExprKind, E->getSourceRange())) 3588 return true; 3589 } 3590 3591 // Completing the expression's type may have changed it. 3592 ExprTy = E->getType(); 3593 assert(!ExprTy->isReferenceType()); 3594 3595 if (ExprTy->isFunctionType()) { 3596 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3597 << ExprKind << E->getSourceRange(); 3598 return true; 3599 } 3600 3601 // The operand for sizeof and alignof is in an unevaluated expression context, 3602 // so side effects could result in unintended consequences. 3603 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3604 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3605 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3606 3607 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3608 E->getSourceRange(), ExprKind)) 3609 return true; 3610 3611 if (ExprKind == UETT_SizeOf) { 3612 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3613 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3614 QualType OType = PVD->getOriginalType(); 3615 QualType Type = PVD->getType(); 3616 if (Type->isPointerType() && OType->isArrayType()) { 3617 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3618 << Type << OType; 3619 Diag(PVD->getLocation(), diag::note_declared_at); 3620 } 3621 } 3622 } 3623 3624 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3625 // decays into a pointer and returns an unintended result. This is most 3626 // likely a typo for "sizeof(array) op x". 3627 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3628 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3629 BO->getLHS()); 3630 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3631 BO->getRHS()); 3632 } 3633 } 3634 3635 return false; 3636 } 3637 3638 /// \brief Check the constraints on operands to unary expression and type 3639 /// traits. 3640 /// 3641 /// This will complete any types necessary, and validate the various constraints 3642 /// on those operands. 3643 /// 3644 /// The UsualUnaryConversions() function is *not* called by this routine. 3645 /// C99 6.3.2.1p[2-4] all state: 3646 /// Except when it is the operand of the sizeof operator ... 3647 /// 3648 /// C++ [expr.sizeof]p4 3649 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3650 /// standard conversions are not applied to the operand of sizeof. 3651 /// 3652 /// This policy is followed for all of the unary trait expressions. 3653 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3654 SourceLocation OpLoc, 3655 SourceRange ExprRange, 3656 UnaryExprOrTypeTrait ExprKind) { 3657 if (ExprType->isDependentType()) 3658 return false; 3659 3660 // C++ [expr.sizeof]p2: 3661 // When applied to a reference or a reference type, the result 3662 // is the size of the referenced type. 3663 // C++11 [expr.alignof]p3: 3664 // When alignof is applied to a reference type, the result 3665 // shall be the alignment of the referenced type. 3666 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3667 ExprType = Ref->getPointeeType(); 3668 3669 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3670 // When alignof or _Alignof is applied to an array type, the result 3671 // is the alignment of the element type. 3672 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3673 ExprType = Context.getBaseElementType(ExprType); 3674 3675 if (ExprKind == UETT_VecStep) 3676 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3677 3678 // Whitelist some types as extensions 3679 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3680 ExprKind)) 3681 return false; 3682 3683 if (RequireCompleteType(OpLoc, ExprType, 3684 diag::err_sizeof_alignof_incomplete_type, 3685 ExprKind, ExprRange)) 3686 return true; 3687 3688 if (ExprType->isFunctionType()) { 3689 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3690 << ExprKind << ExprRange; 3691 return true; 3692 } 3693 3694 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3695 ExprKind)) 3696 return true; 3697 3698 return false; 3699 } 3700 3701 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3702 E = E->IgnoreParens(); 3703 3704 // Cannot know anything else if the expression is dependent. 3705 if (E->isTypeDependent()) 3706 return false; 3707 3708 if (E->getObjectKind() == OK_BitField) { 3709 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3710 << 1 << E->getSourceRange(); 3711 return true; 3712 } 3713 3714 ValueDecl *D = nullptr; 3715 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3716 D = DRE->getDecl(); 3717 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3718 D = ME->getMemberDecl(); 3719 } 3720 3721 // If it's a field, require the containing struct to have a 3722 // complete definition so that we can compute the layout. 3723 // 3724 // This can happen in C++11 onwards, either by naming the member 3725 // in a way that is not transformed into a member access expression 3726 // (in an unevaluated operand, for instance), or by naming the member 3727 // in a trailing-return-type. 3728 // 3729 // For the record, since __alignof__ on expressions is a GCC 3730 // extension, GCC seems to permit this but always gives the 3731 // nonsensical answer 0. 3732 // 3733 // We don't really need the layout here --- we could instead just 3734 // directly check for all the appropriate alignment-lowing 3735 // attributes --- but that would require duplicating a lot of 3736 // logic that just isn't worth duplicating for such a marginal 3737 // use-case. 3738 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3739 // Fast path this check, since we at least know the record has a 3740 // definition if we can find a member of it. 3741 if (!FD->getParent()->isCompleteDefinition()) { 3742 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3743 << E->getSourceRange(); 3744 return true; 3745 } 3746 3747 // Otherwise, if it's a field, and the field doesn't have 3748 // reference type, then it must have a complete type (or be a 3749 // flexible array member, which we explicitly want to 3750 // white-list anyway), which makes the following checks trivial. 3751 if (!FD->getType()->isReferenceType()) 3752 return false; 3753 } 3754 3755 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3756 } 3757 3758 bool Sema::CheckVecStepExpr(Expr *E) { 3759 E = E->IgnoreParens(); 3760 3761 // Cannot know anything else if the expression is dependent. 3762 if (E->isTypeDependent()) 3763 return false; 3764 3765 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3766 } 3767 3768 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3769 CapturingScopeInfo *CSI) { 3770 assert(T->isVariablyModifiedType()); 3771 assert(CSI != nullptr); 3772 3773 // We're going to walk down into the type and look for VLA expressions. 3774 do { 3775 const Type *Ty = T.getTypePtr(); 3776 switch (Ty->getTypeClass()) { 3777 #define TYPE(Class, Base) 3778 #define ABSTRACT_TYPE(Class, Base) 3779 #define NON_CANONICAL_TYPE(Class, Base) 3780 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3781 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3782 #include "clang/AST/TypeNodes.def" 3783 T = QualType(); 3784 break; 3785 // These types are never variably-modified. 3786 case Type::Builtin: 3787 case Type::Complex: 3788 case Type::Vector: 3789 case Type::ExtVector: 3790 case Type::Record: 3791 case Type::Enum: 3792 case Type::Elaborated: 3793 case Type::TemplateSpecialization: 3794 case Type::ObjCObject: 3795 case Type::ObjCInterface: 3796 case Type::ObjCObjectPointer: 3797 case Type::Pipe: 3798 llvm_unreachable("type class is never variably-modified!"); 3799 case Type::Adjusted: 3800 T = cast<AdjustedType>(Ty)->getOriginalType(); 3801 break; 3802 case Type::Decayed: 3803 T = cast<DecayedType>(Ty)->getPointeeType(); 3804 break; 3805 case Type::Pointer: 3806 T = cast<PointerType>(Ty)->getPointeeType(); 3807 break; 3808 case Type::BlockPointer: 3809 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3810 break; 3811 case Type::LValueReference: 3812 case Type::RValueReference: 3813 T = cast<ReferenceType>(Ty)->getPointeeType(); 3814 break; 3815 case Type::MemberPointer: 3816 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3817 break; 3818 case Type::ConstantArray: 3819 case Type::IncompleteArray: 3820 // Losing element qualification here is fine. 3821 T = cast<ArrayType>(Ty)->getElementType(); 3822 break; 3823 case Type::VariableArray: { 3824 // Losing element qualification here is fine. 3825 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3826 3827 // Unknown size indication requires no size computation. 3828 // Otherwise, evaluate and record it. 3829 if (auto Size = VAT->getSizeExpr()) { 3830 if (!CSI->isVLATypeCaptured(VAT)) { 3831 RecordDecl *CapRecord = nullptr; 3832 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3833 CapRecord = LSI->Lambda; 3834 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3835 CapRecord = CRSI->TheRecordDecl; 3836 } 3837 if (CapRecord) { 3838 auto ExprLoc = Size->getExprLoc(); 3839 auto SizeType = Context.getSizeType(); 3840 // Build the non-static data member. 3841 auto Field = 3842 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3843 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3844 /*BW*/ nullptr, /*Mutable*/ false, 3845 /*InitStyle*/ ICIS_NoInit); 3846 Field->setImplicit(true); 3847 Field->setAccess(AS_private); 3848 Field->setCapturedVLAType(VAT); 3849 CapRecord->addDecl(Field); 3850 3851 CSI->addVLATypeCapture(ExprLoc, SizeType); 3852 } 3853 } 3854 } 3855 T = VAT->getElementType(); 3856 break; 3857 } 3858 case Type::FunctionProto: 3859 case Type::FunctionNoProto: 3860 T = cast<FunctionType>(Ty)->getReturnType(); 3861 break; 3862 case Type::Paren: 3863 case Type::TypeOf: 3864 case Type::UnaryTransform: 3865 case Type::Attributed: 3866 case Type::SubstTemplateTypeParm: 3867 case Type::PackExpansion: 3868 // Keep walking after single level desugaring. 3869 T = T.getSingleStepDesugaredType(Context); 3870 break; 3871 case Type::Typedef: 3872 T = cast<TypedefType>(Ty)->desugar(); 3873 break; 3874 case Type::Decltype: 3875 T = cast<DecltypeType>(Ty)->desugar(); 3876 break; 3877 case Type::Auto: 3878 T = cast<AutoType>(Ty)->getDeducedType(); 3879 break; 3880 case Type::TypeOfExpr: 3881 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3882 break; 3883 case Type::Atomic: 3884 T = cast<AtomicType>(Ty)->getValueType(); 3885 break; 3886 } 3887 } while (!T.isNull() && T->isVariablyModifiedType()); 3888 } 3889 3890 /// \brief Build a sizeof or alignof expression given a type operand. 3891 ExprResult 3892 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3893 SourceLocation OpLoc, 3894 UnaryExprOrTypeTrait ExprKind, 3895 SourceRange R) { 3896 if (!TInfo) 3897 return ExprError(); 3898 3899 QualType T = TInfo->getType(); 3900 3901 if (!T->isDependentType() && 3902 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3903 return ExprError(); 3904 3905 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3906 if (auto *TT = T->getAs<TypedefType>()) { 3907 for (auto I = FunctionScopes.rbegin(), 3908 E = std::prev(FunctionScopes.rend()); 3909 I != E; ++I) { 3910 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3911 if (CSI == nullptr) 3912 break; 3913 DeclContext *DC = nullptr; 3914 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3915 DC = LSI->CallOperator; 3916 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3917 DC = CRSI->TheCapturedDecl; 3918 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3919 DC = BSI->TheDecl; 3920 if (DC) { 3921 if (DC->containsDecl(TT->getDecl())) 3922 break; 3923 captureVariablyModifiedType(Context, T, CSI); 3924 } 3925 } 3926 } 3927 } 3928 3929 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3930 return new (Context) UnaryExprOrTypeTraitExpr( 3931 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3932 } 3933 3934 /// \brief Build a sizeof or alignof expression given an expression 3935 /// operand. 3936 ExprResult 3937 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3938 UnaryExprOrTypeTrait ExprKind) { 3939 ExprResult PE = CheckPlaceholderExpr(E); 3940 if (PE.isInvalid()) 3941 return ExprError(); 3942 3943 E = PE.get(); 3944 3945 // Verify that the operand is valid. 3946 bool isInvalid = false; 3947 if (E->isTypeDependent()) { 3948 // Delay type-checking for type-dependent expressions. 3949 } else if (ExprKind == UETT_AlignOf) { 3950 isInvalid = CheckAlignOfExpr(*this, E); 3951 } else if (ExprKind == UETT_VecStep) { 3952 isInvalid = CheckVecStepExpr(E); 3953 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3954 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3955 isInvalid = true; 3956 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3957 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3958 isInvalid = true; 3959 } else { 3960 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3961 } 3962 3963 if (isInvalid) 3964 return ExprError(); 3965 3966 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3967 PE = TransformToPotentiallyEvaluated(E); 3968 if (PE.isInvalid()) return ExprError(); 3969 E = PE.get(); 3970 } 3971 3972 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3973 return new (Context) UnaryExprOrTypeTraitExpr( 3974 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3975 } 3976 3977 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3978 /// expr and the same for @c alignof and @c __alignof 3979 /// Note that the ArgRange is invalid if isType is false. 3980 ExprResult 3981 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3982 UnaryExprOrTypeTrait ExprKind, bool IsType, 3983 void *TyOrEx, SourceRange ArgRange) { 3984 // If error parsing type, ignore. 3985 if (!TyOrEx) return ExprError(); 3986 3987 if (IsType) { 3988 TypeSourceInfo *TInfo; 3989 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3990 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3991 } 3992 3993 Expr *ArgEx = (Expr *)TyOrEx; 3994 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3995 return Result; 3996 } 3997 3998 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3999 bool IsReal) { 4000 if (V.get()->isTypeDependent()) 4001 return S.Context.DependentTy; 4002 4003 // _Real and _Imag are only l-values for normal l-values. 4004 if (V.get()->getObjectKind() != OK_Ordinary) { 4005 V = S.DefaultLvalueConversion(V.get()); 4006 if (V.isInvalid()) 4007 return QualType(); 4008 } 4009 4010 // These operators return the element type of a complex type. 4011 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4012 return CT->getElementType(); 4013 4014 // Otherwise they pass through real integer and floating point types here. 4015 if (V.get()->getType()->isArithmeticType()) 4016 return V.get()->getType(); 4017 4018 // Test for placeholders. 4019 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4020 if (PR.isInvalid()) return QualType(); 4021 if (PR.get() != V.get()) { 4022 V = PR; 4023 return CheckRealImagOperand(S, V, Loc, IsReal); 4024 } 4025 4026 // Reject anything else. 4027 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4028 << (IsReal ? "__real" : "__imag"); 4029 return QualType(); 4030 } 4031 4032 4033 4034 ExprResult 4035 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4036 tok::TokenKind Kind, Expr *Input) { 4037 UnaryOperatorKind Opc; 4038 switch (Kind) { 4039 default: llvm_unreachable("Unknown unary op!"); 4040 case tok::plusplus: Opc = UO_PostInc; break; 4041 case tok::minusminus: Opc = UO_PostDec; break; 4042 } 4043 4044 // Since this might is a postfix expression, get rid of ParenListExprs. 4045 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4046 if (Result.isInvalid()) return ExprError(); 4047 Input = Result.get(); 4048 4049 return BuildUnaryOp(S, OpLoc, Opc, Input); 4050 } 4051 4052 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4053 /// 4054 /// \return true on error 4055 static bool checkArithmeticOnObjCPointer(Sema &S, 4056 SourceLocation opLoc, 4057 Expr *op) { 4058 assert(op->getType()->isObjCObjectPointerType()); 4059 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4060 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4061 return false; 4062 4063 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4064 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4065 << op->getSourceRange(); 4066 return true; 4067 } 4068 4069 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4070 auto *BaseNoParens = Base->IgnoreParens(); 4071 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4072 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4073 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4074 } 4075 4076 ExprResult 4077 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4078 Expr *idx, SourceLocation rbLoc) { 4079 if (base && !base->getType().isNull() && 4080 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4081 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4082 /*Length=*/nullptr, rbLoc); 4083 4084 // Since this might be a postfix expression, get rid of ParenListExprs. 4085 if (isa<ParenListExpr>(base)) { 4086 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4087 if (result.isInvalid()) return ExprError(); 4088 base = result.get(); 4089 } 4090 4091 // Handle any non-overload placeholder types in the base and index 4092 // expressions. We can't handle overloads here because the other 4093 // operand might be an overloadable type, in which case the overload 4094 // resolution for the operator overload should get the first crack 4095 // at the overload. 4096 bool IsMSPropertySubscript = false; 4097 if (base->getType()->isNonOverloadPlaceholderType()) { 4098 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4099 if (!IsMSPropertySubscript) { 4100 ExprResult result = CheckPlaceholderExpr(base); 4101 if (result.isInvalid()) 4102 return ExprError(); 4103 base = result.get(); 4104 } 4105 } 4106 if (idx->getType()->isNonOverloadPlaceholderType()) { 4107 ExprResult result = CheckPlaceholderExpr(idx); 4108 if (result.isInvalid()) return ExprError(); 4109 idx = result.get(); 4110 } 4111 4112 // Build an unanalyzed expression if either operand is type-dependent. 4113 if (getLangOpts().CPlusPlus && 4114 (base->isTypeDependent() || idx->isTypeDependent())) { 4115 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4116 VK_LValue, OK_Ordinary, rbLoc); 4117 } 4118 4119 // MSDN, property (C++) 4120 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4121 // This attribute can also be used in the declaration of an empty array in a 4122 // class or structure definition. For example: 4123 // __declspec(property(get=GetX, put=PutX)) int x[]; 4124 // The above statement indicates that x[] can be used with one or more array 4125 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4126 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4127 if (IsMSPropertySubscript) { 4128 // Build MS property subscript expression if base is MS property reference 4129 // or MS property subscript. 4130 return new (Context) MSPropertySubscriptExpr( 4131 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4132 } 4133 4134 // Use C++ overloaded-operator rules if either operand has record 4135 // type. The spec says to do this if either type is *overloadable*, 4136 // but enum types can't declare subscript operators or conversion 4137 // operators, so there's nothing interesting for overload resolution 4138 // to do if there aren't any record types involved. 4139 // 4140 // ObjC pointers have their own subscripting logic that is not tied 4141 // to overload resolution and so should not take this path. 4142 if (getLangOpts().CPlusPlus && 4143 (base->getType()->isRecordType() || 4144 (!base->getType()->isObjCObjectPointerType() && 4145 idx->getType()->isRecordType()))) { 4146 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4147 } 4148 4149 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4150 } 4151 4152 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4153 Expr *LowerBound, 4154 SourceLocation ColonLoc, Expr *Length, 4155 SourceLocation RBLoc) { 4156 if (Base->getType()->isPlaceholderType() && 4157 !Base->getType()->isSpecificPlaceholderType( 4158 BuiltinType::OMPArraySection)) { 4159 ExprResult Result = CheckPlaceholderExpr(Base); 4160 if (Result.isInvalid()) 4161 return ExprError(); 4162 Base = Result.get(); 4163 } 4164 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4165 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4166 if (Result.isInvalid()) 4167 return ExprError(); 4168 Result = DefaultLvalueConversion(Result.get()); 4169 if (Result.isInvalid()) 4170 return ExprError(); 4171 LowerBound = Result.get(); 4172 } 4173 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4174 ExprResult Result = CheckPlaceholderExpr(Length); 4175 if (Result.isInvalid()) 4176 return ExprError(); 4177 Result = DefaultLvalueConversion(Result.get()); 4178 if (Result.isInvalid()) 4179 return ExprError(); 4180 Length = Result.get(); 4181 } 4182 4183 // Build an unanalyzed expression if either operand is type-dependent. 4184 if (Base->isTypeDependent() || 4185 (LowerBound && 4186 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4187 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4188 return new (Context) 4189 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4190 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4191 } 4192 4193 // Perform default conversions. 4194 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4195 QualType ResultTy; 4196 if (OriginalTy->isAnyPointerType()) { 4197 ResultTy = OriginalTy->getPointeeType(); 4198 } else if (OriginalTy->isArrayType()) { 4199 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4200 } else { 4201 return ExprError( 4202 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4203 << Base->getSourceRange()); 4204 } 4205 // C99 6.5.2.1p1 4206 if (LowerBound) { 4207 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4208 LowerBound); 4209 if (Res.isInvalid()) 4210 return ExprError(Diag(LowerBound->getExprLoc(), 4211 diag::err_omp_typecheck_section_not_integer) 4212 << 0 << LowerBound->getSourceRange()); 4213 LowerBound = Res.get(); 4214 4215 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4216 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4217 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4218 << 0 << LowerBound->getSourceRange(); 4219 } 4220 if (Length) { 4221 auto Res = 4222 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4223 if (Res.isInvalid()) 4224 return ExprError(Diag(Length->getExprLoc(), 4225 diag::err_omp_typecheck_section_not_integer) 4226 << 1 << Length->getSourceRange()); 4227 Length = Res.get(); 4228 4229 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4230 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4231 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4232 << 1 << Length->getSourceRange(); 4233 } 4234 4235 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4236 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4237 // type. Note that functions are not objects, and that (in C99 parlance) 4238 // incomplete types are not object types. 4239 if (ResultTy->isFunctionType()) { 4240 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4241 << ResultTy << Base->getSourceRange(); 4242 return ExprError(); 4243 } 4244 4245 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4246 diag::err_omp_section_incomplete_type, Base)) 4247 return ExprError(); 4248 4249 if (LowerBound) { 4250 llvm::APSInt LowerBoundValue; 4251 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4252 // OpenMP 4.0, [2.4 Array Sections] 4253 // The lower-bound and length must evaluate to non-negative integers. 4254 if (LowerBoundValue.isNegative()) { 4255 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4256 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4257 << LowerBound->getSourceRange(); 4258 return ExprError(); 4259 } 4260 } 4261 } 4262 4263 if (Length) { 4264 llvm::APSInt LengthValue; 4265 if (Length->EvaluateAsInt(LengthValue, Context)) { 4266 // OpenMP 4.0, [2.4 Array Sections] 4267 // The lower-bound and length must evaluate to non-negative integers. 4268 if (LengthValue.isNegative()) { 4269 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4270 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4271 << Length->getSourceRange(); 4272 return ExprError(); 4273 } 4274 } 4275 } else if (ColonLoc.isValid() && 4276 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4277 !OriginalTy->isVariableArrayType()))) { 4278 // OpenMP 4.0, [2.4 Array Sections] 4279 // When the size of the array dimension is not known, the length must be 4280 // specified explicitly. 4281 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4282 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4283 return ExprError(); 4284 } 4285 4286 if (!Base->getType()->isSpecificPlaceholderType( 4287 BuiltinType::OMPArraySection)) { 4288 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4289 if (Result.isInvalid()) 4290 return ExprError(); 4291 Base = Result.get(); 4292 } 4293 return new (Context) 4294 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4295 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4296 } 4297 4298 ExprResult 4299 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4300 Expr *Idx, SourceLocation RLoc) { 4301 Expr *LHSExp = Base; 4302 Expr *RHSExp = Idx; 4303 4304 // Perform default conversions. 4305 if (!LHSExp->getType()->getAs<VectorType>()) { 4306 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4307 if (Result.isInvalid()) 4308 return ExprError(); 4309 LHSExp = Result.get(); 4310 } 4311 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4312 if (Result.isInvalid()) 4313 return ExprError(); 4314 RHSExp = Result.get(); 4315 4316 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4317 ExprValueKind VK = VK_LValue; 4318 ExprObjectKind OK = OK_Ordinary; 4319 4320 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4321 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4322 // in the subscript position. As a result, we need to derive the array base 4323 // and index from the expression types. 4324 Expr *BaseExpr, *IndexExpr; 4325 QualType ResultType; 4326 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4327 BaseExpr = LHSExp; 4328 IndexExpr = RHSExp; 4329 ResultType = Context.DependentTy; 4330 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4331 BaseExpr = LHSExp; 4332 IndexExpr = RHSExp; 4333 ResultType = PTy->getPointeeType(); 4334 } else if (const ObjCObjectPointerType *PTy = 4335 LHSTy->getAs<ObjCObjectPointerType>()) { 4336 BaseExpr = LHSExp; 4337 IndexExpr = RHSExp; 4338 4339 // Use custom logic if this should be the pseudo-object subscript 4340 // expression. 4341 if (!LangOpts.isSubscriptPointerArithmetic()) 4342 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4343 nullptr); 4344 4345 ResultType = PTy->getPointeeType(); 4346 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4347 // Handle the uncommon case of "123[Ptr]". 4348 BaseExpr = RHSExp; 4349 IndexExpr = LHSExp; 4350 ResultType = PTy->getPointeeType(); 4351 } else if (const ObjCObjectPointerType *PTy = 4352 RHSTy->getAs<ObjCObjectPointerType>()) { 4353 // Handle the uncommon case of "123[Ptr]". 4354 BaseExpr = RHSExp; 4355 IndexExpr = LHSExp; 4356 ResultType = PTy->getPointeeType(); 4357 if (!LangOpts.isSubscriptPointerArithmetic()) { 4358 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4359 << ResultType << BaseExpr->getSourceRange(); 4360 return ExprError(); 4361 } 4362 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4363 BaseExpr = LHSExp; // vectors: V[123] 4364 IndexExpr = RHSExp; 4365 VK = LHSExp->getValueKind(); 4366 if (VK != VK_RValue) 4367 OK = OK_VectorComponent; 4368 4369 // FIXME: need to deal with const... 4370 ResultType = VTy->getElementType(); 4371 } else if (LHSTy->isArrayType()) { 4372 // If we see an array that wasn't promoted by 4373 // DefaultFunctionArrayLvalueConversion, it must be an array that 4374 // wasn't promoted because of the C90 rule that doesn't 4375 // allow promoting non-lvalue arrays. Warn, then 4376 // force the promotion here. 4377 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4378 LHSExp->getSourceRange(); 4379 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4380 CK_ArrayToPointerDecay).get(); 4381 LHSTy = LHSExp->getType(); 4382 4383 BaseExpr = LHSExp; 4384 IndexExpr = RHSExp; 4385 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4386 } else if (RHSTy->isArrayType()) { 4387 // Same as previous, except for 123[f().a] case 4388 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4389 RHSExp->getSourceRange(); 4390 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4391 CK_ArrayToPointerDecay).get(); 4392 RHSTy = RHSExp->getType(); 4393 4394 BaseExpr = RHSExp; 4395 IndexExpr = LHSExp; 4396 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4397 } else { 4398 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4399 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4400 } 4401 // C99 6.5.2.1p1 4402 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4403 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4404 << IndexExpr->getSourceRange()); 4405 4406 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4407 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4408 && !IndexExpr->isTypeDependent()) 4409 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4410 4411 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4412 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4413 // type. Note that Functions are not objects, and that (in C99 parlance) 4414 // incomplete types are not object types. 4415 if (ResultType->isFunctionType()) { 4416 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4417 << ResultType << BaseExpr->getSourceRange(); 4418 return ExprError(); 4419 } 4420 4421 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4422 // GNU extension: subscripting on pointer to void 4423 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4424 << BaseExpr->getSourceRange(); 4425 4426 // C forbids expressions of unqualified void type from being l-values. 4427 // See IsCForbiddenLValueType. 4428 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4429 } else if (!ResultType->isDependentType() && 4430 RequireCompleteType(LLoc, ResultType, 4431 diag::err_subscript_incomplete_type, BaseExpr)) 4432 return ExprError(); 4433 4434 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4435 !ResultType.isCForbiddenLValueType()); 4436 4437 return new (Context) 4438 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4439 } 4440 4441 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4442 FunctionDecl *FD, 4443 ParmVarDecl *Param) { 4444 if (Param->hasUnparsedDefaultArg()) { 4445 Diag(CallLoc, 4446 diag::err_use_of_default_argument_to_function_declared_later) << 4447 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4448 Diag(UnparsedDefaultArgLocs[Param], 4449 diag::note_default_argument_declared_here); 4450 return ExprError(); 4451 } 4452 4453 if (Param->hasUninstantiatedDefaultArg()) { 4454 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4455 4456 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4457 Param); 4458 4459 // Instantiate the expression. 4460 MultiLevelTemplateArgumentList MutiLevelArgList 4461 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4462 4463 InstantiatingTemplate Inst(*this, CallLoc, Param, 4464 MutiLevelArgList.getInnermost()); 4465 if (Inst.isInvalid()) 4466 return ExprError(); 4467 4468 ExprResult Result; 4469 { 4470 // C++ [dcl.fct.default]p5: 4471 // The names in the [default argument] expression are bound, and 4472 // the semantic constraints are checked, at the point where the 4473 // default argument expression appears. 4474 ContextRAII SavedContext(*this, FD); 4475 LocalInstantiationScope Local(*this); 4476 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4477 } 4478 if (Result.isInvalid()) 4479 return ExprError(); 4480 4481 // Check the expression as an initializer for the parameter. 4482 InitializedEntity Entity 4483 = InitializedEntity::InitializeParameter(Context, Param); 4484 InitializationKind Kind 4485 = InitializationKind::CreateCopy(Param->getLocation(), 4486 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4487 Expr *ResultE = Result.getAs<Expr>(); 4488 4489 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4490 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4491 if (Result.isInvalid()) 4492 return ExprError(); 4493 4494 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4495 Param->getOuterLocStart()); 4496 if (Result.isInvalid()) 4497 return ExprError(); 4498 4499 // Remember the instantiated default argument. 4500 Param->setDefaultArg(Result.getAs<Expr>()); 4501 if (ASTMutationListener *L = getASTMutationListener()) { 4502 L->DefaultArgumentInstantiated(Param); 4503 } 4504 } 4505 4506 // If the default expression creates temporaries, we need to 4507 // push them to the current stack of expression temporaries so they'll 4508 // be properly destroyed. 4509 // FIXME: We should really be rebuilding the default argument with new 4510 // bound temporaries; see the comment in PR5810. 4511 // We don't need to do that with block decls, though, because 4512 // blocks in default argument expression can never capture anything. 4513 if (isa<ExprWithCleanups>(Param->getInit())) { 4514 // Set the "needs cleanups" bit regardless of whether there are 4515 // any explicit objects. 4516 ExprNeedsCleanups = true; 4517 4518 // Append all the objects to the cleanup list. Right now, this 4519 // should always be a no-op, because blocks in default argument 4520 // expressions should never be able to capture anything. 4521 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4522 "default argument expression has capturing blocks?"); 4523 } 4524 4525 // We already type-checked the argument, so we know it works. 4526 // Just mark all of the declarations in this potentially-evaluated expression 4527 // as being "referenced". 4528 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4529 /*SkipLocalVariables=*/true); 4530 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4531 } 4532 4533 4534 Sema::VariadicCallType 4535 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4536 Expr *Fn) { 4537 if (Proto && Proto->isVariadic()) { 4538 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4539 return VariadicConstructor; 4540 else if (Fn && Fn->getType()->isBlockPointerType()) 4541 return VariadicBlock; 4542 else if (FDecl) { 4543 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4544 if (Method->isInstance()) 4545 return VariadicMethod; 4546 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4547 return VariadicMethod; 4548 return VariadicFunction; 4549 } 4550 return VariadicDoesNotApply; 4551 } 4552 4553 namespace { 4554 class FunctionCallCCC : public FunctionCallFilterCCC { 4555 public: 4556 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4557 unsigned NumArgs, MemberExpr *ME) 4558 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4559 FunctionName(FuncName) {} 4560 4561 bool ValidateCandidate(const TypoCorrection &candidate) override { 4562 if (!candidate.getCorrectionSpecifier() || 4563 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4564 return false; 4565 } 4566 4567 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4568 } 4569 4570 private: 4571 const IdentifierInfo *const FunctionName; 4572 }; 4573 } 4574 4575 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4576 FunctionDecl *FDecl, 4577 ArrayRef<Expr *> Args) { 4578 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4579 DeclarationName FuncName = FDecl->getDeclName(); 4580 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4581 4582 if (TypoCorrection Corrected = S.CorrectTypo( 4583 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4584 S.getScopeForContext(S.CurContext), nullptr, 4585 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4586 Args.size(), ME), 4587 Sema::CTK_ErrorRecovery)) { 4588 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4589 if (Corrected.isOverloaded()) { 4590 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4591 OverloadCandidateSet::iterator Best; 4592 for (NamedDecl *CD : Corrected) { 4593 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4594 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4595 OCS); 4596 } 4597 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4598 case OR_Success: 4599 ND = Best->FoundDecl; 4600 Corrected.setCorrectionDecl(ND); 4601 break; 4602 default: 4603 break; 4604 } 4605 } 4606 ND = ND->getUnderlyingDecl(); 4607 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4608 return Corrected; 4609 } 4610 } 4611 return TypoCorrection(); 4612 } 4613 4614 /// ConvertArgumentsForCall - Converts the arguments specified in 4615 /// Args/NumArgs to the parameter types of the function FDecl with 4616 /// function prototype Proto. Call is the call expression itself, and 4617 /// Fn is the function expression. For a C++ member function, this 4618 /// routine does not attempt to convert the object argument. Returns 4619 /// true if the call is ill-formed. 4620 bool 4621 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4622 FunctionDecl *FDecl, 4623 const FunctionProtoType *Proto, 4624 ArrayRef<Expr *> Args, 4625 SourceLocation RParenLoc, 4626 bool IsExecConfig) { 4627 // Bail out early if calling a builtin with custom typechecking. 4628 if (FDecl) 4629 if (unsigned ID = FDecl->getBuiltinID()) 4630 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4631 return false; 4632 4633 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4634 // assignment, to the types of the corresponding parameter, ... 4635 unsigned NumParams = Proto->getNumParams(); 4636 bool Invalid = false; 4637 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4638 unsigned FnKind = Fn->getType()->isBlockPointerType() 4639 ? 1 /* block */ 4640 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4641 : 0 /* function */); 4642 4643 // If too few arguments are available (and we don't have default 4644 // arguments for the remaining parameters), don't make the call. 4645 if (Args.size() < NumParams) { 4646 if (Args.size() < MinArgs) { 4647 TypoCorrection TC; 4648 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4649 unsigned diag_id = 4650 MinArgs == NumParams && !Proto->isVariadic() 4651 ? diag::err_typecheck_call_too_few_args_suggest 4652 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4653 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4654 << static_cast<unsigned>(Args.size()) 4655 << TC.getCorrectionRange()); 4656 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4657 Diag(RParenLoc, 4658 MinArgs == NumParams && !Proto->isVariadic() 4659 ? diag::err_typecheck_call_too_few_args_one 4660 : diag::err_typecheck_call_too_few_args_at_least_one) 4661 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4662 else 4663 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4664 ? diag::err_typecheck_call_too_few_args 4665 : diag::err_typecheck_call_too_few_args_at_least) 4666 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4667 << Fn->getSourceRange(); 4668 4669 // Emit the location of the prototype. 4670 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4671 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4672 << FDecl; 4673 4674 return true; 4675 } 4676 Call->setNumArgs(Context, NumParams); 4677 } 4678 4679 // If too many are passed and not variadic, error on the extras and drop 4680 // them. 4681 if (Args.size() > NumParams) { 4682 if (!Proto->isVariadic()) { 4683 TypoCorrection TC; 4684 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4685 unsigned diag_id = 4686 MinArgs == NumParams && !Proto->isVariadic() 4687 ? diag::err_typecheck_call_too_many_args_suggest 4688 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4689 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4690 << static_cast<unsigned>(Args.size()) 4691 << TC.getCorrectionRange()); 4692 } else if (NumParams == 1 && FDecl && 4693 FDecl->getParamDecl(0)->getDeclName()) 4694 Diag(Args[NumParams]->getLocStart(), 4695 MinArgs == NumParams 4696 ? diag::err_typecheck_call_too_many_args_one 4697 : diag::err_typecheck_call_too_many_args_at_most_one) 4698 << FnKind << FDecl->getParamDecl(0) 4699 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4700 << SourceRange(Args[NumParams]->getLocStart(), 4701 Args.back()->getLocEnd()); 4702 else 4703 Diag(Args[NumParams]->getLocStart(), 4704 MinArgs == NumParams 4705 ? diag::err_typecheck_call_too_many_args 4706 : diag::err_typecheck_call_too_many_args_at_most) 4707 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4708 << Fn->getSourceRange() 4709 << SourceRange(Args[NumParams]->getLocStart(), 4710 Args.back()->getLocEnd()); 4711 4712 // Emit the location of the prototype. 4713 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4714 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4715 << FDecl; 4716 4717 // This deletes the extra arguments. 4718 Call->setNumArgs(Context, NumParams); 4719 return true; 4720 } 4721 } 4722 SmallVector<Expr *, 8> AllArgs; 4723 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4724 4725 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4726 Proto, 0, Args, AllArgs, CallType); 4727 if (Invalid) 4728 return true; 4729 unsigned TotalNumArgs = AllArgs.size(); 4730 for (unsigned i = 0; i < TotalNumArgs; ++i) 4731 Call->setArg(i, AllArgs[i]); 4732 4733 return false; 4734 } 4735 4736 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4737 const FunctionProtoType *Proto, 4738 unsigned FirstParam, ArrayRef<Expr *> Args, 4739 SmallVectorImpl<Expr *> &AllArgs, 4740 VariadicCallType CallType, bool AllowExplicit, 4741 bool IsListInitialization) { 4742 unsigned NumParams = Proto->getNumParams(); 4743 bool Invalid = false; 4744 size_t ArgIx = 0; 4745 // Continue to check argument types (even if we have too few/many args). 4746 for (unsigned i = FirstParam; i < NumParams; i++) { 4747 QualType ProtoArgType = Proto->getParamType(i); 4748 4749 Expr *Arg; 4750 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4751 if (ArgIx < Args.size()) { 4752 Arg = Args[ArgIx++]; 4753 4754 if (RequireCompleteType(Arg->getLocStart(), 4755 ProtoArgType, 4756 diag::err_call_incomplete_argument, Arg)) 4757 return true; 4758 4759 // Strip the unbridged-cast placeholder expression off, if applicable. 4760 bool CFAudited = false; 4761 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4762 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4763 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4764 Arg = stripARCUnbridgedCast(Arg); 4765 else if (getLangOpts().ObjCAutoRefCount && 4766 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4767 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4768 CFAudited = true; 4769 4770 InitializedEntity Entity = 4771 Param ? InitializedEntity::InitializeParameter(Context, Param, 4772 ProtoArgType) 4773 : InitializedEntity::InitializeParameter( 4774 Context, ProtoArgType, Proto->isParamConsumed(i)); 4775 4776 // Remember that parameter belongs to a CF audited API. 4777 if (CFAudited) 4778 Entity.setParameterCFAudited(); 4779 4780 ExprResult ArgE = PerformCopyInitialization( 4781 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4782 if (ArgE.isInvalid()) 4783 return true; 4784 4785 Arg = ArgE.getAs<Expr>(); 4786 } else { 4787 assert(Param && "can't use default arguments without a known callee"); 4788 4789 ExprResult ArgExpr = 4790 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4791 if (ArgExpr.isInvalid()) 4792 return true; 4793 4794 Arg = ArgExpr.getAs<Expr>(); 4795 } 4796 4797 // Check for array bounds violations for each argument to the call. This 4798 // check only triggers warnings when the argument isn't a more complex Expr 4799 // with its own checking, such as a BinaryOperator. 4800 CheckArrayAccess(Arg); 4801 4802 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4803 CheckStaticArrayArgument(CallLoc, Param, Arg); 4804 4805 AllArgs.push_back(Arg); 4806 } 4807 4808 // If this is a variadic call, handle args passed through "...". 4809 if (CallType != VariadicDoesNotApply) { 4810 // Assume that extern "C" functions with variadic arguments that 4811 // return __unknown_anytype aren't *really* variadic. 4812 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4813 FDecl->isExternC()) { 4814 for (Expr *A : Args.slice(ArgIx)) { 4815 QualType paramType; // ignored 4816 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4817 Invalid |= arg.isInvalid(); 4818 AllArgs.push_back(arg.get()); 4819 } 4820 4821 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4822 } else { 4823 for (Expr *A : Args.slice(ArgIx)) { 4824 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4825 Invalid |= Arg.isInvalid(); 4826 AllArgs.push_back(Arg.get()); 4827 } 4828 } 4829 4830 // Check for array bounds violations. 4831 for (Expr *A : Args.slice(ArgIx)) 4832 CheckArrayAccess(A); 4833 } 4834 return Invalid; 4835 } 4836 4837 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4838 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4839 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4840 TL = DTL.getOriginalLoc(); 4841 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4842 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4843 << ATL.getLocalSourceRange(); 4844 } 4845 4846 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4847 /// array parameter, check that it is non-null, and that if it is formed by 4848 /// array-to-pointer decay, the underlying array is sufficiently large. 4849 /// 4850 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4851 /// array type derivation, then for each call to the function, the value of the 4852 /// corresponding actual argument shall provide access to the first element of 4853 /// an array with at least as many elements as specified by the size expression. 4854 void 4855 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4856 ParmVarDecl *Param, 4857 const Expr *ArgExpr) { 4858 // Static array parameters are not supported in C++. 4859 if (!Param || getLangOpts().CPlusPlus) 4860 return; 4861 4862 QualType OrigTy = Param->getOriginalType(); 4863 4864 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4865 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4866 return; 4867 4868 if (ArgExpr->isNullPointerConstant(Context, 4869 Expr::NPC_NeverValueDependent)) { 4870 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4871 DiagnoseCalleeStaticArrayParam(*this, Param); 4872 return; 4873 } 4874 4875 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4876 if (!CAT) 4877 return; 4878 4879 const ConstantArrayType *ArgCAT = 4880 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4881 if (!ArgCAT) 4882 return; 4883 4884 if (ArgCAT->getSize().ult(CAT->getSize())) { 4885 Diag(CallLoc, diag::warn_static_array_too_small) 4886 << ArgExpr->getSourceRange() 4887 << (unsigned) ArgCAT->getSize().getZExtValue() 4888 << (unsigned) CAT->getSize().getZExtValue(); 4889 DiagnoseCalleeStaticArrayParam(*this, Param); 4890 } 4891 } 4892 4893 /// Given a function expression of unknown-any type, try to rebuild it 4894 /// to have a function type. 4895 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4896 4897 /// Is the given type a placeholder that we need to lower out 4898 /// immediately during argument processing? 4899 static bool isPlaceholderToRemoveAsArg(QualType type) { 4900 // Placeholders are never sugared. 4901 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4902 if (!placeholder) return false; 4903 4904 switch (placeholder->getKind()) { 4905 // Ignore all the non-placeholder types. 4906 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4907 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4908 #include "clang/AST/BuiltinTypes.def" 4909 return false; 4910 4911 // We cannot lower out overload sets; they might validly be resolved 4912 // by the call machinery. 4913 case BuiltinType::Overload: 4914 return false; 4915 4916 // Unbridged casts in ARC can be handled in some call positions and 4917 // should be left in place. 4918 case BuiltinType::ARCUnbridgedCast: 4919 return false; 4920 4921 // Pseudo-objects should be converted as soon as possible. 4922 case BuiltinType::PseudoObject: 4923 return true; 4924 4925 // The debugger mode could theoretically but currently does not try 4926 // to resolve unknown-typed arguments based on known parameter types. 4927 case BuiltinType::UnknownAny: 4928 return true; 4929 4930 // These are always invalid as call arguments and should be reported. 4931 case BuiltinType::BoundMember: 4932 case BuiltinType::BuiltinFn: 4933 case BuiltinType::OMPArraySection: 4934 return true; 4935 4936 } 4937 llvm_unreachable("bad builtin type kind"); 4938 } 4939 4940 /// Check an argument list for placeholders that we won't try to 4941 /// handle later. 4942 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4943 // Apply this processing to all the arguments at once instead of 4944 // dying at the first failure. 4945 bool hasInvalid = false; 4946 for (size_t i = 0, e = args.size(); i != e; i++) { 4947 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4948 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4949 if (result.isInvalid()) hasInvalid = true; 4950 else args[i] = result.get(); 4951 } else if (hasInvalid) { 4952 (void)S.CorrectDelayedTyposInExpr(args[i]); 4953 } 4954 } 4955 return hasInvalid; 4956 } 4957 4958 /// If a builtin function has a pointer argument with no explicit address 4959 /// space, then it should be able to accept a pointer to any address 4960 /// space as input. In order to do this, we need to replace the 4961 /// standard builtin declaration with one that uses the same address space 4962 /// as the call. 4963 /// 4964 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4965 /// it does not contain any pointer arguments without 4966 /// an address space qualifer. Otherwise the rewritten 4967 /// FunctionDecl is returned. 4968 /// TODO: Handle pointer return types. 4969 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4970 const FunctionDecl *FDecl, 4971 MultiExprArg ArgExprs) { 4972 4973 QualType DeclType = FDecl->getType(); 4974 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4975 4976 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4977 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4978 return nullptr; 4979 4980 bool NeedsNewDecl = false; 4981 unsigned i = 0; 4982 SmallVector<QualType, 8> OverloadParams; 4983 4984 for (QualType ParamType : FT->param_types()) { 4985 4986 // Convert array arguments to pointer to simplify type lookup. 4987 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4988 QualType ArgType = Arg->getType(); 4989 if (!ParamType->isPointerType() || 4990 ParamType.getQualifiers().hasAddressSpace() || 4991 !ArgType->isPointerType() || 4992 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4993 OverloadParams.push_back(ParamType); 4994 continue; 4995 } 4996 4997 NeedsNewDecl = true; 4998 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 4999 5000 QualType PointeeType = ParamType->getPointeeType(); 5001 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5002 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5003 } 5004 5005 if (!NeedsNewDecl) 5006 return nullptr; 5007 5008 FunctionProtoType::ExtProtoInfo EPI; 5009 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5010 OverloadParams, EPI); 5011 DeclContext *Parent = Context.getTranslationUnitDecl(); 5012 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5013 FDecl->getLocation(), 5014 FDecl->getLocation(), 5015 FDecl->getIdentifier(), 5016 OverloadTy, 5017 /*TInfo=*/nullptr, 5018 SC_Extern, false, 5019 /*hasPrototype=*/true); 5020 SmallVector<ParmVarDecl*, 16> Params; 5021 FT = cast<FunctionProtoType>(OverloadTy); 5022 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5023 QualType ParamType = FT->getParamType(i); 5024 ParmVarDecl *Parm = 5025 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5026 SourceLocation(), nullptr, ParamType, 5027 /*TInfo=*/nullptr, SC_None, nullptr); 5028 Parm->setScopeInfo(0, i); 5029 Params.push_back(Parm); 5030 } 5031 OverloadDecl->setParams(Params); 5032 return OverloadDecl; 5033 } 5034 5035 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5036 /// This provides the location of the left/right parens and a list of comma 5037 /// locations. 5038 ExprResult 5039 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5040 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5041 Expr *ExecConfig, bool IsExecConfig) { 5042 // Since this might be a postfix expression, get rid of ParenListExprs. 5043 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 5044 if (Result.isInvalid()) return ExprError(); 5045 Fn = Result.get(); 5046 5047 if (checkArgsForPlaceholders(*this, ArgExprs)) 5048 return ExprError(); 5049 5050 if (getLangOpts().CPlusPlus) { 5051 // If this is a pseudo-destructor expression, build the call immediately. 5052 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5053 if (!ArgExprs.empty()) { 5054 // Pseudo-destructor calls should not have any arguments. 5055 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5056 << FixItHint::CreateRemoval( 5057 SourceRange(ArgExprs.front()->getLocStart(), 5058 ArgExprs.back()->getLocEnd())); 5059 } 5060 5061 return new (Context) 5062 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5063 } 5064 if (Fn->getType() == Context.PseudoObjectTy) { 5065 ExprResult result = CheckPlaceholderExpr(Fn); 5066 if (result.isInvalid()) return ExprError(); 5067 Fn = result.get(); 5068 } 5069 5070 // Determine whether this is a dependent call inside a C++ template, 5071 // in which case we won't do any semantic analysis now. 5072 // FIXME: Will need to cache the results of name lookup (including ADL) in 5073 // Fn. 5074 bool Dependent = false; 5075 if (Fn->isTypeDependent()) 5076 Dependent = true; 5077 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5078 Dependent = true; 5079 5080 if (Dependent) { 5081 if (ExecConfig) { 5082 return new (Context) CUDAKernelCallExpr( 5083 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5084 Context.DependentTy, VK_RValue, RParenLoc); 5085 } else { 5086 return new (Context) CallExpr( 5087 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5088 } 5089 } 5090 5091 // Determine whether this is a call to an object (C++ [over.call.object]). 5092 if (Fn->getType()->isRecordType()) 5093 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 5094 RParenLoc); 5095 5096 if (Fn->getType() == Context.UnknownAnyTy) { 5097 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5098 if (result.isInvalid()) return ExprError(); 5099 Fn = result.get(); 5100 } 5101 5102 if (Fn->getType() == Context.BoundMemberTy) { 5103 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5104 } 5105 } 5106 5107 // Check for overloaded calls. This can happen even in C due to extensions. 5108 if (Fn->getType() == Context.OverloadTy) { 5109 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5110 5111 // We aren't supposed to apply this logic for if there's an '&' involved. 5112 if (!find.HasFormOfMemberPointer) { 5113 OverloadExpr *ovl = find.Expression; 5114 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5115 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 5116 RParenLoc, ExecConfig, 5117 /*AllowTypoCorrection=*/true, 5118 find.IsAddressOfOperand); 5119 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5120 } 5121 } 5122 5123 // If we're directly calling a function, get the appropriate declaration. 5124 if (Fn->getType() == Context.UnknownAnyTy) { 5125 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5126 if (result.isInvalid()) return ExprError(); 5127 Fn = result.get(); 5128 } 5129 5130 Expr *NakedFn = Fn->IgnoreParens(); 5131 5132 bool CallingNDeclIndirectly = false; 5133 NamedDecl *NDecl = nullptr; 5134 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5135 if (UnOp->getOpcode() == UO_AddrOf) { 5136 CallingNDeclIndirectly = true; 5137 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5138 } 5139 } 5140 5141 if (isa<DeclRefExpr>(NakedFn)) { 5142 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5143 5144 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5145 if (FDecl && FDecl->getBuiltinID()) { 5146 // Rewrite the function decl for this builtin by replacing parameters 5147 // with no explicit address space with the address space of the arguments 5148 // in ArgExprs. 5149 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5150 NDecl = FDecl; 5151 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 5152 SourceLocation(), FDecl, false, 5153 SourceLocation(), FDecl->getType(), 5154 Fn->getValueKind(), FDecl); 5155 } 5156 } 5157 } else if (isa<MemberExpr>(NakedFn)) 5158 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5159 5160 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5161 if (CallingNDeclIndirectly && 5162 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5163 Fn->getLocStart())) 5164 return ExprError(); 5165 5166 if (FD->hasAttr<EnableIfAttr>()) { 5167 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5168 Diag(Fn->getLocStart(), 5169 isa<CXXMethodDecl>(FD) ? 5170 diag::err_ovl_no_viable_member_function_in_call : 5171 diag::err_ovl_no_viable_function_in_call) 5172 << FD << FD->getSourceRange(); 5173 Diag(FD->getLocation(), 5174 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5175 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5176 } 5177 } 5178 } 5179 5180 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5181 ExecConfig, IsExecConfig); 5182 } 5183 5184 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5185 /// 5186 /// __builtin_astype( value, dst type ) 5187 /// 5188 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5189 SourceLocation BuiltinLoc, 5190 SourceLocation RParenLoc) { 5191 ExprValueKind VK = VK_RValue; 5192 ExprObjectKind OK = OK_Ordinary; 5193 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5194 QualType SrcTy = E->getType(); 5195 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5196 return ExprError(Diag(BuiltinLoc, 5197 diag::err_invalid_astype_of_different_size) 5198 << DstTy 5199 << SrcTy 5200 << E->getSourceRange()); 5201 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5202 } 5203 5204 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5205 /// provided arguments. 5206 /// 5207 /// __builtin_convertvector( value, dst type ) 5208 /// 5209 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5210 SourceLocation BuiltinLoc, 5211 SourceLocation RParenLoc) { 5212 TypeSourceInfo *TInfo; 5213 GetTypeFromParser(ParsedDestTy, &TInfo); 5214 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5215 } 5216 5217 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5218 /// i.e. an expression not of \p OverloadTy. The expression should 5219 /// unary-convert to an expression of function-pointer or 5220 /// block-pointer type. 5221 /// 5222 /// \param NDecl the declaration being called, if available 5223 ExprResult 5224 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5225 SourceLocation LParenLoc, 5226 ArrayRef<Expr *> Args, 5227 SourceLocation RParenLoc, 5228 Expr *Config, bool IsExecConfig) { 5229 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5230 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5231 5232 // Functions with 'interrupt' attribute cannot be called directly. 5233 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5234 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5235 return ExprError(); 5236 } 5237 5238 // Promote the function operand. 5239 // We special-case function promotion here because we only allow promoting 5240 // builtin functions to function pointers in the callee of a call. 5241 ExprResult Result; 5242 if (BuiltinID && 5243 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5244 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5245 CK_BuiltinFnToFnPtr).get(); 5246 } else { 5247 Result = CallExprUnaryConversions(Fn); 5248 } 5249 if (Result.isInvalid()) 5250 return ExprError(); 5251 Fn = Result.get(); 5252 5253 // Make the call expr early, before semantic checks. This guarantees cleanup 5254 // of arguments and function on error. 5255 CallExpr *TheCall; 5256 if (Config) 5257 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5258 cast<CallExpr>(Config), Args, 5259 Context.BoolTy, VK_RValue, 5260 RParenLoc); 5261 else 5262 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5263 VK_RValue, RParenLoc); 5264 5265 if (!getLangOpts().CPlusPlus) { 5266 // C cannot always handle TypoExpr nodes in builtin calls and direct 5267 // function calls as their argument checking don't necessarily handle 5268 // dependent types properly, so make sure any TypoExprs have been 5269 // dealt with. 5270 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5271 if (!Result.isUsable()) return ExprError(); 5272 TheCall = dyn_cast<CallExpr>(Result.get()); 5273 if (!TheCall) return Result; 5274 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5275 } 5276 5277 // Bail out early if calling a builtin with custom typechecking. 5278 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5279 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5280 5281 retry: 5282 const FunctionType *FuncT; 5283 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5284 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5285 // have type pointer to function". 5286 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5287 if (!FuncT) 5288 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5289 << Fn->getType() << Fn->getSourceRange()); 5290 } else if (const BlockPointerType *BPT = 5291 Fn->getType()->getAs<BlockPointerType>()) { 5292 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5293 } else { 5294 // Handle calls to expressions of unknown-any type. 5295 if (Fn->getType() == Context.UnknownAnyTy) { 5296 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5297 if (rewrite.isInvalid()) return ExprError(); 5298 Fn = rewrite.get(); 5299 TheCall->setCallee(Fn); 5300 goto retry; 5301 } 5302 5303 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5304 << Fn->getType() << Fn->getSourceRange()); 5305 } 5306 5307 if (getLangOpts().CUDA) { 5308 if (Config) { 5309 // CUDA: Kernel calls must be to global functions 5310 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5311 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5312 << FDecl->getName() << Fn->getSourceRange()); 5313 5314 // CUDA: Kernel function must have 'void' return type 5315 if (!FuncT->getReturnType()->isVoidType()) 5316 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5317 << Fn->getType() << Fn->getSourceRange()); 5318 } else { 5319 // CUDA: Calls to global functions must be configured 5320 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5321 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5322 << FDecl->getName() << Fn->getSourceRange()); 5323 } 5324 } 5325 5326 // Check for a valid return type 5327 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5328 FDecl)) 5329 return ExprError(); 5330 5331 // We know the result type of the call, set it. 5332 TheCall->setType(FuncT->getCallResultType(Context)); 5333 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5334 5335 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5336 if (Proto) { 5337 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5338 IsExecConfig)) 5339 return ExprError(); 5340 } else { 5341 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5342 5343 if (FDecl) { 5344 // Check if we have too few/too many template arguments, based 5345 // on our knowledge of the function definition. 5346 const FunctionDecl *Def = nullptr; 5347 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5348 Proto = Def->getType()->getAs<FunctionProtoType>(); 5349 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5350 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5351 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5352 } 5353 5354 // If the function we're calling isn't a function prototype, but we have 5355 // a function prototype from a prior declaratiom, use that prototype. 5356 if (!FDecl->hasPrototype()) 5357 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5358 } 5359 5360 // Promote the arguments (C99 6.5.2.2p6). 5361 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5362 Expr *Arg = Args[i]; 5363 5364 if (Proto && i < Proto->getNumParams()) { 5365 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5366 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5367 ExprResult ArgE = 5368 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5369 if (ArgE.isInvalid()) 5370 return true; 5371 5372 Arg = ArgE.getAs<Expr>(); 5373 5374 } else { 5375 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5376 5377 if (ArgE.isInvalid()) 5378 return true; 5379 5380 Arg = ArgE.getAs<Expr>(); 5381 } 5382 5383 if (RequireCompleteType(Arg->getLocStart(), 5384 Arg->getType(), 5385 diag::err_call_incomplete_argument, Arg)) 5386 return ExprError(); 5387 5388 TheCall->setArg(i, Arg); 5389 } 5390 } 5391 5392 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5393 if (!Method->isStatic()) 5394 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5395 << Fn->getSourceRange()); 5396 5397 // Check for sentinels 5398 if (NDecl) 5399 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5400 5401 // Do special checking on direct calls to functions. 5402 if (FDecl) { 5403 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5404 return ExprError(); 5405 5406 if (BuiltinID) 5407 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5408 } else if (NDecl) { 5409 if (CheckPointerCall(NDecl, TheCall, Proto)) 5410 return ExprError(); 5411 } else { 5412 if (CheckOtherCall(TheCall, Proto)) 5413 return ExprError(); 5414 } 5415 5416 return MaybeBindToTemporary(TheCall); 5417 } 5418 5419 ExprResult 5420 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5421 SourceLocation RParenLoc, Expr *InitExpr) { 5422 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5423 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5424 5425 TypeSourceInfo *TInfo; 5426 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5427 if (!TInfo) 5428 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5429 5430 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5431 } 5432 5433 ExprResult 5434 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5435 SourceLocation RParenLoc, Expr *LiteralExpr) { 5436 QualType literalType = TInfo->getType(); 5437 5438 if (literalType->isArrayType()) { 5439 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5440 diag::err_illegal_decl_array_incomplete_type, 5441 SourceRange(LParenLoc, 5442 LiteralExpr->getSourceRange().getEnd()))) 5443 return ExprError(); 5444 if (literalType->isVariableArrayType()) 5445 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5446 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5447 } else if (!literalType->isDependentType() && 5448 RequireCompleteType(LParenLoc, literalType, 5449 diag::err_typecheck_decl_incomplete_type, 5450 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5451 return ExprError(); 5452 5453 InitializedEntity Entity 5454 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5455 InitializationKind Kind 5456 = InitializationKind::CreateCStyleCast(LParenLoc, 5457 SourceRange(LParenLoc, RParenLoc), 5458 /*InitList=*/true); 5459 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5460 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5461 &literalType); 5462 if (Result.isInvalid()) 5463 return ExprError(); 5464 LiteralExpr = Result.get(); 5465 5466 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5467 if (isFileScope && 5468 !LiteralExpr->isTypeDependent() && 5469 !LiteralExpr->isValueDependent() && 5470 !literalType->isDependentType()) { // 6.5.2.5p3 5471 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5472 return ExprError(); 5473 } 5474 5475 // In C, compound literals are l-values for some reason. 5476 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5477 5478 return MaybeBindToTemporary( 5479 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5480 VK, LiteralExpr, isFileScope)); 5481 } 5482 5483 ExprResult 5484 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5485 SourceLocation RBraceLoc) { 5486 // Immediately handle non-overload placeholders. Overloads can be 5487 // resolved contextually, but everything else here can't. 5488 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5489 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5490 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5491 5492 // Ignore failures; dropping the entire initializer list because 5493 // of one failure would be terrible for indexing/etc. 5494 if (result.isInvalid()) continue; 5495 5496 InitArgList[I] = result.get(); 5497 } 5498 } 5499 5500 // Semantic analysis for initializers is done by ActOnDeclarator() and 5501 // CheckInitializer() - it requires knowledge of the object being intialized. 5502 5503 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5504 RBraceLoc); 5505 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5506 return E; 5507 } 5508 5509 /// Do an explicit extend of the given block pointer if we're in ARC. 5510 void Sema::maybeExtendBlockObject(ExprResult &E) { 5511 assert(E.get()->getType()->isBlockPointerType()); 5512 assert(E.get()->isRValue()); 5513 5514 // Only do this in an r-value context. 5515 if (!getLangOpts().ObjCAutoRefCount) return; 5516 5517 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5518 CK_ARCExtendBlockObject, E.get(), 5519 /*base path*/ nullptr, VK_RValue); 5520 ExprNeedsCleanups = true; 5521 } 5522 5523 /// Prepare a conversion of the given expression to an ObjC object 5524 /// pointer type. 5525 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5526 QualType type = E.get()->getType(); 5527 if (type->isObjCObjectPointerType()) { 5528 return CK_BitCast; 5529 } else if (type->isBlockPointerType()) { 5530 maybeExtendBlockObject(E); 5531 return CK_BlockPointerToObjCPointerCast; 5532 } else { 5533 assert(type->isPointerType()); 5534 return CK_CPointerToObjCPointerCast; 5535 } 5536 } 5537 5538 /// Prepares for a scalar cast, performing all the necessary stages 5539 /// except the final cast and returning the kind required. 5540 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5541 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5542 // Also, callers should have filtered out the invalid cases with 5543 // pointers. Everything else should be possible. 5544 5545 QualType SrcTy = Src.get()->getType(); 5546 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5547 return CK_NoOp; 5548 5549 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5550 case Type::STK_MemberPointer: 5551 llvm_unreachable("member pointer type in C"); 5552 5553 case Type::STK_CPointer: 5554 case Type::STK_BlockPointer: 5555 case Type::STK_ObjCObjectPointer: 5556 switch (DestTy->getScalarTypeKind()) { 5557 case Type::STK_CPointer: { 5558 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5559 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5560 if (SrcAS != DestAS) 5561 return CK_AddressSpaceConversion; 5562 return CK_BitCast; 5563 } 5564 case Type::STK_BlockPointer: 5565 return (SrcKind == Type::STK_BlockPointer 5566 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5567 case Type::STK_ObjCObjectPointer: 5568 if (SrcKind == Type::STK_ObjCObjectPointer) 5569 return CK_BitCast; 5570 if (SrcKind == Type::STK_CPointer) 5571 return CK_CPointerToObjCPointerCast; 5572 maybeExtendBlockObject(Src); 5573 return CK_BlockPointerToObjCPointerCast; 5574 case Type::STK_Bool: 5575 return CK_PointerToBoolean; 5576 case Type::STK_Integral: 5577 return CK_PointerToIntegral; 5578 case Type::STK_Floating: 5579 case Type::STK_FloatingComplex: 5580 case Type::STK_IntegralComplex: 5581 case Type::STK_MemberPointer: 5582 llvm_unreachable("illegal cast from pointer"); 5583 } 5584 llvm_unreachable("Should have returned before this"); 5585 5586 case Type::STK_Bool: // casting from bool is like casting from an integer 5587 case Type::STK_Integral: 5588 switch (DestTy->getScalarTypeKind()) { 5589 case Type::STK_CPointer: 5590 case Type::STK_ObjCObjectPointer: 5591 case Type::STK_BlockPointer: 5592 if (Src.get()->isNullPointerConstant(Context, 5593 Expr::NPC_ValueDependentIsNull)) 5594 return CK_NullToPointer; 5595 return CK_IntegralToPointer; 5596 case Type::STK_Bool: 5597 return CK_IntegralToBoolean; 5598 case Type::STK_Integral: 5599 return CK_IntegralCast; 5600 case Type::STK_Floating: 5601 return CK_IntegralToFloating; 5602 case Type::STK_IntegralComplex: 5603 Src = ImpCastExprToType(Src.get(), 5604 DestTy->castAs<ComplexType>()->getElementType(), 5605 CK_IntegralCast); 5606 return CK_IntegralRealToComplex; 5607 case Type::STK_FloatingComplex: 5608 Src = ImpCastExprToType(Src.get(), 5609 DestTy->castAs<ComplexType>()->getElementType(), 5610 CK_IntegralToFloating); 5611 return CK_FloatingRealToComplex; 5612 case Type::STK_MemberPointer: 5613 llvm_unreachable("member pointer type in C"); 5614 } 5615 llvm_unreachable("Should have returned before this"); 5616 5617 case Type::STK_Floating: 5618 switch (DestTy->getScalarTypeKind()) { 5619 case Type::STK_Floating: 5620 return CK_FloatingCast; 5621 case Type::STK_Bool: 5622 return CK_FloatingToBoolean; 5623 case Type::STK_Integral: 5624 return CK_FloatingToIntegral; 5625 case Type::STK_FloatingComplex: 5626 Src = ImpCastExprToType(Src.get(), 5627 DestTy->castAs<ComplexType>()->getElementType(), 5628 CK_FloatingCast); 5629 return CK_FloatingRealToComplex; 5630 case Type::STK_IntegralComplex: 5631 Src = ImpCastExprToType(Src.get(), 5632 DestTy->castAs<ComplexType>()->getElementType(), 5633 CK_FloatingToIntegral); 5634 return CK_IntegralRealToComplex; 5635 case Type::STK_CPointer: 5636 case Type::STK_ObjCObjectPointer: 5637 case Type::STK_BlockPointer: 5638 llvm_unreachable("valid float->pointer cast?"); 5639 case Type::STK_MemberPointer: 5640 llvm_unreachable("member pointer type in C"); 5641 } 5642 llvm_unreachable("Should have returned before this"); 5643 5644 case Type::STK_FloatingComplex: 5645 switch (DestTy->getScalarTypeKind()) { 5646 case Type::STK_FloatingComplex: 5647 return CK_FloatingComplexCast; 5648 case Type::STK_IntegralComplex: 5649 return CK_FloatingComplexToIntegralComplex; 5650 case Type::STK_Floating: { 5651 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5652 if (Context.hasSameType(ET, DestTy)) 5653 return CK_FloatingComplexToReal; 5654 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5655 return CK_FloatingCast; 5656 } 5657 case Type::STK_Bool: 5658 return CK_FloatingComplexToBoolean; 5659 case Type::STK_Integral: 5660 Src = ImpCastExprToType(Src.get(), 5661 SrcTy->castAs<ComplexType>()->getElementType(), 5662 CK_FloatingComplexToReal); 5663 return CK_FloatingToIntegral; 5664 case Type::STK_CPointer: 5665 case Type::STK_ObjCObjectPointer: 5666 case Type::STK_BlockPointer: 5667 llvm_unreachable("valid complex float->pointer cast?"); 5668 case Type::STK_MemberPointer: 5669 llvm_unreachable("member pointer type in C"); 5670 } 5671 llvm_unreachable("Should have returned before this"); 5672 5673 case Type::STK_IntegralComplex: 5674 switch (DestTy->getScalarTypeKind()) { 5675 case Type::STK_FloatingComplex: 5676 return CK_IntegralComplexToFloatingComplex; 5677 case Type::STK_IntegralComplex: 5678 return CK_IntegralComplexCast; 5679 case Type::STK_Integral: { 5680 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5681 if (Context.hasSameType(ET, DestTy)) 5682 return CK_IntegralComplexToReal; 5683 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5684 return CK_IntegralCast; 5685 } 5686 case Type::STK_Bool: 5687 return CK_IntegralComplexToBoolean; 5688 case Type::STK_Floating: 5689 Src = ImpCastExprToType(Src.get(), 5690 SrcTy->castAs<ComplexType>()->getElementType(), 5691 CK_IntegralComplexToReal); 5692 return CK_IntegralToFloating; 5693 case Type::STK_CPointer: 5694 case Type::STK_ObjCObjectPointer: 5695 case Type::STK_BlockPointer: 5696 llvm_unreachable("valid complex int->pointer cast?"); 5697 case Type::STK_MemberPointer: 5698 llvm_unreachable("member pointer type in C"); 5699 } 5700 llvm_unreachable("Should have returned before this"); 5701 } 5702 5703 llvm_unreachable("Unhandled scalar cast"); 5704 } 5705 5706 static bool breakDownVectorType(QualType type, uint64_t &len, 5707 QualType &eltType) { 5708 // Vectors are simple. 5709 if (const VectorType *vecType = type->getAs<VectorType>()) { 5710 len = vecType->getNumElements(); 5711 eltType = vecType->getElementType(); 5712 assert(eltType->isScalarType()); 5713 return true; 5714 } 5715 5716 // We allow lax conversion to and from non-vector types, but only if 5717 // they're real types (i.e. non-complex, non-pointer scalar types). 5718 if (!type->isRealType()) return false; 5719 5720 len = 1; 5721 eltType = type; 5722 return true; 5723 } 5724 5725 /// Are the two types lax-compatible vector types? That is, given 5726 /// that one of them is a vector, do they have equal storage sizes, 5727 /// where the storage size is the number of elements times the element 5728 /// size? 5729 /// 5730 /// This will also return false if either of the types is neither a 5731 /// vector nor a real type. 5732 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5733 assert(destTy->isVectorType() || srcTy->isVectorType()); 5734 5735 // Disallow lax conversions between scalars and ExtVectors (these 5736 // conversions are allowed for other vector types because common headers 5737 // depend on them). Most scalar OP ExtVector cases are handled by the 5738 // splat path anyway, which does what we want (convert, not bitcast). 5739 // What this rules out for ExtVectors is crazy things like char4*float. 5740 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5741 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5742 5743 uint64_t srcLen, destLen; 5744 QualType srcEltTy, destEltTy; 5745 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5746 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5747 5748 // ASTContext::getTypeSize will return the size rounded up to a 5749 // power of 2, so instead of using that, we need to use the raw 5750 // element size multiplied by the element count. 5751 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5752 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5753 5754 return (srcLen * srcEltSize == destLen * destEltSize); 5755 } 5756 5757 /// Is this a legal conversion between two types, one of which is 5758 /// known to be a vector type? 5759 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5760 assert(destTy->isVectorType() || srcTy->isVectorType()); 5761 5762 if (!Context.getLangOpts().LaxVectorConversions) 5763 return false; 5764 return areLaxCompatibleVectorTypes(srcTy, destTy); 5765 } 5766 5767 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5768 CastKind &Kind) { 5769 assert(VectorTy->isVectorType() && "Not a vector type!"); 5770 5771 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5772 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5773 return Diag(R.getBegin(), 5774 Ty->isVectorType() ? 5775 diag::err_invalid_conversion_between_vectors : 5776 diag::err_invalid_conversion_between_vector_and_integer) 5777 << VectorTy << Ty << R; 5778 } else 5779 return Diag(R.getBegin(), 5780 diag::err_invalid_conversion_between_vector_and_scalar) 5781 << VectorTy << Ty << R; 5782 5783 Kind = CK_BitCast; 5784 return false; 5785 } 5786 5787 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5788 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5789 5790 if (DestElemTy == SplattedExpr->getType()) 5791 return SplattedExpr; 5792 5793 assert(DestElemTy->isFloatingType() || 5794 DestElemTy->isIntegralOrEnumerationType()); 5795 5796 CastKind CK; 5797 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5798 // OpenCL requires that we convert `true` boolean expressions to -1, but 5799 // only when splatting vectors. 5800 if (DestElemTy->isFloatingType()) { 5801 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5802 // in two steps: boolean to signed integral, then to floating. 5803 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5804 CK_BooleanToSignedIntegral); 5805 SplattedExpr = CastExprRes.get(); 5806 CK = CK_IntegralToFloating; 5807 } else { 5808 CK = CK_BooleanToSignedIntegral; 5809 } 5810 } else { 5811 ExprResult CastExprRes = SplattedExpr; 5812 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5813 if (CastExprRes.isInvalid()) 5814 return ExprError(); 5815 SplattedExpr = CastExprRes.get(); 5816 } 5817 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5818 } 5819 5820 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5821 Expr *CastExpr, CastKind &Kind) { 5822 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5823 5824 QualType SrcTy = CastExpr->getType(); 5825 5826 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5827 // an ExtVectorType. 5828 // In OpenCL, casts between vectors of different types are not allowed. 5829 // (See OpenCL 6.2). 5830 if (SrcTy->isVectorType()) { 5831 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5832 || (getLangOpts().OpenCL && 5833 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5834 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5835 << DestTy << SrcTy << R; 5836 return ExprError(); 5837 } 5838 Kind = CK_BitCast; 5839 return CastExpr; 5840 } 5841 5842 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5843 // conversion will take place first from scalar to elt type, and then 5844 // splat from elt type to vector. 5845 if (SrcTy->isPointerType()) 5846 return Diag(R.getBegin(), 5847 diag::err_invalid_conversion_between_vector_and_scalar) 5848 << DestTy << SrcTy << R; 5849 5850 Kind = CK_VectorSplat; 5851 return prepareVectorSplat(DestTy, CastExpr); 5852 } 5853 5854 ExprResult 5855 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5856 Declarator &D, ParsedType &Ty, 5857 SourceLocation RParenLoc, Expr *CastExpr) { 5858 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5859 "ActOnCastExpr(): missing type or expr"); 5860 5861 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5862 if (D.isInvalidType()) 5863 return ExprError(); 5864 5865 if (getLangOpts().CPlusPlus) { 5866 // Check that there are no default arguments (C++ only). 5867 CheckExtraCXXDefaultArguments(D); 5868 } else { 5869 // Make sure any TypoExprs have been dealt with. 5870 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5871 if (!Res.isUsable()) 5872 return ExprError(); 5873 CastExpr = Res.get(); 5874 } 5875 5876 checkUnusedDeclAttributes(D); 5877 5878 QualType castType = castTInfo->getType(); 5879 Ty = CreateParsedType(castType, castTInfo); 5880 5881 bool isVectorLiteral = false; 5882 5883 // Check for an altivec or OpenCL literal, 5884 // i.e. all the elements are integer constants. 5885 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5886 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5887 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5888 && castType->isVectorType() && (PE || PLE)) { 5889 if (PLE && PLE->getNumExprs() == 0) { 5890 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5891 return ExprError(); 5892 } 5893 if (PE || PLE->getNumExprs() == 1) { 5894 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5895 if (!E->getType()->isVectorType()) 5896 isVectorLiteral = true; 5897 } 5898 else 5899 isVectorLiteral = true; 5900 } 5901 5902 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5903 // then handle it as such. 5904 if (isVectorLiteral) 5905 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5906 5907 // If the Expr being casted is a ParenListExpr, handle it specially. 5908 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5909 // sequence of BinOp comma operators. 5910 if (isa<ParenListExpr>(CastExpr)) { 5911 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5912 if (Result.isInvalid()) return ExprError(); 5913 CastExpr = Result.get(); 5914 } 5915 5916 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5917 !getSourceManager().isInSystemMacro(LParenLoc)) 5918 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5919 5920 CheckTollFreeBridgeCast(castType, CastExpr); 5921 5922 CheckObjCBridgeRelatedCast(castType, CastExpr); 5923 5924 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5925 } 5926 5927 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5928 SourceLocation RParenLoc, Expr *E, 5929 TypeSourceInfo *TInfo) { 5930 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5931 "Expected paren or paren list expression"); 5932 5933 Expr **exprs; 5934 unsigned numExprs; 5935 Expr *subExpr; 5936 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5937 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5938 LiteralLParenLoc = PE->getLParenLoc(); 5939 LiteralRParenLoc = PE->getRParenLoc(); 5940 exprs = PE->getExprs(); 5941 numExprs = PE->getNumExprs(); 5942 } else { // isa<ParenExpr> by assertion at function entrance 5943 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5944 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5945 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5946 exprs = &subExpr; 5947 numExprs = 1; 5948 } 5949 5950 QualType Ty = TInfo->getType(); 5951 assert(Ty->isVectorType() && "Expected vector type"); 5952 5953 SmallVector<Expr *, 8> initExprs; 5954 const VectorType *VTy = Ty->getAs<VectorType>(); 5955 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5956 5957 // '(...)' form of vector initialization in AltiVec: the number of 5958 // initializers must be one or must match the size of the vector. 5959 // If a single value is specified in the initializer then it will be 5960 // replicated to all the components of the vector 5961 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5962 // The number of initializers must be one or must match the size of the 5963 // vector. If a single value is specified in the initializer then it will 5964 // be replicated to all the components of the vector 5965 if (numExprs == 1) { 5966 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5967 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5968 if (Literal.isInvalid()) 5969 return ExprError(); 5970 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5971 PrepareScalarCast(Literal, ElemTy)); 5972 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5973 } 5974 else if (numExprs < numElems) { 5975 Diag(E->getExprLoc(), 5976 diag::err_incorrect_number_of_vector_initializers); 5977 return ExprError(); 5978 } 5979 else 5980 initExprs.append(exprs, exprs + numExprs); 5981 } 5982 else { 5983 // For OpenCL, when the number of initializers is a single value, 5984 // it will be replicated to all components of the vector. 5985 if (getLangOpts().OpenCL && 5986 VTy->getVectorKind() == VectorType::GenericVector && 5987 numExprs == 1) { 5988 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5989 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5990 if (Literal.isInvalid()) 5991 return ExprError(); 5992 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5993 PrepareScalarCast(Literal, ElemTy)); 5994 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5995 } 5996 5997 initExprs.append(exprs, exprs + numExprs); 5998 } 5999 // FIXME: This means that pretty-printing the final AST will produce curly 6000 // braces instead of the original commas. 6001 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6002 initExprs, LiteralRParenLoc); 6003 initE->setType(Ty); 6004 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6005 } 6006 6007 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6008 /// the ParenListExpr into a sequence of comma binary operators. 6009 ExprResult 6010 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6011 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6012 if (!E) 6013 return OrigExpr; 6014 6015 ExprResult Result(E->getExpr(0)); 6016 6017 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6018 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6019 E->getExpr(i)); 6020 6021 if (Result.isInvalid()) return ExprError(); 6022 6023 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6024 } 6025 6026 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6027 SourceLocation R, 6028 MultiExprArg Val) { 6029 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6030 return expr; 6031 } 6032 6033 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6034 /// constant and the other is not a pointer. Returns true if a diagnostic is 6035 /// emitted. 6036 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6037 SourceLocation QuestionLoc) { 6038 Expr *NullExpr = LHSExpr; 6039 Expr *NonPointerExpr = RHSExpr; 6040 Expr::NullPointerConstantKind NullKind = 6041 NullExpr->isNullPointerConstant(Context, 6042 Expr::NPC_ValueDependentIsNotNull); 6043 6044 if (NullKind == Expr::NPCK_NotNull) { 6045 NullExpr = RHSExpr; 6046 NonPointerExpr = LHSExpr; 6047 NullKind = 6048 NullExpr->isNullPointerConstant(Context, 6049 Expr::NPC_ValueDependentIsNotNull); 6050 } 6051 6052 if (NullKind == Expr::NPCK_NotNull) 6053 return false; 6054 6055 if (NullKind == Expr::NPCK_ZeroExpression) 6056 return false; 6057 6058 if (NullKind == Expr::NPCK_ZeroLiteral) { 6059 // In this case, check to make sure that we got here from a "NULL" 6060 // string in the source code. 6061 NullExpr = NullExpr->IgnoreParenImpCasts(); 6062 SourceLocation loc = NullExpr->getExprLoc(); 6063 if (!findMacroSpelling(loc, "NULL")) 6064 return false; 6065 } 6066 6067 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6068 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6069 << NonPointerExpr->getType() << DiagType 6070 << NonPointerExpr->getSourceRange(); 6071 return true; 6072 } 6073 6074 /// \brief Return false if the condition expression is valid, true otherwise. 6075 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6076 QualType CondTy = Cond->getType(); 6077 6078 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6079 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6080 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6081 << CondTy << Cond->getSourceRange(); 6082 return true; 6083 } 6084 6085 // C99 6.5.15p2 6086 if (CondTy->isScalarType()) return false; 6087 6088 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6089 << CondTy << Cond->getSourceRange(); 6090 return true; 6091 } 6092 6093 /// \brief Handle when one or both operands are void type. 6094 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6095 ExprResult &RHS) { 6096 Expr *LHSExpr = LHS.get(); 6097 Expr *RHSExpr = RHS.get(); 6098 6099 if (!LHSExpr->getType()->isVoidType()) 6100 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6101 << RHSExpr->getSourceRange(); 6102 if (!RHSExpr->getType()->isVoidType()) 6103 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6104 << LHSExpr->getSourceRange(); 6105 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6106 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6107 return S.Context.VoidTy; 6108 } 6109 6110 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6111 /// true otherwise. 6112 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6113 QualType PointerTy) { 6114 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6115 !NullExpr.get()->isNullPointerConstant(S.Context, 6116 Expr::NPC_ValueDependentIsNull)) 6117 return true; 6118 6119 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6120 return false; 6121 } 6122 6123 /// \brief Checks compatibility between two pointers and return the resulting 6124 /// type. 6125 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6126 ExprResult &RHS, 6127 SourceLocation Loc) { 6128 QualType LHSTy = LHS.get()->getType(); 6129 QualType RHSTy = RHS.get()->getType(); 6130 6131 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6132 // Two identical pointers types are always compatible. 6133 return LHSTy; 6134 } 6135 6136 QualType lhptee, rhptee; 6137 6138 // Get the pointee types. 6139 bool IsBlockPointer = false; 6140 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6141 lhptee = LHSBTy->getPointeeType(); 6142 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6143 IsBlockPointer = true; 6144 } else { 6145 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6146 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6147 } 6148 6149 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6150 // differently qualified versions of compatible types, the result type is 6151 // a pointer to an appropriately qualified version of the composite 6152 // type. 6153 6154 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6155 // clause doesn't make sense for our extensions. E.g. address space 2 should 6156 // be incompatible with address space 3: they may live on different devices or 6157 // anything. 6158 Qualifiers lhQual = lhptee.getQualifiers(); 6159 Qualifiers rhQual = rhptee.getQualifiers(); 6160 6161 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6162 lhQual.removeCVRQualifiers(); 6163 rhQual.removeCVRQualifiers(); 6164 6165 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6166 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6167 6168 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6169 6170 if (CompositeTy.isNull()) { 6171 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6172 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6173 << RHS.get()->getSourceRange(); 6174 // In this situation, we assume void* type. No especially good 6175 // reason, but this is what gcc does, and we do have to pick 6176 // to get a consistent AST. 6177 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6178 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6179 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6180 return incompatTy; 6181 } 6182 6183 // The pointer types are compatible. 6184 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6185 if (IsBlockPointer) 6186 ResultTy = S.Context.getBlockPointerType(ResultTy); 6187 else 6188 ResultTy = S.Context.getPointerType(ResultTy); 6189 6190 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 6191 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 6192 return ResultTy; 6193 } 6194 6195 /// \brief Return the resulting type when the operands are both block pointers. 6196 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6197 ExprResult &LHS, 6198 ExprResult &RHS, 6199 SourceLocation Loc) { 6200 QualType LHSTy = LHS.get()->getType(); 6201 QualType RHSTy = RHS.get()->getType(); 6202 6203 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6204 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6205 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6206 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6207 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6208 return destType; 6209 } 6210 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6211 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6212 << RHS.get()->getSourceRange(); 6213 return QualType(); 6214 } 6215 6216 // We have 2 block pointer types. 6217 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6218 } 6219 6220 /// \brief Return the resulting type when the operands are both pointers. 6221 static QualType 6222 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6223 ExprResult &RHS, 6224 SourceLocation Loc) { 6225 // get the pointer types 6226 QualType LHSTy = LHS.get()->getType(); 6227 QualType RHSTy = RHS.get()->getType(); 6228 6229 // get the "pointed to" types 6230 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6231 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6232 6233 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6234 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6235 // Figure out necessary qualifiers (C99 6.5.15p6) 6236 QualType destPointee 6237 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6238 QualType destType = S.Context.getPointerType(destPointee); 6239 // Add qualifiers if necessary. 6240 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6241 // Promote to void*. 6242 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6243 return destType; 6244 } 6245 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6246 QualType destPointee 6247 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6248 QualType destType = S.Context.getPointerType(destPointee); 6249 // Add qualifiers if necessary. 6250 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6251 // Promote to void*. 6252 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6253 return destType; 6254 } 6255 6256 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6257 } 6258 6259 /// \brief Return false if the first expression is not an integer and the second 6260 /// expression is not a pointer, true otherwise. 6261 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6262 Expr* PointerExpr, SourceLocation Loc, 6263 bool IsIntFirstExpr) { 6264 if (!PointerExpr->getType()->isPointerType() || 6265 !Int.get()->getType()->isIntegerType()) 6266 return false; 6267 6268 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6269 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6270 6271 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6272 << Expr1->getType() << Expr2->getType() 6273 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6274 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6275 CK_IntegralToPointer); 6276 return true; 6277 } 6278 6279 /// \brief Simple conversion between integer and floating point types. 6280 /// 6281 /// Used when handling the OpenCL conditional operator where the 6282 /// condition is a vector while the other operands are scalar. 6283 /// 6284 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6285 /// types are either integer or floating type. Between the two 6286 /// operands, the type with the higher rank is defined as the "result 6287 /// type". The other operand needs to be promoted to the same type. No 6288 /// other type promotion is allowed. We cannot use 6289 /// UsualArithmeticConversions() for this purpose, since it always 6290 /// promotes promotable types. 6291 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6292 ExprResult &RHS, 6293 SourceLocation QuestionLoc) { 6294 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6295 if (LHS.isInvalid()) 6296 return QualType(); 6297 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6298 if (RHS.isInvalid()) 6299 return QualType(); 6300 6301 // For conversion purposes, we ignore any qualifiers. 6302 // For example, "const float" and "float" are equivalent. 6303 QualType LHSType = 6304 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6305 QualType RHSType = 6306 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6307 6308 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6309 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6310 << LHSType << LHS.get()->getSourceRange(); 6311 return QualType(); 6312 } 6313 6314 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6315 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6316 << RHSType << RHS.get()->getSourceRange(); 6317 return QualType(); 6318 } 6319 6320 // If both types are identical, no conversion is needed. 6321 if (LHSType == RHSType) 6322 return LHSType; 6323 6324 // Now handle "real" floating types (i.e. float, double, long double). 6325 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6326 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6327 /*IsCompAssign = */ false); 6328 6329 // Finally, we have two differing integer types. 6330 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6331 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6332 } 6333 6334 /// \brief Convert scalar operands to a vector that matches the 6335 /// condition in length. 6336 /// 6337 /// Used when handling the OpenCL conditional operator where the 6338 /// condition is a vector while the other operands are scalar. 6339 /// 6340 /// We first compute the "result type" for the scalar operands 6341 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6342 /// into a vector of that type where the length matches the condition 6343 /// vector type. s6.11.6 requires that the element types of the result 6344 /// and the condition must have the same number of bits. 6345 static QualType 6346 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6347 QualType CondTy, SourceLocation QuestionLoc) { 6348 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6349 if (ResTy.isNull()) return QualType(); 6350 6351 const VectorType *CV = CondTy->getAs<VectorType>(); 6352 assert(CV); 6353 6354 // Determine the vector result type 6355 unsigned NumElements = CV->getNumElements(); 6356 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6357 6358 // Ensure that all types have the same number of bits 6359 if (S.Context.getTypeSize(CV->getElementType()) 6360 != S.Context.getTypeSize(ResTy)) { 6361 // Since VectorTy is created internally, it does not pretty print 6362 // with an OpenCL name. Instead, we just print a description. 6363 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6364 SmallString<64> Str; 6365 llvm::raw_svector_ostream OS(Str); 6366 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6367 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6368 << CondTy << OS.str(); 6369 return QualType(); 6370 } 6371 6372 // Convert operands to the vector result type 6373 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6374 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6375 6376 return VectorTy; 6377 } 6378 6379 /// \brief Return false if this is a valid OpenCL condition vector 6380 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6381 SourceLocation QuestionLoc) { 6382 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6383 // integral type. 6384 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6385 assert(CondTy); 6386 QualType EleTy = CondTy->getElementType(); 6387 if (EleTy->isIntegerType()) return false; 6388 6389 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6390 << Cond->getType() << Cond->getSourceRange(); 6391 return true; 6392 } 6393 6394 /// \brief Return false if the vector condition type and the vector 6395 /// result type are compatible. 6396 /// 6397 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6398 /// number of elements, and their element types have the same number 6399 /// of bits. 6400 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6401 SourceLocation QuestionLoc) { 6402 const VectorType *CV = CondTy->getAs<VectorType>(); 6403 const VectorType *RV = VecResTy->getAs<VectorType>(); 6404 assert(CV && RV); 6405 6406 if (CV->getNumElements() != RV->getNumElements()) { 6407 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6408 << CondTy << VecResTy; 6409 return true; 6410 } 6411 6412 QualType CVE = CV->getElementType(); 6413 QualType RVE = RV->getElementType(); 6414 6415 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6416 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6417 << CondTy << VecResTy; 6418 return true; 6419 } 6420 6421 return false; 6422 } 6423 6424 /// \brief Return the resulting type for the conditional operator in 6425 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6426 /// s6.3.i) when the condition is a vector type. 6427 static QualType 6428 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6429 ExprResult &LHS, ExprResult &RHS, 6430 SourceLocation QuestionLoc) { 6431 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6432 if (Cond.isInvalid()) 6433 return QualType(); 6434 QualType CondTy = Cond.get()->getType(); 6435 6436 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6437 return QualType(); 6438 6439 // If either operand is a vector then find the vector type of the 6440 // result as specified in OpenCL v1.1 s6.3.i. 6441 if (LHS.get()->getType()->isVectorType() || 6442 RHS.get()->getType()->isVectorType()) { 6443 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6444 /*isCompAssign*/false, 6445 /*AllowBothBool*/true, 6446 /*AllowBoolConversions*/false); 6447 if (VecResTy.isNull()) return QualType(); 6448 // The result type must match the condition type as specified in 6449 // OpenCL v1.1 s6.11.6. 6450 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6451 return QualType(); 6452 return VecResTy; 6453 } 6454 6455 // Both operands are scalar. 6456 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6457 } 6458 6459 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6460 /// In that case, LHS = cond. 6461 /// C99 6.5.15 6462 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6463 ExprResult &RHS, ExprValueKind &VK, 6464 ExprObjectKind &OK, 6465 SourceLocation QuestionLoc) { 6466 6467 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6468 if (!LHSResult.isUsable()) return QualType(); 6469 LHS = LHSResult; 6470 6471 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6472 if (!RHSResult.isUsable()) return QualType(); 6473 RHS = RHSResult; 6474 6475 // C++ is sufficiently different to merit its own checker. 6476 if (getLangOpts().CPlusPlus) 6477 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6478 6479 VK = VK_RValue; 6480 OK = OK_Ordinary; 6481 6482 // The OpenCL operator with a vector condition is sufficiently 6483 // different to merit its own checker. 6484 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6485 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6486 6487 // First, check the condition. 6488 Cond = UsualUnaryConversions(Cond.get()); 6489 if (Cond.isInvalid()) 6490 return QualType(); 6491 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6492 return QualType(); 6493 6494 // Now check the two expressions. 6495 if (LHS.get()->getType()->isVectorType() || 6496 RHS.get()->getType()->isVectorType()) 6497 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6498 /*AllowBothBool*/true, 6499 /*AllowBoolConversions*/false); 6500 6501 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6502 if (LHS.isInvalid() || RHS.isInvalid()) 6503 return QualType(); 6504 6505 QualType LHSTy = LHS.get()->getType(); 6506 QualType RHSTy = RHS.get()->getType(); 6507 6508 // If both operands have arithmetic type, do the usual arithmetic conversions 6509 // to find a common type: C99 6.5.15p3,5. 6510 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6511 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6512 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6513 6514 return ResTy; 6515 } 6516 6517 // If both operands are the same structure or union type, the result is that 6518 // type. 6519 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6520 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6521 if (LHSRT->getDecl() == RHSRT->getDecl()) 6522 // "If both the operands have structure or union type, the result has 6523 // that type." This implies that CV qualifiers are dropped. 6524 return LHSTy.getUnqualifiedType(); 6525 // FIXME: Type of conditional expression must be complete in C mode. 6526 } 6527 6528 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6529 // The following || allows only one side to be void (a GCC-ism). 6530 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6531 return checkConditionalVoidType(*this, LHS, RHS); 6532 } 6533 6534 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6535 // the type of the other operand." 6536 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6537 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6538 6539 // All objective-c pointer type analysis is done here. 6540 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6541 QuestionLoc); 6542 if (LHS.isInvalid() || RHS.isInvalid()) 6543 return QualType(); 6544 if (!compositeType.isNull()) 6545 return compositeType; 6546 6547 6548 // Handle block pointer types. 6549 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6550 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6551 QuestionLoc); 6552 6553 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6554 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6555 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6556 QuestionLoc); 6557 6558 // GCC compatibility: soften pointer/integer mismatch. Note that 6559 // null pointers have been filtered out by this point. 6560 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6561 /*isIntFirstExpr=*/true)) 6562 return RHSTy; 6563 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6564 /*isIntFirstExpr=*/false)) 6565 return LHSTy; 6566 6567 // Emit a better diagnostic if one of the expressions is a null pointer 6568 // constant and the other is not a pointer type. In this case, the user most 6569 // likely forgot to take the address of the other expression. 6570 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6571 return QualType(); 6572 6573 // Otherwise, the operands are not compatible. 6574 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6575 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6576 << RHS.get()->getSourceRange(); 6577 return QualType(); 6578 } 6579 6580 /// FindCompositeObjCPointerType - Helper method to find composite type of 6581 /// two objective-c pointer types of the two input expressions. 6582 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6583 SourceLocation QuestionLoc) { 6584 QualType LHSTy = LHS.get()->getType(); 6585 QualType RHSTy = RHS.get()->getType(); 6586 6587 // Handle things like Class and struct objc_class*. Here we case the result 6588 // to the pseudo-builtin, because that will be implicitly cast back to the 6589 // redefinition type if an attempt is made to access its fields. 6590 if (LHSTy->isObjCClassType() && 6591 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6592 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6593 return LHSTy; 6594 } 6595 if (RHSTy->isObjCClassType() && 6596 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6597 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6598 return RHSTy; 6599 } 6600 // And the same for struct objc_object* / id 6601 if (LHSTy->isObjCIdType() && 6602 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6603 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6604 return LHSTy; 6605 } 6606 if (RHSTy->isObjCIdType() && 6607 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6608 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6609 return RHSTy; 6610 } 6611 // And the same for struct objc_selector* / SEL 6612 if (Context.isObjCSelType(LHSTy) && 6613 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6614 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6615 return LHSTy; 6616 } 6617 if (Context.isObjCSelType(RHSTy) && 6618 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6619 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6620 return RHSTy; 6621 } 6622 // Check constraints for Objective-C object pointers types. 6623 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6624 6625 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6626 // Two identical object pointer types are always compatible. 6627 return LHSTy; 6628 } 6629 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6630 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6631 QualType compositeType = LHSTy; 6632 6633 // If both operands are interfaces and either operand can be 6634 // assigned to the other, use that type as the composite 6635 // type. This allows 6636 // xxx ? (A*) a : (B*) b 6637 // where B is a subclass of A. 6638 // 6639 // Additionally, as for assignment, if either type is 'id' 6640 // allow silent coercion. Finally, if the types are 6641 // incompatible then make sure to use 'id' as the composite 6642 // type so the result is acceptable for sending messages to. 6643 6644 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6645 // It could return the composite type. 6646 if (!(compositeType = 6647 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6648 // Nothing more to do. 6649 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6650 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6651 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6652 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6653 } else if ((LHSTy->isObjCQualifiedIdType() || 6654 RHSTy->isObjCQualifiedIdType()) && 6655 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6656 // Need to handle "id<xx>" explicitly. 6657 // GCC allows qualified id and any Objective-C type to devolve to 6658 // id. Currently localizing to here until clear this should be 6659 // part of ObjCQualifiedIdTypesAreCompatible. 6660 compositeType = Context.getObjCIdType(); 6661 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6662 compositeType = Context.getObjCIdType(); 6663 } else { 6664 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6665 << LHSTy << RHSTy 6666 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6667 QualType incompatTy = Context.getObjCIdType(); 6668 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6669 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6670 return incompatTy; 6671 } 6672 // The object pointer types are compatible. 6673 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6674 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6675 return compositeType; 6676 } 6677 // Check Objective-C object pointer types and 'void *' 6678 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6679 if (getLangOpts().ObjCAutoRefCount) { 6680 // ARC forbids the implicit conversion of object pointers to 'void *', 6681 // so these types are not compatible. 6682 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6683 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6684 LHS = RHS = true; 6685 return QualType(); 6686 } 6687 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6688 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6689 QualType destPointee 6690 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6691 QualType destType = Context.getPointerType(destPointee); 6692 // Add qualifiers if necessary. 6693 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6694 // Promote to void*. 6695 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6696 return destType; 6697 } 6698 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6699 if (getLangOpts().ObjCAutoRefCount) { 6700 // ARC forbids the implicit conversion of object pointers to 'void *', 6701 // so these types are not compatible. 6702 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6703 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6704 LHS = RHS = true; 6705 return QualType(); 6706 } 6707 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6708 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6709 QualType destPointee 6710 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6711 QualType destType = Context.getPointerType(destPointee); 6712 // Add qualifiers if necessary. 6713 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6714 // Promote to void*. 6715 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6716 return destType; 6717 } 6718 return QualType(); 6719 } 6720 6721 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6722 /// ParenRange in parentheses. 6723 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6724 const PartialDiagnostic &Note, 6725 SourceRange ParenRange) { 6726 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6727 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6728 EndLoc.isValid()) { 6729 Self.Diag(Loc, Note) 6730 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6731 << FixItHint::CreateInsertion(EndLoc, ")"); 6732 } else { 6733 // We can't display the parentheses, so just show the bare note. 6734 Self.Diag(Loc, Note) << ParenRange; 6735 } 6736 } 6737 6738 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6739 return BinaryOperator::isAdditiveOp(Opc) || 6740 BinaryOperator::isMultiplicativeOp(Opc) || 6741 BinaryOperator::isShiftOp(Opc); 6742 } 6743 6744 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6745 /// expression, either using a built-in or overloaded operator, 6746 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6747 /// expression. 6748 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6749 Expr **RHSExprs) { 6750 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6751 E = E->IgnoreImpCasts(); 6752 E = E->IgnoreConversionOperator(); 6753 E = E->IgnoreImpCasts(); 6754 6755 // Built-in binary operator. 6756 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6757 if (IsArithmeticOp(OP->getOpcode())) { 6758 *Opcode = OP->getOpcode(); 6759 *RHSExprs = OP->getRHS(); 6760 return true; 6761 } 6762 } 6763 6764 // Overloaded operator. 6765 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6766 if (Call->getNumArgs() != 2) 6767 return false; 6768 6769 // Make sure this is really a binary operator that is safe to pass into 6770 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6771 OverloadedOperatorKind OO = Call->getOperator(); 6772 if (OO < OO_Plus || OO > OO_Arrow || 6773 OO == OO_PlusPlus || OO == OO_MinusMinus) 6774 return false; 6775 6776 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6777 if (IsArithmeticOp(OpKind)) { 6778 *Opcode = OpKind; 6779 *RHSExprs = Call->getArg(1); 6780 return true; 6781 } 6782 } 6783 6784 return false; 6785 } 6786 6787 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6788 /// or is a logical expression such as (x==y) which has int type, but is 6789 /// commonly interpreted as boolean. 6790 static bool ExprLooksBoolean(Expr *E) { 6791 E = E->IgnoreParenImpCasts(); 6792 6793 if (E->getType()->isBooleanType()) 6794 return true; 6795 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6796 return OP->isComparisonOp() || OP->isLogicalOp(); 6797 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6798 return OP->getOpcode() == UO_LNot; 6799 if (E->getType()->isPointerType()) 6800 return true; 6801 6802 return false; 6803 } 6804 6805 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6806 /// and binary operator are mixed in a way that suggests the programmer assumed 6807 /// the conditional operator has higher precedence, for example: 6808 /// "int x = a + someBinaryCondition ? 1 : 2". 6809 static void DiagnoseConditionalPrecedence(Sema &Self, 6810 SourceLocation OpLoc, 6811 Expr *Condition, 6812 Expr *LHSExpr, 6813 Expr *RHSExpr) { 6814 BinaryOperatorKind CondOpcode; 6815 Expr *CondRHS; 6816 6817 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6818 return; 6819 if (!ExprLooksBoolean(CondRHS)) 6820 return; 6821 6822 // The condition is an arithmetic binary expression, with a right- 6823 // hand side that looks boolean, so warn. 6824 6825 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6826 << Condition->getSourceRange() 6827 << BinaryOperator::getOpcodeStr(CondOpcode); 6828 6829 SuggestParentheses(Self, OpLoc, 6830 Self.PDiag(diag::note_precedence_silence) 6831 << BinaryOperator::getOpcodeStr(CondOpcode), 6832 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6833 6834 SuggestParentheses(Self, OpLoc, 6835 Self.PDiag(diag::note_precedence_conditional_first), 6836 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6837 } 6838 6839 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6840 /// in the case of a the GNU conditional expr extension. 6841 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6842 SourceLocation ColonLoc, 6843 Expr *CondExpr, Expr *LHSExpr, 6844 Expr *RHSExpr) { 6845 if (!getLangOpts().CPlusPlus) { 6846 // C cannot handle TypoExpr nodes in the condition because it 6847 // doesn't handle dependent types properly, so make sure any TypoExprs have 6848 // been dealt with before checking the operands. 6849 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6850 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 6851 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 6852 6853 if (!CondResult.isUsable()) 6854 return ExprError(); 6855 6856 if (LHSExpr) { 6857 if (!LHSResult.isUsable()) 6858 return ExprError(); 6859 } 6860 6861 if (!RHSResult.isUsable()) 6862 return ExprError(); 6863 6864 CondExpr = CondResult.get(); 6865 LHSExpr = LHSResult.get(); 6866 RHSExpr = RHSResult.get(); 6867 } 6868 6869 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6870 // was the condition. 6871 OpaqueValueExpr *opaqueValue = nullptr; 6872 Expr *commonExpr = nullptr; 6873 if (!LHSExpr) { 6874 commonExpr = CondExpr; 6875 // Lower out placeholder types first. This is important so that we don't 6876 // try to capture a placeholder. This happens in few cases in C++; such 6877 // as Objective-C++'s dictionary subscripting syntax. 6878 if (commonExpr->hasPlaceholderType()) { 6879 ExprResult result = CheckPlaceholderExpr(commonExpr); 6880 if (!result.isUsable()) return ExprError(); 6881 commonExpr = result.get(); 6882 } 6883 // We usually want to apply unary conversions *before* saving, except 6884 // in the special case of a C++ l-value conditional. 6885 if (!(getLangOpts().CPlusPlus 6886 && !commonExpr->isTypeDependent() 6887 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6888 && commonExpr->isGLValue() 6889 && commonExpr->isOrdinaryOrBitFieldObject() 6890 && RHSExpr->isOrdinaryOrBitFieldObject() 6891 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6892 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6893 if (commonRes.isInvalid()) 6894 return ExprError(); 6895 commonExpr = commonRes.get(); 6896 } 6897 6898 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6899 commonExpr->getType(), 6900 commonExpr->getValueKind(), 6901 commonExpr->getObjectKind(), 6902 commonExpr); 6903 LHSExpr = CondExpr = opaqueValue; 6904 } 6905 6906 ExprValueKind VK = VK_RValue; 6907 ExprObjectKind OK = OK_Ordinary; 6908 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6909 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6910 VK, OK, QuestionLoc); 6911 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6912 RHS.isInvalid()) 6913 return ExprError(); 6914 6915 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6916 RHS.get()); 6917 6918 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6919 6920 if (!commonExpr) 6921 return new (Context) 6922 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6923 RHS.get(), result, VK, OK); 6924 6925 return new (Context) BinaryConditionalOperator( 6926 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6927 ColonLoc, result, VK, OK); 6928 } 6929 6930 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6931 // being closely modeled after the C99 spec:-). The odd characteristic of this 6932 // routine is it effectively iqnores the qualifiers on the top level pointee. 6933 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6934 // FIXME: add a couple examples in this comment. 6935 static Sema::AssignConvertType 6936 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6937 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6938 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6939 6940 // get the "pointed to" type (ignoring qualifiers at the top level) 6941 const Type *lhptee, *rhptee; 6942 Qualifiers lhq, rhq; 6943 std::tie(lhptee, lhq) = 6944 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6945 std::tie(rhptee, rhq) = 6946 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6947 6948 Sema::AssignConvertType ConvTy = Sema::Compatible; 6949 6950 // C99 6.5.16.1p1: This following citation is common to constraints 6951 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6952 // qualifiers of the type *pointed to* by the right; 6953 6954 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6955 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6956 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6957 // Ignore lifetime for further calculation. 6958 lhq.removeObjCLifetime(); 6959 rhq.removeObjCLifetime(); 6960 } 6961 6962 if (!lhq.compatiblyIncludes(rhq)) { 6963 // Treat address-space mismatches as fatal. TODO: address subspaces 6964 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6965 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6966 6967 // It's okay to add or remove GC or lifetime qualifiers when converting to 6968 // and from void*. 6969 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6970 .compatiblyIncludes( 6971 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6972 && (lhptee->isVoidType() || rhptee->isVoidType())) 6973 ; // keep old 6974 6975 // Treat lifetime mismatches as fatal. 6976 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6977 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6978 6979 // For GCC compatibility, other qualifier mismatches are treated 6980 // as still compatible in C. 6981 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6982 } 6983 6984 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6985 // incomplete type and the other is a pointer to a qualified or unqualified 6986 // version of void... 6987 if (lhptee->isVoidType()) { 6988 if (rhptee->isIncompleteOrObjectType()) 6989 return ConvTy; 6990 6991 // As an extension, we allow cast to/from void* to function pointer. 6992 assert(rhptee->isFunctionType()); 6993 return Sema::FunctionVoidPointer; 6994 } 6995 6996 if (rhptee->isVoidType()) { 6997 if (lhptee->isIncompleteOrObjectType()) 6998 return ConvTy; 6999 7000 // As an extension, we allow cast to/from void* to function pointer. 7001 assert(lhptee->isFunctionType()); 7002 return Sema::FunctionVoidPointer; 7003 } 7004 7005 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7006 // unqualified versions of compatible types, ... 7007 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7008 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7009 // Check if the pointee types are compatible ignoring the sign. 7010 // We explicitly check for char so that we catch "char" vs 7011 // "unsigned char" on systems where "char" is unsigned. 7012 if (lhptee->isCharType()) 7013 ltrans = S.Context.UnsignedCharTy; 7014 else if (lhptee->hasSignedIntegerRepresentation()) 7015 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7016 7017 if (rhptee->isCharType()) 7018 rtrans = S.Context.UnsignedCharTy; 7019 else if (rhptee->hasSignedIntegerRepresentation()) 7020 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7021 7022 if (ltrans == rtrans) { 7023 // Types are compatible ignoring the sign. Qualifier incompatibility 7024 // takes priority over sign incompatibility because the sign 7025 // warning can be disabled. 7026 if (ConvTy != Sema::Compatible) 7027 return ConvTy; 7028 7029 return Sema::IncompatiblePointerSign; 7030 } 7031 7032 // If we are a multi-level pointer, it's possible that our issue is simply 7033 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7034 // the eventual target type is the same and the pointers have the same 7035 // level of indirection, this must be the issue. 7036 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7037 do { 7038 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7039 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7040 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7041 7042 if (lhptee == rhptee) 7043 return Sema::IncompatibleNestedPointerQualifiers; 7044 } 7045 7046 // General pointer incompatibility takes priority over qualifiers. 7047 return Sema::IncompatiblePointer; 7048 } 7049 if (!S.getLangOpts().CPlusPlus && 7050 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7051 return Sema::IncompatiblePointer; 7052 return ConvTy; 7053 } 7054 7055 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7056 /// block pointer types are compatible or whether a block and normal pointer 7057 /// are compatible. It is more restrict than comparing two function pointer 7058 // types. 7059 static Sema::AssignConvertType 7060 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7061 QualType RHSType) { 7062 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7063 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7064 7065 QualType lhptee, rhptee; 7066 7067 // get the "pointed to" type (ignoring qualifiers at the top level) 7068 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7069 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7070 7071 // In C++, the types have to match exactly. 7072 if (S.getLangOpts().CPlusPlus) 7073 return Sema::IncompatibleBlockPointer; 7074 7075 Sema::AssignConvertType ConvTy = Sema::Compatible; 7076 7077 // For blocks we enforce that qualifiers are identical. 7078 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7079 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7080 7081 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7082 return Sema::IncompatibleBlockPointer; 7083 7084 return ConvTy; 7085 } 7086 7087 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7088 /// for assignment compatibility. 7089 static Sema::AssignConvertType 7090 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7091 QualType RHSType) { 7092 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7093 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7094 7095 if (LHSType->isObjCBuiltinType()) { 7096 // Class is not compatible with ObjC object pointers. 7097 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7098 !RHSType->isObjCQualifiedClassType()) 7099 return Sema::IncompatiblePointer; 7100 return Sema::Compatible; 7101 } 7102 if (RHSType->isObjCBuiltinType()) { 7103 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7104 !LHSType->isObjCQualifiedClassType()) 7105 return Sema::IncompatiblePointer; 7106 return Sema::Compatible; 7107 } 7108 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7109 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7110 7111 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7112 // make an exception for id<P> 7113 !LHSType->isObjCQualifiedIdType()) 7114 return Sema::CompatiblePointerDiscardsQualifiers; 7115 7116 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7117 return Sema::Compatible; 7118 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7119 return Sema::IncompatibleObjCQualifiedId; 7120 return Sema::IncompatiblePointer; 7121 } 7122 7123 Sema::AssignConvertType 7124 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7125 QualType LHSType, QualType RHSType) { 7126 // Fake up an opaque expression. We don't actually care about what 7127 // cast operations are required, so if CheckAssignmentConstraints 7128 // adds casts to this they'll be wasted, but fortunately that doesn't 7129 // usually happen on valid code. 7130 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7131 ExprResult RHSPtr = &RHSExpr; 7132 CastKind K = CK_Invalid; 7133 7134 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7135 } 7136 7137 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7138 /// has code to accommodate several GCC extensions when type checking 7139 /// pointers. Here are some objectionable examples that GCC considers warnings: 7140 /// 7141 /// int a, *pint; 7142 /// short *pshort; 7143 /// struct foo *pfoo; 7144 /// 7145 /// pint = pshort; // warning: assignment from incompatible pointer type 7146 /// a = pint; // warning: assignment makes integer from pointer without a cast 7147 /// pint = a; // warning: assignment makes pointer from integer without a cast 7148 /// pint = pfoo; // warning: assignment from incompatible pointer type 7149 /// 7150 /// As a result, the code for dealing with pointers is more complex than the 7151 /// C99 spec dictates. 7152 /// 7153 /// Sets 'Kind' for any result kind except Incompatible. 7154 Sema::AssignConvertType 7155 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7156 CastKind &Kind, bool ConvertRHS) { 7157 QualType RHSType = RHS.get()->getType(); 7158 QualType OrigLHSType = LHSType; 7159 7160 // Get canonical types. We're not formatting these types, just comparing 7161 // them. 7162 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7163 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7164 7165 // Common case: no conversion required. 7166 if (LHSType == RHSType) { 7167 Kind = CK_NoOp; 7168 return Compatible; 7169 } 7170 7171 // If we have an atomic type, try a non-atomic assignment, then just add an 7172 // atomic qualification step. 7173 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7174 Sema::AssignConvertType result = 7175 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7176 if (result != Compatible) 7177 return result; 7178 if (Kind != CK_NoOp && ConvertRHS) 7179 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7180 Kind = CK_NonAtomicToAtomic; 7181 return Compatible; 7182 } 7183 7184 // If the left-hand side is a reference type, then we are in a 7185 // (rare!) case where we've allowed the use of references in C, 7186 // e.g., as a parameter type in a built-in function. In this case, 7187 // just make sure that the type referenced is compatible with the 7188 // right-hand side type. The caller is responsible for adjusting 7189 // LHSType so that the resulting expression does not have reference 7190 // type. 7191 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7192 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7193 Kind = CK_LValueBitCast; 7194 return Compatible; 7195 } 7196 return Incompatible; 7197 } 7198 7199 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7200 // to the same ExtVector type. 7201 if (LHSType->isExtVectorType()) { 7202 if (RHSType->isExtVectorType()) 7203 return Incompatible; 7204 if (RHSType->isArithmeticType()) { 7205 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7206 if (ConvertRHS) 7207 RHS = prepareVectorSplat(LHSType, RHS.get()); 7208 Kind = CK_VectorSplat; 7209 return Compatible; 7210 } 7211 } 7212 7213 // Conversions to or from vector type. 7214 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7215 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7216 // Allow assignments of an AltiVec vector type to an equivalent GCC 7217 // vector type and vice versa 7218 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7219 Kind = CK_BitCast; 7220 return Compatible; 7221 } 7222 7223 // If we are allowing lax vector conversions, and LHS and RHS are both 7224 // vectors, the total size only needs to be the same. This is a bitcast; 7225 // no bits are changed but the result type is different. 7226 if (isLaxVectorConversion(RHSType, LHSType)) { 7227 Kind = CK_BitCast; 7228 return IncompatibleVectors; 7229 } 7230 } 7231 return Incompatible; 7232 } 7233 7234 // Arithmetic conversions. 7235 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7236 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7237 if (ConvertRHS) 7238 Kind = PrepareScalarCast(RHS, LHSType); 7239 return Compatible; 7240 } 7241 7242 // Conversions to normal pointers. 7243 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7244 // U* -> T* 7245 if (isa<PointerType>(RHSType)) { 7246 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7247 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7248 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7249 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7250 } 7251 7252 // int -> T* 7253 if (RHSType->isIntegerType()) { 7254 Kind = CK_IntegralToPointer; // FIXME: null? 7255 return IntToPointer; 7256 } 7257 7258 // C pointers are not compatible with ObjC object pointers, 7259 // with two exceptions: 7260 if (isa<ObjCObjectPointerType>(RHSType)) { 7261 // - conversions to void* 7262 if (LHSPointer->getPointeeType()->isVoidType()) { 7263 Kind = CK_BitCast; 7264 return Compatible; 7265 } 7266 7267 // - conversions from 'Class' to the redefinition type 7268 if (RHSType->isObjCClassType() && 7269 Context.hasSameType(LHSType, 7270 Context.getObjCClassRedefinitionType())) { 7271 Kind = CK_BitCast; 7272 return Compatible; 7273 } 7274 7275 Kind = CK_BitCast; 7276 return IncompatiblePointer; 7277 } 7278 7279 // U^ -> void* 7280 if (RHSType->getAs<BlockPointerType>()) { 7281 if (LHSPointer->getPointeeType()->isVoidType()) { 7282 Kind = CK_BitCast; 7283 return Compatible; 7284 } 7285 } 7286 7287 return Incompatible; 7288 } 7289 7290 // Conversions to block pointers. 7291 if (isa<BlockPointerType>(LHSType)) { 7292 // U^ -> T^ 7293 if (RHSType->isBlockPointerType()) { 7294 Kind = CK_BitCast; 7295 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7296 } 7297 7298 // int or null -> T^ 7299 if (RHSType->isIntegerType()) { 7300 Kind = CK_IntegralToPointer; // FIXME: null 7301 return IntToBlockPointer; 7302 } 7303 7304 // id -> T^ 7305 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7306 Kind = CK_AnyPointerToBlockPointerCast; 7307 return Compatible; 7308 } 7309 7310 // void* -> T^ 7311 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7312 if (RHSPT->getPointeeType()->isVoidType()) { 7313 Kind = CK_AnyPointerToBlockPointerCast; 7314 return Compatible; 7315 } 7316 7317 return Incompatible; 7318 } 7319 7320 // Conversions to Objective-C pointers. 7321 if (isa<ObjCObjectPointerType>(LHSType)) { 7322 // A* -> B* 7323 if (RHSType->isObjCObjectPointerType()) { 7324 Kind = CK_BitCast; 7325 Sema::AssignConvertType result = 7326 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7327 if (getLangOpts().ObjCAutoRefCount && 7328 result == Compatible && 7329 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7330 result = IncompatibleObjCWeakRef; 7331 return result; 7332 } 7333 7334 // int or null -> A* 7335 if (RHSType->isIntegerType()) { 7336 Kind = CK_IntegralToPointer; // FIXME: null 7337 return IntToPointer; 7338 } 7339 7340 // In general, C pointers are not compatible with ObjC object pointers, 7341 // with two exceptions: 7342 if (isa<PointerType>(RHSType)) { 7343 Kind = CK_CPointerToObjCPointerCast; 7344 7345 // - conversions from 'void*' 7346 if (RHSType->isVoidPointerType()) { 7347 return Compatible; 7348 } 7349 7350 // - conversions to 'Class' from its redefinition type 7351 if (LHSType->isObjCClassType() && 7352 Context.hasSameType(RHSType, 7353 Context.getObjCClassRedefinitionType())) { 7354 return Compatible; 7355 } 7356 7357 return IncompatiblePointer; 7358 } 7359 7360 // Only under strict condition T^ is compatible with an Objective-C pointer. 7361 if (RHSType->isBlockPointerType() && 7362 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7363 if (ConvertRHS) 7364 maybeExtendBlockObject(RHS); 7365 Kind = CK_BlockPointerToObjCPointerCast; 7366 return Compatible; 7367 } 7368 7369 return Incompatible; 7370 } 7371 7372 // Conversions from pointers that are not covered by the above. 7373 if (isa<PointerType>(RHSType)) { 7374 // T* -> _Bool 7375 if (LHSType == Context.BoolTy) { 7376 Kind = CK_PointerToBoolean; 7377 return Compatible; 7378 } 7379 7380 // T* -> int 7381 if (LHSType->isIntegerType()) { 7382 Kind = CK_PointerToIntegral; 7383 return PointerToInt; 7384 } 7385 7386 return Incompatible; 7387 } 7388 7389 // Conversions from Objective-C pointers that are not covered by the above. 7390 if (isa<ObjCObjectPointerType>(RHSType)) { 7391 // T* -> _Bool 7392 if (LHSType == Context.BoolTy) { 7393 Kind = CK_PointerToBoolean; 7394 return Compatible; 7395 } 7396 7397 // T* -> int 7398 if (LHSType->isIntegerType()) { 7399 Kind = CK_PointerToIntegral; 7400 return PointerToInt; 7401 } 7402 7403 return Incompatible; 7404 } 7405 7406 // struct A -> struct B 7407 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7408 if (Context.typesAreCompatible(LHSType, RHSType)) { 7409 Kind = CK_NoOp; 7410 return Compatible; 7411 } 7412 } 7413 7414 return Incompatible; 7415 } 7416 7417 /// \brief Constructs a transparent union from an expression that is 7418 /// used to initialize the transparent union. 7419 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7420 ExprResult &EResult, QualType UnionType, 7421 FieldDecl *Field) { 7422 // Build an initializer list that designates the appropriate member 7423 // of the transparent union. 7424 Expr *E = EResult.get(); 7425 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7426 E, SourceLocation()); 7427 Initializer->setType(UnionType); 7428 Initializer->setInitializedFieldInUnion(Field); 7429 7430 // Build a compound literal constructing a value of the transparent 7431 // union type from this initializer list. 7432 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7433 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7434 VK_RValue, Initializer, false); 7435 } 7436 7437 Sema::AssignConvertType 7438 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7439 ExprResult &RHS) { 7440 QualType RHSType = RHS.get()->getType(); 7441 7442 // If the ArgType is a Union type, we want to handle a potential 7443 // transparent_union GCC extension. 7444 const RecordType *UT = ArgType->getAsUnionType(); 7445 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7446 return Incompatible; 7447 7448 // The field to initialize within the transparent union. 7449 RecordDecl *UD = UT->getDecl(); 7450 FieldDecl *InitField = nullptr; 7451 // It's compatible if the expression matches any of the fields. 7452 for (auto *it : UD->fields()) { 7453 if (it->getType()->isPointerType()) { 7454 // If the transparent union contains a pointer type, we allow: 7455 // 1) void pointer 7456 // 2) null pointer constant 7457 if (RHSType->isPointerType()) 7458 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7459 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7460 InitField = it; 7461 break; 7462 } 7463 7464 if (RHS.get()->isNullPointerConstant(Context, 7465 Expr::NPC_ValueDependentIsNull)) { 7466 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7467 CK_NullToPointer); 7468 InitField = it; 7469 break; 7470 } 7471 } 7472 7473 CastKind Kind = CK_Invalid; 7474 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7475 == Compatible) { 7476 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7477 InitField = it; 7478 break; 7479 } 7480 } 7481 7482 if (!InitField) 7483 return Incompatible; 7484 7485 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7486 return Compatible; 7487 } 7488 7489 Sema::AssignConvertType 7490 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7491 bool Diagnose, 7492 bool DiagnoseCFAudited, 7493 bool ConvertRHS) { 7494 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7495 // we can't avoid *all* modifications at the moment, so we need some somewhere 7496 // to put the updated value. 7497 ExprResult LocalRHS = CallerRHS; 7498 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7499 7500 if (getLangOpts().CPlusPlus) { 7501 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7502 // C++ 5.17p3: If the left operand is not of class type, the 7503 // expression is implicitly converted (C++ 4) to the 7504 // cv-unqualified type of the left operand. 7505 ExprResult Res; 7506 if (Diagnose) { 7507 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7508 AA_Assigning); 7509 } else { 7510 ImplicitConversionSequence ICS = 7511 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7512 /*SuppressUserConversions=*/false, 7513 /*AllowExplicit=*/false, 7514 /*InOverloadResolution=*/false, 7515 /*CStyle=*/false, 7516 /*AllowObjCWritebackConversion=*/false); 7517 if (ICS.isFailure()) 7518 return Incompatible; 7519 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7520 ICS, AA_Assigning); 7521 } 7522 if (Res.isInvalid()) 7523 return Incompatible; 7524 Sema::AssignConvertType result = Compatible; 7525 if (getLangOpts().ObjCAutoRefCount && 7526 !CheckObjCARCUnavailableWeakConversion(LHSType, 7527 RHS.get()->getType())) 7528 result = IncompatibleObjCWeakRef; 7529 RHS = Res; 7530 return result; 7531 } 7532 7533 // FIXME: Currently, we fall through and treat C++ classes like C 7534 // structures. 7535 // FIXME: We also fall through for atomics; not sure what should 7536 // happen there, though. 7537 } else if (RHS.get()->getType() == Context.OverloadTy) { 7538 // As a set of extensions to C, we support overloading on functions. These 7539 // functions need to be resolved here. 7540 DeclAccessPair DAP; 7541 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7542 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7543 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7544 else 7545 return Incompatible; 7546 } 7547 7548 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7549 // a null pointer constant. 7550 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7551 LHSType->isBlockPointerType()) && 7552 RHS.get()->isNullPointerConstant(Context, 7553 Expr::NPC_ValueDependentIsNull)) { 7554 if (Diagnose || ConvertRHS) { 7555 CastKind Kind; 7556 CXXCastPath Path; 7557 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7558 /*IgnoreBaseAccess=*/false, Diagnose); 7559 if (ConvertRHS) 7560 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7561 } 7562 return Compatible; 7563 } 7564 7565 // This check seems unnatural, however it is necessary to ensure the proper 7566 // conversion of functions/arrays. If the conversion were done for all 7567 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7568 // expressions that suppress this implicit conversion (&, sizeof). 7569 // 7570 // Suppress this for references: C++ 8.5.3p5. 7571 if (!LHSType->isReferenceType()) { 7572 // FIXME: We potentially allocate here even if ConvertRHS is false. 7573 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7574 if (RHS.isInvalid()) 7575 return Incompatible; 7576 } 7577 7578 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7579 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7580 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7581 if (PDecl && !PDecl->hasDefinition()) { 7582 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7583 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7584 } 7585 } 7586 7587 CastKind Kind = CK_Invalid; 7588 Sema::AssignConvertType result = 7589 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7590 7591 // C99 6.5.16.1p2: The value of the right operand is converted to the 7592 // type of the assignment expression. 7593 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7594 // so that we can use references in built-in functions even in C. 7595 // The getNonReferenceType() call makes sure that the resulting expression 7596 // does not have reference type. 7597 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7598 QualType Ty = LHSType.getNonLValueExprType(Context); 7599 Expr *E = RHS.get(); 7600 7601 // Check for various Objective-C errors. If we are not reporting 7602 // diagnostics and just checking for errors, e.g., during overload 7603 // resolution, return Incompatible to indicate the failure. 7604 if (getLangOpts().ObjCAutoRefCount && 7605 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7606 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7607 if (!Diagnose) 7608 return Incompatible; 7609 } 7610 if (getLangOpts().ObjC1 && 7611 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7612 E->getType(), E, Diagnose) || 7613 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7614 if (!Diagnose) 7615 return Incompatible; 7616 // Replace the expression with a corrected version and continue so we 7617 // can find further errors. 7618 RHS = E; 7619 return Compatible; 7620 } 7621 7622 if (ConvertRHS) 7623 RHS = ImpCastExprToType(E, Ty, Kind); 7624 } 7625 return result; 7626 } 7627 7628 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7629 ExprResult &RHS) { 7630 Diag(Loc, diag::err_typecheck_invalid_operands) 7631 << LHS.get()->getType() << RHS.get()->getType() 7632 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7633 return QualType(); 7634 } 7635 7636 /// Try to convert a value of non-vector type to a vector type by converting 7637 /// the type to the element type of the vector and then performing a splat. 7638 /// If the language is OpenCL, we only use conversions that promote scalar 7639 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7640 /// for float->int. 7641 /// 7642 /// \param scalar - if non-null, actually perform the conversions 7643 /// \return true if the operation fails (but without diagnosing the failure) 7644 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7645 QualType scalarTy, 7646 QualType vectorEltTy, 7647 QualType vectorTy) { 7648 // The conversion to apply to the scalar before splatting it, 7649 // if necessary. 7650 CastKind scalarCast = CK_Invalid; 7651 7652 if (vectorEltTy->isIntegralType(S.Context)) { 7653 if (!scalarTy->isIntegralType(S.Context)) 7654 return true; 7655 if (S.getLangOpts().OpenCL && 7656 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7657 return true; 7658 scalarCast = CK_IntegralCast; 7659 } else if (vectorEltTy->isRealFloatingType()) { 7660 if (scalarTy->isRealFloatingType()) { 7661 if (S.getLangOpts().OpenCL && 7662 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7663 return true; 7664 scalarCast = CK_FloatingCast; 7665 } 7666 else if (scalarTy->isIntegralType(S.Context)) 7667 scalarCast = CK_IntegralToFloating; 7668 else 7669 return true; 7670 } else { 7671 return true; 7672 } 7673 7674 // Adjust scalar if desired. 7675 if (scalar) { 7676 if (scalarCast != CK_Invalid) 7677 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7678 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7679 } 7680 return false; 7681 } 7682 7683 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7684 SourceLocation Loc, bool IsCompAssign, 7685 bool AllowBothBool, 7686 bool AllowBoolConversions) { 7687 if (!IsCompAssign) { 7688 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7689 if (LHS.isInvalid()) 7690 return QualType(); 7691 } 7692 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7693 if (RHS.isInvalid()) 7694 return QualType(); 7695 7696 // For conversion purposes, we ignore any qualifiers. 7697 // For example, "const float" and "float" are equivalent. 7698 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7699 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7700 7701 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7702 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7703 assert(LHSVecType || RHSVecType); 7704 7705 // AltiVec-style "vector bool op vector bool" combinations are allowed 7706 // for some operators but not others. 7707 if (!AllowBothBool && 7708 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7709 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7710 return InvalidOperands(Loc, LHS, RHS); 7711 7712 // If the vector types are identical, return. 7713 if (Context.hasSameType(LHSType, RHSType)) 7714 return LHSType; 7715 7716 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7717 if (LHSVecType && RHSVecType && 7718 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7719 if (isa<ExtVectorType>(LHSVecType)) { 7720 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7721 return LHSType; 7722 } 7723 7724 if (!IsCompAssign) 7725 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7726 return RHSType; 7727 } 7728 7729 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7730 // can be mixed, with the result being the non-bool type. The non-bool 7731 // operand must have integer element type. 7732 if (AllowBoolConversions && LHSVecType && RHSVecType && 7733 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7734 (Context.getTypeSize(LHSVecType->getElementType()) == 7735 Context.getTypeSize(RHSVecType->getElementType()))) { 7736 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7737 LHSVecType->getElementType()->isIntegerType() && 7738 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7739 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7740 return LHSType; 7741 } 7742 if (!IsCompAssign && 7743 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7744 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7745 RHSVecType->getElementType()->isIntegerType()) { 7746 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7747 return RHSType; 7748 } 7749 } 7750 7751 // If there's an ext-vector type and a scalar, try to convert the scalar to 7752 // the vector element type and splat. 7753 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7754 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7755 LHSVecType->getElementType(), LHSType)) 7756 return LHSType; 7757 } 7758 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7759 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7760 LHSType, RHSVecType->getElementType(), 7761 RHSType)) 7762 return RHSType; 7763 } 7764 7765 // If we're allowing lax vector conversions, only the total (data) size 7766 // needs to be the same. 7767 // FIXME: Should we really be allowing this? 7768 // FIXME: We really just pick the LHS type arbitrarily? 7769 if (isLaxVectorConversion(RHSType, LHSType)) { 7770 QualType resultType = LHSType; 7771 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7772 return resultType; 7773 } 7774 7775 // Okay, the expression is invalid. 7776 7777 // If there's a non-vector, non-real operand, diagnose that. 7778 if ((!RHSVecType && !RHSType->isRealType()) || 7779 (!LHSVecType && !LHSType->isRealType())) { 7780 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7781 << LHSType << RHSType 7782 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7783 return QualType(); 7784 } 7785 7786 // OpenCL V1.1 6.2.6.p1: 7787 // If the operands are of more than one vector type, then an error shall 7788 // occur. Implicit conversions between vector types are not permitted, per 7789 // section 6.2.1. 7790 if (getLangOpts().OpenCL && 7791 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7792 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7793 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7794 << RHSType; 7795 return QualType(); 7796 } 7797 7798 // Otherwise, use the generic diagnostic. 7799 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7800 << LHSType << RHSType 7801 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7802 return QualType(); 7803 } 7804 7805 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7806 // expression. These are mainly cases where the null pointer is used as an 7807 // integer instead of a pointer. 7808 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7809 SourceLocation Loc, bool IsCompare) { 7810 // The canonical way to check for a GNU null is with isNullPointerConstant, 7811 // but we use a bit of a hack here for speed; this is a relatively 7812 // hot path, and isNullPointerConstant is slow. 7813 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7814 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7815 7816 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7817 7818 // Avoid analyzing cases where the result will either be invalid (and 7819 // diagnosed as such) or entirely valid and not something to warn about. 7820 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7821 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7822 return; 7823 7824 // Comparison operations would not make sense with a null pointer no matter 7825 // what the other expression is. 7826 if (!IsCompare) { 7827 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7828 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7829 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7830 return; 7831 } 7832 7833 // The rest of the operations only make sense with a null pointer 7834 // if the other expression is a pointer. 7835 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7836 NonNullType->canDecayToPointerType()) 7837 return; 7838 7839 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7840 << LHSNull /* LHS is NULL */ << NonNullType 7841 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7842 } 7843 7844 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7845 ExprResult &RHS, 7846 SourceLocation Loc, bool IsDiv) { 7847 // Check for division/remainder by zero. 7848 llvm::APSInt RHSValue; 7849 if (!RHS.get()->isValueDependent() && 7850 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7851 S.DiagRuntimeBehavior(Loc, RHS.get(), 7852 S.PDiag(diag::warn_remainder_division_by_zero) 7853 << IsDiv << RHS.get()->getSourceRange()); 7854 } 7855 7856 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7857 SourceLocation Loc, 7858 bool IsCompAssign, bool IsDiv) { 7859 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7860 7861 if (LHS.get()->getType()->isVectorType() || 7862 RHS.get()->getType()->isVectorType()) 7863 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7864 /*AllowBothBool*/getLangOpts().AltiVec, 7865 /*AllowBoolConversions*/false); 7866 7867 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7868 if (LHS.isInvalid() || RHS.isInvalid()) 7869 return QualType(); 7870 7871 7872 if (compType.isNull() || !compType->isArithmeticType()) 7873 return InvalidOperands(Loc, LHS, RHS); 7874 if (IsDiv) 7875 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7876 return compType; 7877 } 7878 7879 QualType Sema::CheckRemainderOperands( 7880 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7881 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7882 7883 if (LHS.get()->getType()->isVectorType() || 7884 RHS.get()->getType()->isVectorType()) { 7885 if (LHS.get()->getType()->hasIntegerRepresentation() && 7886 RHS.get()->getType()->hasIntegerRepresentation()) 7887 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7888 /*AllowBothBool*/getLangOpts().AltiVec, 7889 /*AllowBoolConversions*/false); 7890 return InvalidOperands(Loc, LHS, RHS); 7891 } 7892 7893 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7894 if (LHS.isInvalid() || RHS.isInvalid()) 7895 return QualType(); 7896 7897 if (compType.isNull() || !compType->isIntegerType()) 7898 return InvalidOperands(Loc, LHS, RHS); 7899 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 7900 return compType; 7901 } 7902 7903 /// \brief Diagnose invalid arithmetic on two void pointers. 7904 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7905 Expr *LHSExpr, Expr *RHSExpr) { 7906 S.Diag(Loc, S.getLangOpts().CPlusPlus 7907 ? diag::err_typecheck_pointer_arith_void_type 7908 : diag::ext_gnu_void_ptr) 7909 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7910 << RHSExpr->getSourceRange(); 7911 } 7912 7913 /// \brief Diagnose invalid arithmetic on a void pointer. 7914 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7915 Expr *Pointer) { 7916 S.Diag(Loc, S.getLangOpts().CPlusPlus 7917 ? diag::err_typecheck_pointer_arith_void_type 7918 : diag::ext_gnu_void_ptr) 7919 << 0 /* one pointer */ << Pointer->getSourceRange(); 7920 } 7921 7922 /// \brief Diagnose invalid arithmetic on two function pointers. 7923 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7924 Expr *LHS, Expr *RHS) { 7925 assert(LHS->getType()->isAnyPointerType()); 7926 assert(RHS->getType()->isAnyPointerType()); 7927 S.Diag(Loc, S.getLangOpts().CPlusPlus 7928 ? diag::err_typecheck_pointer_arith_function_type 7929 : diag::ext_gnu_ptr_func_arith) 7930 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7931 // We only show the second type if it differs from the first. 7932 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7933 RHS->getType()) 7934 << RHS->getType()->getPointeeType() 7935 << LHS->getSourceRange() << RHS->getSourceRange(); 7936 } 7937 7938 /// \brief Diagnose invalid arithmetic on a function pointer. 7939 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7940 Expr *Pointer) { 7941 assert(Pointer->getType()->isAnyPointerType()); 7942 S.Diag(Loc, S.getLangOpts().CPlusPlus 7943 ? diag::err_typecheck_pointer_arith_function_type 7944 : diag::ext_gnu_ptr_func_arith) 7945 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7946 << 0 /* one pointer, so only one type */ 7947 << Pointer->getSourceRange(); 7948 } 7949 7950 /// \brief Emit error if Operand is incomplete pointer type 7951 /// 7952 /// \returns True if pointer has incomplete type 7953 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7954 Expr *Operand) { 7955 QualType ResType = Operand->getType(); 7956 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7957 ResType = ResAtomicType->getValueType(); 7958 7959 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7960 QualType PointeeTy = ResType->getPointeeType(); 7961 return S.RequireCompleteType(Loc, PointeeTy, 7962 diag::err_typecheck_arithmetic_incomplete_type, 7963 PointeeTy, Operand->getSourceRange()); 7964 } 7965 7966 /// \brief Check the validity of an arithmetic pointer operand. 7967 /// 7968 /// If the operand has pointer type, this code will check for pointer types 7969 /// which are invalid in arithmetic operations. These will be diagnosed 7970 /// appropriately, including whether or not the use is supported as an 7971 /// extension. 7972 /// 7973 /// \returns True when the operand is valid to use (even if as an extension). 7974 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7975 Expr *Operand) { 7976 QualType ResType = Operand->getType(); 7977 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7978 ResType = ResAtomicType->getValueType(); 7979 7980 if (!ResType->isAnyPointerType()) return true; 7981 7982 QualType PointeeTy = ResType->getPointeeType(); 7983 if (PointeeTy->isVoidType()) { 7984 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7985 return !S.getLangOpts().CPlusPlus; 7986 } 7987 if (PointeeTy->isFunctionType()) { 7988 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7989 return !S.getLangOpts().CPlusPlus; 7990 } 7991 7992 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7993 7994 return true; 7995 } 7996 7997 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7998 /// operands. 7999 /// 8000 /// This routine will diagnose any invalid arithmetic on pointer operands much 8001 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8002 /// for emitting a single diagnostic even for operations where both LHS and RHS 8003 /// are (potentially problematic) pointers. 8004 /// 8005 /// \returns True when the operand is valid to use (even if as an extension). 8006 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8007 Expr *LHSExpr, Expr *RHSExpr) { 8008 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8009 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8010 if (!isLHSPointer && !isRHSPointer) return true; 8011 8012 QualType LHSPointeeTy, RHSPointeeTy; 8013 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8014 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8015 8016 // if both are pointers check if operation is valid wrt address spaces 8017 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8018 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8019 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8020 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8021 S.Diag(Loc, 8022 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8023 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8024 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8025 return false; 8026 } 8027 } 8028 8029 // Check for arithmetic on pointers to incomplete types. 8030 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8031 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8032 if (isLHSVoidPtr || isRHSVoidPtr) { 8033 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8034 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8035 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8036 8037 return !S.getLangOpts().CPlusPlus; 8038 } 8039 8040 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8041 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8042 if (isLHSFuncPtr || isRHSFuncPtr) { 8043 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8044 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8045 RHSExpr); 8046 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8047 8048 return !S.getLangOpts().CPlusPlus; 8049 } 8050 8051 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8052 return false; 8053 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8054 return false; 8055 8056 return true; 8057 } 8058 8059 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8060 /// literal. 8061 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8062 Expr *LHSExpr, Expr *RHSExpr) { 8063 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8064 Expr* IndexExpr = RHSExpr; 8065 if (!StrExpr) { 8066 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8067 IndexExpr = LHSExpr; 8068 } 8069 8070 bool IsStringPlusInt = StrExpr && 8071 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8072 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8073 return; 8074 8075 llvm::APSInt index; 8076 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8077 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8078 if (index.isNonNegative() && 8079 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8080 index.isUnsigned())) 8081 return; 8082 } 8083 8084 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8085 Self.Diag(OpLoc, diag::warn_string_plus_int) 8086 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8087 8088 // Only print a fixit for "str" + int, not for int + "str". 8089 if (IndexExpr == RHSExpr) { 8090 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8091 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8092 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8093 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8094 << FixItHint::CreateInsertion(EndLoc, "]"); 8095 } else 8096 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8097 } 8098 8099 /// \brief Emit a warning when adding a char literal to a string. 8100 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8101 Expr *LHSExpr, Expr *RHSExpr) { 8102 const Expr *StringRefExpr = LHSExpr; 8103 const CharacterLiteral *CharExpr = 8104 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8105 8106 if (!CharExpr) { 8107 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8108 StringRefExpr = RHSExpr; 8109 } 8110 8111 if (!CharExpr || !StringRefExpr) 8112 return; 8113 8114 const QualType StringType = StringRefExpr->getType(); 8115 8116 // Return if not a PointerType. 8117 if (!StringType->isAnyPointerType()) 8118 return; 8119 8120 // Return if not a CharacterType. 8121 if (!StringType->getPointeeType()->isAnyCharacterType()) 8122 return; 8123 8124 ASTContext &Ctx = Self.getASTContext(); 8125 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8126 8127 const QualType CharType = CharExpr->getType(); 8128 if (!CharType->isAnyCharacterType() && 8129 CharType->isIntegerType() && 8130 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8131 Self.Diag(OpLoc, diag::warn_string_plus_char) 8132 << DiagRange << Ctx.CharTy; 8133 } else { 8134 Self.Diag(OpLoc, diag::warn_string_plus_char) 8135 << DiagRange << CharExpr->getType(); 8136 } 8137 8138 // Only print a fixit for str + char, not for char + str. 8139 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8140 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8141 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8142 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8143 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8144 << FixItHint::CreateInsertion(EndLoc, "]"); 8145 } else { 8146 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8147 } 8148 } 8149 8150 /// \brief Emit error when two pointers are incompatible. 8151 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8152 Expr *LHSExpr, Expr *RHSExpr) { 8153 assert(LHSExpr->getType()->isAnyPointerType()); 8154 assert(RHSExpr->getType()->isAnyPointerType()); 8155 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8156 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8157 << RHSExpr->getSourceRange(); 8158 } 8159 8160 // C99 6.5.6 8161 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8162 SourceLocation Loc, BinaryOperatorKind Opc, 8163 QualType* CompLHSTy) { 8164 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8165 8166 if (LHS.get()->getType()->isVectorType() || 8167 RHS.get()->getType()->isVectorType()) { 8168 QualType compType = CheckVectorOperands( 8169 LHS, RHS, Loc, CompLHSTy, 8170 /*AllowBothBool*/getLangOpts().AltiVec, 8171 /*AllowBoolConversions*/getLangOpts().ZVector); 8172 if (CompLHSTy) *CompLHSTy = compType; 8173 return compType; 8174 } 8175 8176 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8177 if (LHS.isInvalid() || RHS.isInvalid()) 8178 return QualType(); 8179 8180 // Diagnose "string literal" '+' int and string '+' "char literal". 8181 if (Opc == BO_Add) { 8182 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8183 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8184 } 8185 8186 // handle the common case first (both operands are arithmetic). 8187 if (!compType.isNull() && compType->isArithmeticType()) { 8188 if (CompLHSTy) *CompLHSTy = compType; 8189 return compType; 8190 } 8191 8192 // Type-checking. Ultimately the pointer's going to be in PExp; 8193 // note that we bias towards the LHS being the pointer. 8194 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8195 8196 bool isObjCPointer; 8197 if (PExp->getType()->isPointerType()) { 8198 isObjCPointer = false; 8199 } else if (PExp->getType()->isObjCObjectPointerType()) { 8200 isObjCPointer = true; 8201 } else { 8202 std::swap(PExp, IExp); 8203 if (PExp->getType()->isPointerType()) { 8204 isObjCPointer = false; 8205 } else if (PExp->getType()->isObjCObjectPointerType()) { 8206 isObjCPointer = true; 8207 } else { 8208 return InvalidOperands(Loc, LHS, RHS); 8209 } 8210 } 8211 assert(PExp->getType()->isAnyPointerType()); 8212 8213 if (!IExp->getType()->isIntegerType()) 8214 return InvalidOperands(Loc, LHS, RHS); 8215 8216 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8217 return QualType(); 8218 8219 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8220 return QualType(); 8221 8222 // Check array bounds for pointer arithemtic 8223 CheckArrayAccess(PExp, IExp); 8224 8225 if (CompLHSTy) { 8226 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8227 if (LHSTy.isNull()) { 8228 LHSTy = LHS.get()->getType(); 8229 if (LHSTy->isPromotableIntegerType()) 8230 LHSTy = Context.getPromotedIntegerType(LHSTy); 8231 } 8232 *CompLHSTy = LHSTy; 8233 } 8234 8235 return PExp->getType(); 8236 } 8237 8238 // C99 6.5.6 8239 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8240 SourceLocation Loc, 8241 QualType* CompLHSTy) { 8242 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8243 8244 if (LHS.get()->getType()->isVectorType() || 8245 RHS.get()->getType()->isVectorType()) { 8246 QualType compType = CheckVectorOperands( 8247 LHS, RHS, Loc, CompLHSTy, 8248 /*AllowBothBool*/getLangOpts().AltiVec, 8249 /*AllowBoolConversions*/getLangOpts().ZVector); 8250 if (CompLHSTy) *CompLHSTy = compType; 8251 return compType; 8252 } 8253 8254 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8255 if (LHS.isInvalid() || RHS.isInvalid()) 8256 return QualType(); 8257 8258 // Enforce type constraints: C99 6.5.6p3. 8259 8260 // Handle the common case first (both operands are arithmetic). 8261 if (!compType.isNull() && compType->isArithmeticType()) { 8262 if (CompLHSTy) *CompLHSTy = compType; 8263 return compType; 8264 } 8265 8266 // Either ptr - int or ptr - ptr. 8267 if (LHS.get()->getType()->isAnyPointerType()) { 8268 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8269 8270 // Diagnose bad cases where we step over interface counts. 8271 if (LHS.get()->getType()->isObjCObjectPointerType() && 8272 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8273 return QualType(); 8274 8275 // The result type of a pointer-int computation is the pointer type. 8276 if (RHS.get()->getType()->isIntegerType()) { 8277 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8278 return QualType(); 8279 8280 // Check array bounds for pointer arithemtic 8281 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8282 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8283 8284 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8285 return LHS.get()->getType(); 8286 } 8287 8288 // Handle pointer-pointer subtractions. 8289 if (const PointerType *RHSPTy 8290 = RHS.get()->getType()->getAs<PointerType>()) { 8291 QualType rpointee = RHSPTy->getPointeeType(); 8292 8293 if (getLangOpts().CPlusPlus) { 8294 // Pointee types must be the same: C++ [expr.add] 8295 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8296 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8297 } 8298 } else { 8299 // Pointee types must be compatible C99 6.5.6p3 8300 if (!Context.typesAreCompatible( 8301 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8302 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8303 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8304 return QualType(); 8305 } 8306 } 8307 8308 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8309 LHS.get(), RHS.get())) 8310 return QualType(); 8311 8312 // The pointee type may have zero size. As an extension, a structure or 8313 // union may have zero size or an array may have zero length. In this 8314 // case subtraction does not make sense. 8315 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8316 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8317 if (ElementSize.isZero()) { 8318 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8319 << rpointee.getUnqualifiedType() 8320 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8321 } 8322 } 8323 8324 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8325 return Context.getPointerDiffType(); 8326 } 8327 } 8328 8329 return InvalidOperands(Loc, LHS, RHS); 8330 } 8331 8332 static bool isScopedEnumerationType(QualType T) { 8333 if (const EnumType *ET = T->getAs<EnumType>()) 8334 return ET->getDecl()->isScoped(); 8335 return false; 8336 } 8337 8338 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8339 SourceLocation Loc, BinaryOperatorKind Opc, 8340 QualType LHSType) { 8341 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8342 // so skip remaining warnings as we don't want to modify values within Sema. 8343 if (S.getLangOpts().OpenCL) 8344 return; 8345 8346 llvm::APSInt Right; 8347 // Check right/shifter operand 8348 if (RHS.get()->isValueDependent() || 8349 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8350 return; 8351 8352 if (Right.isNegative()) { 8353 S.DiagRuntimeBehavior(Loc, RHS.get(), 8354 S.PDiag(diag::warn_shift_negative) 8355 << RHS.get()->getSourceRange()); 8356 return; 8357 } 8358 llvm::APInt LeftBits(Right.getBitWidth(), 8359 S.Context.getTypeSize(LHS.get()->getType())); 8360 if (Right.uge(LeftBits)) { 8361 S.DiagRuntimeBehavior(Loc, RHS.get(), 8362 S.PDiag(diag::warn_shift_gt_typewidth) 8363 << RHS.get()->getSourceRange()); 8364 return; 8365 } 8366 if (Opc != BO_Shl) 8367 return; 8368 8369 // When left shifting an ICE which is signed, we can check for overflow which 8370 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8371 // integers have defined behavior modulo one more than the maximum value 8372 // representable in the result type, so never warn for those. 8373 llvm::APSInt Left; 8374 if (LHS.get()->isValueDependent() || 8375 LHSType->hasUnsignedIntegerRepresentation() || 8376 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8377 return; 8378 8379 // If LHS does not have a signed type and non-negative value 8380 // then, the behavior is undefined. Warn about it. 8381 if (Left.isNegative()) { 8382 S.DiagRuntimeBehavior(Loc, LHS.get(), 8383 S.PDiag(diag::warn_shift_lhs_negative) 8384 << LHS.get()->getSourceRange()); 8385 return; 8386 } 8387 8388 llvm::APInt ResultBits = 8389 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8390 if (LeftBits.uge(ResultBits)) 8391 return; 8392 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8393 Result = Result.shl(Right); 8394 8395 // Print the bit representation of the signed integer as an unsigned 8396 // hexadecimal number. 8397 SmallString<40> HexResult; 8398 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8399 8400 // If we are only missing a sign bit, this is less likely to result in actual 8401 // bugs -- if the result is cast back to an unsigned type, it will have the 8402 // expected value. Thus we place this behind a different warning that can be 8403 // turned off separately if needed. 8404 if (LeftBits == ResultBits - 1) { 8405 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8406 << HexResult << LHSType 8407 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8408 return; 8409 } 8410 8411 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8412 << HexResult.str() << Result.getMinSignedBits() << LHSType 8413 << Left.getBitWidth() << LHS.get()->getSourceRange() 8414 << RHS.get()->getSourceRange(); 8415 } 8416 8417 /// \brief Return the resulting type when an OpenCL vector is shifted 8418 /// by a scalar or vector shift amount. 8419 static QualType checkOpenCLVectorShift(Sema &S, 8420 ExprResult &LHS, ExprResult &RHS, 8421 SourceLocation Loc, bool IsCompAssign) { 8422 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8423 if (!LHS.get()->getType()->isVectorType()) { 8424 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8425 << RHS.get()->getType() << LHS.get()->getType() 8426 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8427 return QualType(); 8428 } 8429 8430 if (!IsCompAssign) { 8431 LHS = S.UsualUnaryConversions(LHS.get()); 8432 if (LHS.isInvalid()) return QualType(); 8433 } 8434 8435 RHS = S.UsualUnaryConversions(RHS.get()); 8436 if (RHS.isInvalid()) return QualType(); 8437 8438 QualType LHSType = LHS.get()->getType(); 8439 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8440 QualType LHSEleType = LHSVecTy->getElementType(); 8441 8442 // Note that RHS might not be a vector. 8443 QualType RHSType = RHS.get()->getType(); 8444 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8445 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8446 8447 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8448 if (!LHSEleType->isIntegerType()) { 8449 S.Diag(Loc, diag::err_typecheck_expect_int) 8450 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8451 return QualType(); 8452 } 8453 8454 if (!RHSEleType->isIntegerType()) { 8455 S.Diag(Loc, diag::err_typecheck_expect_int) 8456 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8457 return QualType(); 8458 } 8459 8460 if (RHSVecTy) { 8461 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8462 // are applied component-wise. So if RHS is a vector, then ensure 8463 // that the number of elements is the same as LHS... 8464 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8465 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8466 << LHS.get()->getType() << RHS.get()->getType() 8467 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8468 return QualType(); 8469 } 8470 } else { 8471 // ...else expand RHS to match the number of elements in LHS. 8472 QualType VecTy = 8473 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8474 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8475 } 8476 8477 return LHSType; 8478 } 8479 8480 // C99 6.5.7 8481 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8482 SourceLocation Loc, BinaryOperatorKind Opc, 8483 bool IsCompAssign) { 8484 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8485 8486 // Vector shifts promote their scalar inputs to vector type. 8487 if (LHS.get()->getType()->isVectorType() || 8488 RHS.get()->getType()->isVectorType()) { 8489 if (LangOpts.OpenCL) 8490 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8491 if (LangOpts.ZVector) { 8492 // The shift operators for the z vector extensions work basically 8493 // like OpenCL shifts, except that neither the LHS nor the RHS is 8494 // allowed to be a "vector bool". 8495 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8496 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8497 return InvalidOperands(Loc, LHS, RHS); 8498 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8499 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8500 return InvalidOperands(Loc, LHS, RHS); 8501 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8502 } 8503 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8504 /*AllowBothBool*/true, 8505 /*AllowBoolConversions*/false); 8506 } 8507 8508 // Shifts don't perform usual arithmetic conversions, they just do integer 8509 // promotions on each operand. C99 6.5.7p3 8510 8511 // For the LHS, do usual unary conversions, but then reset them away 8512 // if this is a compound assignment. 8513 ExprResult OldLHS = LHS; 8514 LHS = UsualUnaryConversions(LHS.get()); 8515 if (LHS.isInvalid()) 8516 return QualType(); 8517 QualType LHSType = LHS.get()->getType(); 8518 if (IsCompAssign) LHS = OldLHS; 8519 8520 // The RHS is simpler. 8521 RHS = UsualUnaryConversions(RHS.get()); 8522 if (RHS.isInvalid()) 8523 return QualType(); 8524 QualType RHSType = RHS.get()->getType(); 8525 8526 // C99 6.5.7p2: Each of the operands shall have integer type. 8527 if (!LHSType->hasIntegerRepresentation() || 8528 !RHSType->hasIntegerRepresentation()) 8529 return InvalidOperands(Loc, LHS, RHS); 8530 8531 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8532 // hasIntegerRepresentation() above instead of this. 8533 if (isScopedEnumerationType(LHSType) || 8534 isScopedEnumerationType(RHSType)) { 8535 return InvalidOperands(Loc, LHS, RHS); 8536 } 8537 // Sanity-check shift operands 8538 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8539 8540 // "The type of the result is that of the promoted left operand." 8541 return LHSType; 8542 } 8543 8544 static bool IsWithinTemplateSpecialization(Decl *D) { 8545 if (DeclContext *DC = D->getDeclContext()) { 8546 if (isa<ClassTemplateSpecializationDecl>(DC)) 8547 return true; 8548 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8549 return FD->isFunctionTemplateSpecialization(); 8550 } 8551 return false; 8552 } 8553 8554 /// If two different enums are compared, raise a warning. 8555 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8556 Expr *RHS) { 8557 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8558 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8559 8560 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8561 if (!LHSEnumType) 8562 return; 8563 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8564 if (!RHSEnumType) 8565 return; 8566 8567 // Ignore anonymous enums. 8568 if (!LHSEnumType->getDecl()->getIdentifier()) 8569 return; 8570 if (!RHSEnumType->getDecl()->getIdentifier()) 8571 return; 8572 8573 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8574 return; 8575 8576 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8577 << LHSStrippedType << RHSStrippedType 8578 << LHS->getSourceRange() << RHS->getSourceRange(); 8579 } 8580 8581 /// \brief Diagnose bad pointer comparisons. 8582 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8583 ExprResult &LHS, ExprResult &RHS, 8584 bool IsError) { 8585 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8586 : diag::ext_typecheck_comparison_of_distinct_pointers) 8587 << LHS.get()->getType() << RHS.get()->getType() 8588 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8589 } 8590 8591 /// \brief Returns false if the pointers are converted to a composite type, 8592 /// true otherwise. 8593 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8594 ExprResult &LHS, ExprResult &RHS) { 8595 // C++ [expr.rel]p2: 8596 // [...] Pointer conversions (4.10) and qualification 8597 // conversions (4.4) are performed on pointer operands (or on 8598 // a pointer operand and a null pointer constant) to bring 8599 // them to their composite pointer type. [...] 8600 // 8601 // C++ [expr.eq]p1 uses the same notion for (in)equality 8602 // comparisons of pointers. 8603 8604 // C++ [expr.eq]p2: 8605 // In addition, pointers to members can be compared, or a pointer to 8606 // member and a null pointer constant. Pointer to member conversions 8607 // (4.11) and qualification conversions (4.4) are performed to bring 8608 // them to a common type. If one operand is a null pointer constant, 8609 // the common type is the type of the other operand. Otherwise, the 8610 // common type is a pointer to member type similar (4.4) to the type 8611 // of one of the operands, with a cv-qualification signature (4.4) 8612 // that is the union of the cv-qualification signatures of the operand 8613 // types. 8614 8615 QualType LHSType = LHS.get()->getType(); 8616 QualType RHSType = RHS.get()->getType(); 8617 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8618 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8619 8620 bool NonStandardCompositeType = false; 8621 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8622 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8623 if (T.isNull()) { 8624 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8625 return true; 8626 } 8627 8628 if (NonStandardCompositeType) 8629 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8630 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8631 << RHS.get()->getSourceRange(); 8632 8633 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8634 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8635 return false; 8636 } 8637 8638 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8639 ExprResult &LHS, 8640 ExprResult &RHS, 8641 bool IsError) { 8642 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8643 : diag::ext_typecheck_comparison_of_fptr_to_void) 8644 << LHS.get()->getType() << RHS.get()->getType() 8645 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8646 } 8647 8648 static bool isObjCObjectLiteral(ExprResult &E) { 8649 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8650 case Stmt::ObjCArrayLiteralClass: 8651 case Stmt::ObjCDictionaryLiteralClass: 8652 case Stmt::ObjCStringLiteralClass: 8653 case Stmt::ObjCBoxedExprClass: 8654 return true; 8655 default: 8656 // Note that ObjCBoolLiteral is NOT an object literal! 8657 return false; 8658 } 8659 } 8660 8661 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8662 const ObjCObjectPointerType *Type = 8663 LHS->getType()->getAs<ObjCObjectPointerType>(); 8664 8665 // If this is not actually an Objective-C object, bail out. 8666 if (!Type) 8667 return false; 8668 8669 // Get the LHS object's interface type. 8670 QualType InterfaceType = Type->getPointeeType(); 8671 8672 // If the RHS isn't an Objective-C object, bail out. 8673 if (!RHS->getType()->isObjCObjectPointerType()) 8674 return false; 8675 8676 // Try to find the -isEqual: method. 8677 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8678 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8679 InterfaceType, 8680 /*instance=*/true); 8681 if (!Method) { 8682 if (Type->isObjCIdType()) { 8683 // For 'id', just check the global pool. 8684 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8685 /*receiverId=*/true); 8686 } else { 8687 // Check protocols. 8688 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8689 /*instance=*/true); 8690 } 8691 } 8692 8693 if (!Method) 8694 return false; 8695 8696 QualType T = Method->parameters()[0]->getType(); 8697 if (!T->isObjCObjectPointerType()) 8698 return false; 8699 8700 QualType R = Method->getReturnType(); 8701 if (!R->isScalarType()) 8702 return false; 8703 8704 return true; 8705 } 8706 8707 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8708 FromE = FromE->IgnoreParenImpCasts(); 8709 switch (FromE->getStmtClass()) { 8710 default: 8711 break; 8712 case Stmt::ObjCStringLiteralClass: 8713 // "string literal" 8714 return LK_String; 8715 case Stmt::ObjCArrayLiteralClass: 8716 // "array literal" 8717 return LK_Array; 8718 case Stmt::ObjCDictionaryLiteralClass: 8719 // "dictionary literal" 8720 return LK_Dictionary; 8721 case Stmt::BlockExprClass: 8722 return LK_Block; 8723 case Stmt::ObjCBoxedExprClass: { 8724 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8725 switch (Inner->getStmtClass()) { 8726 case Stmt::IntegerLiteralClass: 8727 case Stmt::FloatingLiteralClass: 8728 case Stmt::CharacterLiteralClass: 8729 case Stmt::ObjCBoolLiteralExprClass: 8730 case Stmt::CXXBoolLiteralExprClass: 8731 // "numeric literal" 8732 return LK_Numeric; 8733 case Stmt::ImplicitCastExprClass: { 8734 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8735 // Boolean literals can be represented by implicit casts. 8736 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8737 return LK_Numeric; 8738 break; 8739 } 8740 default: 8741 break; 8742 } 8743 return LK_Boxed; 8744 } 8745 } 8746 return LK_None; 8747 } 8748 8749 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8750 ExprResult &LHS, ExprResult &RHS, 8751 BinaryOperator::Opcode Opc){ 8752 Expr *Literal; 8753 Expr *Other; 8754 if (isObjCObjectLiteral(LHS)) { 8755 Literal = LHS.get(); 8756 Other = RHS.get(); 8757 } else { 8758 Literal = RHS.get(); 8759 Other = LHS.get(); 8760 } 8761 8762 // Don't warn on comparisons against nil. 8763 Other = Other->IgnoreParenCasts(); 8764 if (Other->isNullPointerConstant(S.getASTContext(), 8765 Expr::NPC_ValueDependentIsNotNull)) 8766 return; 8767 8768 // This should be kept in sync with warn_objc_literal_comparison. 8769 // LK_String should always be after the other literals, since it has its own 8770 // warning flag. 8771 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8772 assert(LiteralKind != Sema::LK_Block); 8773 if (LiteralKind == Sema::LK_None) { 8774 llvm_unreachable("Unknown Objective-C object literal kind"); 8775 } 8776 8777 if (LiteralKind == Sema::LK_String) 8778 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8779 << Literal->getSourceRange(); 8780 else 8781 S.Diag(Loc, diag::warn_objc_literal_comparison) 8782 << LiteralKind << Literal->getSourceRange(); 8783 8784 if (BinaryOperator::isEqualityOp(Opc) && 8785 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8786 SourceLocation Start = LHS.get()->getLocStart(); 8787 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 8788 CharSourceRange OpRange = 8789 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 8790 8791 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8792 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8793 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8794 << FixItHint::CreateInsertion(End, "]"); 8795 } 8796 } 8797 8798 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8799 ExprResult &RHS, 8800 SourceLocation Loc, 8801 BinaryOperatorKind Opc) { 8802 // Check that left hand side is !something. 8803 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8804 if (!UO || UO->getOpcode() != UO_LNot) return; 8805 8806 // Only check if the right hand side is non-bool arithmetic type. 8807 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8808 8809 // Make sure that the something in !something is not bool. 8810 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8811 if (SubExpr->isKnownToHaveBooleanValue()) return; 8812 8813 // Emit warning. 8814 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8815 << Loc; 8816 8817 // First note suggest !(x < y) 8818 SourceLocation FirstOpen = SubExpr->getLocStart(); 8819 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8820 FirstClose = S.getLocForEndOfToken(FirstClose); 8821 if (FirstClose.isInvalid()) 8822 FirstOpen = SourceLocation(); 8823 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8824 << FixItHint::CreateInsertion(FirstOpen, "(") 8825 << FixItHint::CreateInsertion(FirstClose, ")"); 8826 8827 // Second note suggests (!x) < y 8828 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8829 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8830 SecondClose = S.getLocForEndOfToken(SecondClose); 8831 if (SecondClose.isInvalid()) 8832 SecondOpen = SourceLocation(); 8833 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8834 << FixItHint::CreateInsertion(SecondOpen, "(") 8835 << FixItHint::CreateInsertion(SecondClose, ")"); 8836 } 8837 8838 // Get the decl for a simple expression: a reference to a variable, 8839 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8840 static ValueDecl *getCompareDecl(Expr *E) { 8841 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8842 return DR->getDecl(); 8843 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8844 if (Ivar->isFreeIvar()) 8845 return Ivar->getDecl(); 8846 } 8847 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8848 if (Mem->isImplicitAccess()) 8849 return Mem->getMemberDecl(); 8850 } 8851 return nullptr; 8852 } 8853 8854 // C99 6.5.8, C++ [expr.rel] 8855 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8856 SourceLocation Loc, BinaryOperatorKind Opc, 8857 bool IsRelational) { 8858 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8859 8860 // Handle vector comparisons separately. 8861 if (LHS.get()->getType()->isVectorType() || 8862 RHS.get()->getType()->isVectorType()) 8863 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8864 8865 QualType LHSType = LHS.get()->getType(); 8866 QualType RHSType = RHS.get()->getType(); 8867 8868 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8869 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8870 8871 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8872 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 8873 8874 if (!LHSType->hasFloatingRepresentation() && 8875 !(LHSType->isBlockPointerType() && IsRelational) && 8876 !LHS.get()->getLocStart().isMacroID() && 8877 !RHS.get()->getLocStart().isMacroID() && 8878 ActiveTemplateInstantiations.empty()) { 8879 // For non-floating point types, check for self-comparisons of the form 8880 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8881 // often indicate logic errors in the program. 8882 // 8883 // NOTE: Don't warn about comparison expressions resulting from macro 8884 // expansion. Also don't warn about comparisons which are only self 8885 // comparisons within a template specialization. The warnings should catch 8886 // obvious cases in the definition of the template anyways. The idea is to 8887 // warn when the typed comparison operator will always evaluate to the same 8888 // result. 8889 ValueDecl *DL = getCompareDecl(LHSStripped); 8890 ValueDecl *DR = getCompareDecl(RHSStripped); 8891 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8892 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8893 << 0 // self- 8894 << (Opc == BO_EQ 8895 || Opc == BO_LE 8896 || Opc == BO_GE)); 8897 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8898 !DL->getType()->isReferenceType() && 8899 !DR->getType()->isReferenceType()) { 8900 // what is it always going to eval to? 8901 char always_evals_to; 8902 switch(Opc) { 8903 case BO_EQ: // e.g. array1 == array2 8904 always_evals_to = 0; // false 8905 break; 8906 case BO_NE: // e.g. array1 != array2 8907 always_evals_to = 1; // true 8908 break; 8909 default: 8910 // best we can say is 'a constant' 8911 always_evals_to = 2; // e.g. array1 <= array2 8912 break; 8913 } 8914 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8915 << 1 // array 8916 << always_evals_to); 8917 } 8918 8919 if (isa<CastExpr>(LHSStripped)) 8920 LHSStripped = LHSStripped->IgnoreParenCasts(); 8921 if (isa<CastExpr>(RHSStripped)) 8922 RHSStripped = RHSStripped->IgnoreParenCasts(); 8923 8924 // Warn about comparisons against a string constant (unless the other 8925 // operand is null), the user probably wants strcmp. 8926 Expr *literalString = nullptr; 8927 Expr *literalStringStripped = nullptr; 8928 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8929 !RHSStripped->isNullPointerConstant(Context, 8930 Expr::NPC_ValueDependentIsNull)) { 8931 literalString = LHS.get(); 8932 literalStringStripped = LHSStripped; 8933 } else if ((isa<StringLiteral>(RHSStripped) || 8934 isa<ObjCEncodeExpr>(RHSStripped)) && 8935 !LHSStripped->isNullPointerConstant(Context, 8936 Expr::NPC_ValueDependentIsNull)) { 8937 literalString = RHS.get(); 8938 literalStringStripped = RHSStripped; 8939 } 8940 8941 if (literalString) { 8942 DiagRuntimeBehavior(Loc, nullptr, 8943 PDiag(diag::warn_stringcompare) 8944 << isa<ObjCEncodeExpr>(literalStringStripped) 8945 << literalString->getSourceRange()); 8946 } 8947 } 8948 8949 // C99 6.5.8p3 / C99 6.5.9p4 8950 UsualArithmeticConversions(LHS, RHS); 8951 if (LHS.isInvalid() || RHS.isInvalid()) 8952 return QualType(); 8953 8954 LHSType = LHS.get()->getType(); 8955 RHSType = RHS.get()->getType(); 8956 8957 // The result of comparisons is 'bool' in C++, 'int' in C. 8958 QualType ResultTy = Context.getLogicalOperationType(); 8959 8960 if (IsRelational) { 8961 if (LHSType->isRealType() && RHSType->isRealType()) 8962 return ResultTy; 8963 } else { 8964 // Check for comparisons of floating point operands using != and ==. 8965 if (LHSType->hasFloatingRepresentation()) 8966 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8967 8968 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8969 return ResultTy; 8970 } 8971 8972 const Expr::NullPointerConstantKind LHSNullKind = 8973 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8974 const Expr::NullPointerConstantKind RHSNullKind = 8975 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8976 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8977 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8978 8979 if (!IsRelational && LHSIsNull != RHSIsNull) { 8980 bool IsEquality = Opc == BO_EQ; 8981 if (RHSIsNull) 8982 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 8983 RHS.get()->getSourceRange()); 8984 else 8985 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 8986 LHS.get()->getSourceRange()); 8987 } 8988 8989 // All of the following pointer-related warnings are GCC extensions, except 8990 // when handling null pointer constants. 8991 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 8992 QualType LCanPointeeTy = 8993 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8994 QualType RCanPointeeTy = 8995 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8996 8997 if (getLangOpts().CPlusPlus) { 8998 if (LCanPointeeTy == RCanPointeeTy) 8999 return ResultTy; 9000 if (!IsRelational && 9001 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9002 // Valid unless comparison between non-null pointer and function pointer 9003 // This is a gcc extension compatibility comparison. 9004 // In a SFINAE context, we treat this as a hard error to maintain 9005 // conformance with the C++ standard. 9006 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9007 && !LHSIsNull && !RHSIsNull) { 9008 diagnoseFunctionPointerToVoidComparison( 9009 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9010 9011 if (isSFINAEContext()) 9012 return QualType(); 9013 9014 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9015 return ResultTy; 9016 } 9017 } 9018 9019 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9020 return QualType(); 9021 else 9022 return ResultTy; 9023 } 9024 // C99 6.5.9p2 and C99 6.5.8p2 9025 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9026 RCanPointeeTy.getUnqualifiedType())) { 9027 // Valid unless a relational comparison of function pointers 9028 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9029 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9030 << LHSType << RHSType << LHS.get()->getSourceRange() 9031 << RHS.get()->getSourceRange(); 9032 } 9033 } else if (!IsRelational && 9034 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9035 // Valid unless comparison between non-null pointer and function pointer 9036 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9037 && !LHSIsNull && !RHSIsNull) 9038 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9039 /*isError*/false); 9040 } else { 9041 // Invalid 9042 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9043 } 9044 if (LCanPointeeTy != RCanPointeeTy) { 9045 // Treat NULL constant as a special case in OpenCL. 9046 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9047 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9048 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9049 Diag(Loc, 9050 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9051 << LHSType << RHSType << 0 /* comparison */ 9052 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9053 } 9054 } 9055 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9056 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9057 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9058 : CK_BitCast; 9059 if (LHSIsNull && !RHSIsNull) 9060 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9061 else 9062 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9063 } 9064 return ResultTy; 9065 } 9066 9067 if (getLangOpts().CPlusPlus) { 9068 // Comparison of nullptr_t with itself. 9069 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9070 return ResultTy; 9071 9072 // Comparison of pointers with null pointer constants and equality 9073 // comparisons of member pointers to null pointer constants. 9074 if (RHSIsNull && 9075 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9076 (!IsRelational && 9077 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9078 RHS = ImpCastExprToType(RHS.get(), LHSType, 9079 LHSType->isMemberPointerType() 9080 ? CK_NullToMemberPointer 9081 : CK_NullToPointer); 9082 return ResultTy; 9083 } 9084 if (LHSIsNull && 9085 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9086 (!IsRelational && 9087 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9088 LHS = ImpCastExprToType(LHS.get(), RHSType, 9089 RHSType->isMemberPointerType() 9090 ? CK_NullToMemberPointer 9091 : CK_NullToPointer); 9092 return ResultTy; 9093 } 9094 9095 // Comparison of member pointers. 9096 if (!IsRelational && 9097 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9098 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9099 return QualType(); 9100 else 9101 return ResultTy; 9102 } 9103 9104 // Handle scoped enumeration types specifically, since they don't promote 9105 // to integers. 9106 if (LHS.get()->getType()->isEnumeralType() && 9107 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9108 RHS.get()->getType())) 9109 return ResultTy; 9110 } 9111 9112 // Handle block pointer types. 9113 if (!IsRelational && LHSType->isBlockPointerType() && 9114 RHSType->isBlockPointerType()) { 9115 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9116 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9117 9118 if (!LHSIsNull && !RHSIsNull && 9119 !Context.typesAreCompatible(lpointee, rpointee)) { 9120 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9121 << LHSType << RHSType << LHS.get()->getSourceRange() 9122 << RHS.get()->getSourceRange(); 9123 } 9124 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9125 return ResultTy; 9126 } 9127 9128 // Allow block pointers to be compared with null pointer constants. 9129 if (!IsRelational 9130 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9131 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9132 if (!LHSIsNull && !RHSIsNull) { 9133 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9134 ->getPointeeType()->isVoidType()) 9135 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9136 ->getPointeeType()->isVoidType()))) 9137 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9138 << LHSType << RHSType << LHS.get()->getSourceRange() 9139 << RHS.get()->getSourceRange(); 9140 } 9141 if (LHSIsNull && !RHSIsNull) 9142 LHS = ImpCastExprToType(LHS.get(), RHSType, 9143 RHSType->isPointerType() ? CK_BitCast 9144 : CK_AnyPointerToBlockPointerCast); 9145 else 9146 RHS = ImpCastExprToType(RHS.get(), LHSType, 9147 LHSType->isPointerType() ? CK_BitCast 9148 : CK_AnyPointerToBlockPointerCast); 9149 return ResultTy; 9150 } 9151 9152 if (LHSType->isObjCObjectPointerType() || 9153 RHSType->isObjCObjectPointerType()) { 9154 const PointerType *LPT = LHSType->getAs<PointerType>(); 9155 const PointerType *RPT = RHSType->getAs<PointerType>(); 9156 if (LPT || RPT) { 9157 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9158 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9159 9160 if (!LPtrToVoid && !RPtrToVoid && 9161 !Context.typesAreCompatible(LHSType, RHSType)) { 9162 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9163 /*isError*/false); 9164 } 9165 if (LHSIsNull && !RHSIsNull) { 9166 Expr *E = LHS.get(); 9167 if (getLangOpts().ObjCAutoRefCount) 9168 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9169 LHS = ImpCastExprToType(E, RHSType, 9170 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9171 } 9172 else { 9173 Expr *E = RHS.get(); 9174 if (getLangOpts().ObjCAutoRefCount) 9175 CheckObjCARCConversion(SourceRange(), LHSType, E, 9176 CCK_ImplicitConversion, /*Diagnose=*/true, 9177 /*DiagnoseCFAudited=*/false, Opc); 9178 RHS = ImpCastExprToType(E, LHSType, 9179 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9180 } 9181 return ResultTy; 9182 } 9183 if (LHSType->isObjCObjectPointerType() && 9184 RHSType->isObjCObjectPointerType()) { 9185 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9186 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9187 /*isError*/false); 9188 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9189 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9190 9191 if (LHSIsNull && !RHSIsNull) 9192 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9193 else 9194 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9195 return ResultTy; 9196 } 9197 } 9198 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9199 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9200 unsigned DiagID = 0; 9201 bool isError = false; 9202 if (LangOpts.DebuggerSupport) { 9203 // Under a debugger, allow the comparison of pointers to integers, 9204 // since users tend to want to compare addresses. 9205 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9206 (RHSIsNull && RHSType->isIntegerType())) { 9207 if (IsRelational && !getLangOpts().CPlusPlus) 9208 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9209 } else if (IsRelational && !getLangOpts().CPlusPlus) 9210 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9211 else if (getLangOpts().CPlusPlus) { 9212 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9213 isError = true; 9214 } else 9215 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9216 9217 if (DiagID) { 9218 Diag(Loc, DiagID) 9219 << LHSType << RHSType << LHS.get()->getSourceRange() 9220 << RHS.get()->getSourceRange(); 9221 if (isError) 9222 return QualType(); 9223 } 9224 9225 if (LHSType->isIntegerType()) 9226 LHS = ImpCastExprToType(LHS.get(), RHSType, 9227 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9228 else 9229 RHS = ImpCastExprToType(RHS.get(), LHSType, 9230 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9231 return ResultTy; 9232 } 9233 9234 // Handle block pointers. 9235 if (!IsRelational && RHSIsNull 9236 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9237 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9238 return ResultTy; 9239 } 9240 if (!IsRelational && LHSIsNull 9241 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9242 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9243 return ResultTy; 9244 } 9245 9246 return InvalidOperands(Loc, LHS, RHS); 9247 } 9248 9249 9250 // Return a signed type that is of identical size and number of elements. 9251 // For floating point vectors, return an integer type of identical size 9252 // and number of elements. 9253 QualType Sema::GetSignedVectorType(QualType V) { 9254 const VectorType *VTy = V->getAs<VectorType>(); 9255 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9256 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9257 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9258 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9259 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9260 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9261 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9262 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9263 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9264 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9265 "Unhandled vector element size in vector compare"); 9266 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9267 } 9268 9269 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9270 /// operates on extended vector types. Instead of producing an IntTy result, 9271 /// like a scalar comparison, a vector comparison produces a vector of integer 9272 /// types. 9273 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9274 SourceLocation Loc, 9275 bool IsRelational) { 9276 // Check to make sure we're operating on vectors of the same type and width, 9277 // Allowing one side to be a scalar of element type. 9278 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9279 /*AllowBothBool*/true, 9280 /*AllowBoolConversions*/getLangOpts().ZVector); 9281 if (vType.isNull()) 9282 return vType; 9283 9284 QualType LHSType = LHS.get()->getType(); 9285 9286 // If AltiVec, the comparison results in a numeric type, i.e. 9287 // bool for C++, int for C 9288 if (getLangOpts().AltiVec && 9289 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9290 return Context.getLogicalOperationType(); 9291 9292 // For non-floating point types, check for self-comparisons of the form 9293 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9294 // often indicate logic errors in the program. 9295 if (!LHSType->hasFloatingRepresentation() && 9296 ActiveTemplateInstantiations.empty()) { 9297 if (DeclRefExpr* DRL 9298 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9299 if (DeclRefExpr* DRR 9300 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9301 if (DRL->getDecl() == DRR->getDecl()) 9302 DiagRuntimeBehavior(Loc, nullptr, 9303 PDiag(diag::warn_comparison_always) 9304 << 0 // self- 9305 << 2 // "a constant" 9306 ); 9307 } 9308 9309 // Check for comparisons of floating point operands using != and ==. 9310 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9311 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9312 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9313 } 9314 9315 // Return a signed type for the vector. 9316 return GetSignedVectorType(LHSType); 9317 } 9318 9319 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9320 SourceLocation Loc) { 9321 // Ensure that either both operands are of the same vector type, or 9322 // one operand is of a vector type and the other is of its element type. 9323 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9324 /*AllowBothBool*/true, 9325 /*AllowBoolConversions*/false); 9326 if (vType.isNull()) 9327 return InvalidOperands(Loc, LHS, RHS); 9328 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9329 vType->hasFloatingRepresentation()) 9330 return InvalidOperands(Loc, LHS, RHS); 9331 9332 return GetSignedVectorType(LHS.get()->getType()); 9333 } 9334 9335 inline QualType Sema::CheckBitwiseOperands( 9336 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9337 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9338 9339 if (LHS.get()->getType()->isVectorType() || 9340 RHS.get()->getType()->isVectorType()) { 9341 if (LHS.get()->getType()->hasIntegerRepresentation() && 9342 RHS.get()->getType()->hasIntegerRepresentation()) 9343 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9344 /*AllowBothBool*/true, 9345 /*AllowBoolConversions*/getLangOpts().ZVector); 9346 return InvalidOperands(Loc, LHS, RHS); 9347 } 9348 9349 ExprResult LHSResult = LHS, RHSResult = RHS; 9350 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9351 IsCompAssign); 9352 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9353 return QualType(); 9354 LHS = LHSResult.get(); 9355 RHS = RHSResult.get(); 9356 9357 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9358 return compType; 9359 return InvalidOperands(Loc, LHS, RHS); 9360 } 9361 9362 // C99 6.5.[13,14] 9363 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9364 SourceLocation Loc, 9365 BinaryOperatorKind Opc) { 9366 // Check vector operands differently. 9367 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9368 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9369 9370 // Diagnose cases where the user write a logical and/or but probably meant a 9371 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9372 // is a constant. 9373 if (LHS.get()->getType()->isIntegerType() && 9374 !LHS.get()->getType()->isBooleanType() && 9375 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9376 // Don't warn in macros or template instantiations. 9377 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9378 // If the RHS can be constant folded, and if it constant folds to something 9379 // that isn't 0 or 1 (which indicate a potential logical operation that 9380 // happened to fold to true/false) then warn. 9381 // Parens on the RHS are ignored. 9382 llvm::APSInt Result; 9383 if (RHS.get()->EvaluateAsInt(Result, Context)) 9384 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9385 !RHS.get()->getExprLoc().isMacroID()) || 9386 (Result != 0 && Result != 1)) { 9387 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9388 << RHS.get()->getSourceRange() 9389 << (Opc == BO_LAnd ? "&&" : "||"); 9390 // Suggest replacing the logical operator with the bitwise version 9391 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9392 << (Opc == BO_LAnd ? "&" : "|") 9393 << FixItHint::CreateReplacement(SourceRange( 9394 Loc, getLocForEndOfToken(Loc)), 9395 Opc == BO_LAnd ? "&" : "|"); 9396 if (Opc == BO_LAnd) 9397 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9398 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9399 << FixItHint::CreateRemoval( 9400 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9401 RHS.get()->getLocEnd())); 9402 } 9403 } 9404 9405 if (!Context.getLangOpts().CPlusPlus) { 9406 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9407 // not operate on the built-in scalar and vector float types. 9408 if (Context.getLangOpts().OpenCL && 9409 Context.getLangOpts().OpenCLVersion < 120) { 9410 if (LHS.get()->getType()->isFloatingType() || 9411 RHS.get()->getType()->isFloatingType()) 9412 return InvalidOperands(Loc, LHS, RHS); 9413 } 9414 9415 LHS = UsualUnaryConversions(LHS.get()); 9416 if (LHS.isInvalid()) 9417 return QualType(); 9418 9419 RHS = UsualUnaryConversions(RHS.get()); 9420 if (RHS.isInvalid()) 9421 return QualType(); 9422 9423 if (!LHS.get()->getType()->isScalarType() || 9424 !RHS.get()->getType()->isScalarType()) 9425 return InvalidOperands(Loc, LHS, RHS); 9426 9427 return Context.IntTy; 9428 } 9429 9430 // The following is safe because we only use this method for 9431 // non-overloadable operands. 9432 9433 // C++ [expr.log.and]p1 9434 // C++ [expr.log.or]p1 9435 // The operands are both contextually converted to type bool. 9436 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9437 if (LHSRes.isInvalid()) 9438 return InvalidOperands(Loc, LHS, RHS); 9439 LHS = LHSRes; 9440 9441 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9442 if (RHSRes.isInvalid()) 9443 return InvalidOperands(Loc, LHS, RHS); 9444 RHS = RHSRes; 9445 9446 // C++ [expr.log.and]p2 9447 // C++ [expr.log.or]p2 9448 // The result is a bool. 9449 return Context.BoolTy; 9450 } 9451 9452 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9453 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9454 if (!ME) return false; 9455 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9456 ObjCMessageExpr *Base = 9457 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9458 if (!Base) return false; 9459 return Base->getMethodDecl() != nullptr; 9460 } 9461 9462 /// Is the given expression (which must be 'const') a reference to a 9463 /// variable which was originally non-const, but which has become 9464 /// 'const' due to being captured within a block? 9465 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9466 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9467 assert(E->isLValue() && E->getType().isConstQualified()); 9468 E = E->IgnoreParens(); 9469 9470 // Must be a reference to a declaration from an enclosing scope. 9471 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9472 if (!DRE) return NCCK_None; 9473 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9474 9475 // The declaration must be a variable which is not declared 'const'. 9476 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9477 if (!var) return NCCK_None; 9478 if (var->getType().isConstQualified()) return NCCK_None; 9479 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9480 9481 // Decide whether the first capture was for a block or a lambda. 9482 DeclContext *DC = S.CurContext, *Prev = nullptr; 9483 while (DC != var->getDeclContext()) { 9484 Prev = DC; 9485 DC = DC->getParent(); 9486 } 9487 // Unless we have an init-capture, we've gone one step too far. 9488 if (!var->isInitCapture()) 9489 DC = Prev; 9490 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9491 } 9492 9493 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9494 Ty = Ty.getNonReferenceType(); 9495 if (IsDereference && Ty->isPointerType()) 9496 Ty = Ty->getPointeeType(); 9497 return !Ty.isConstQualified(); 9498 } 9499 9500 /// Emit the "read-only variable not assignable" error and print notes to give 9501 /// more information about why the variable is not assignable, such as pointing 9502 /// to the declaration of a const variable, showing that a method is const, or 9503 /// that the function is returning a const reference. 9504 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9505 SourceLocation Loc) { 9506 // Update err_typecheck_assign_const and note_typecheck_assign_const 9507 // when this enum is changed. 9508 enum { 9509 ConstFunction, 9510 ConstVariable, 9511 ConstMember, 9512 ConstMethod, 9513 ConstUnknown, // Keep as last element 9514 }; 9515 9516 SourceRange ExprRange = E->getSourceRange(); 9517 9518 // Only emit one error on the first const found. All other consts will emit 9519 // a note to the error. 9520 bool DiagnosticEmitted = false; 9521 9522 // Track if the current expression is the result of a derefence, and if the 9523 // next checked expression is the result of a derefence. 9524 bool IsDereference = false; 9525 bool NextIsDereference = false; 9526 9527 // Loop to process MemberExpr chains. 9528 while (true) { 9529 IsDereference = NextIsDereference; 9530 NextIsDereference = false; 9531 9532 E = E->IgnoreParenImpCasts(); 9533 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9534 NextIsDereference = ME->isArrow(); 9535 const ValueDecl *VD = ME->getMemberDecl(); 9536 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9537 // Mutable fields can be modified even if the class is const. 9538 if (Field->isMutable()) { 9539 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9540 break; 9541 } 9542 9543 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9544 if (!DiagnosticEmitted) { 9545 S.Diag(Loc, diag::err_typecheck_assign_const) 9546 << ExprRange << ConstMember << false /*static*/ << Field 9547 << Field->getType(); 9548 DiagnosticEmitted = true; 9549 } 9550 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9551 << ConstMember << false /*static*/ << Field << Field->getType() 9552 << Field->getSourceRange(); 9553 } 9554 E = ME->getBase(); 9555 continue; 9556 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9557 if (VDecl->getType().isConstQualified()) { 9558 if (!DiagnosticEmitted) { 9559 S.Diag(Loc, diag::err_typecheck_assign_const) 9560 << ExprRange << ConstMember << true /*static*/ << VDecl 9561 << VDecl->getType(); 9562 DiagnosticEmitted = true; 9563 } 9564 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9565 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9566 << VDecl->getSourceRange(); 9567 } 9568 // Static fields do not inherit constness from parents. 9569 break; 9570 } 9571 break; 9572 } // End MemberExpr 9573 break; 9574 } 9575 9576 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9577 // Function calls 9578 const FunctionDecl *FD = CE->getDirectCallee(); 9579 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9580 if (!DiagnosticEmitted) { 9581 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9582 << ConstFunction << FD; 9583 DiagnosticEmitted = true; 9584 } 9585 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9586 diag::note_typecheck_assign_const) 9587 << ConstFunction << FD << FD->getReturnType() 9588 << FD->getReturnTypeSourceRange(); 9589 } 9590 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9591 // Point to variable declaration. 9592 if (const ValueDecl *VD = DRE->getDecl()) { 9593 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9594 if (!DiagnosticEmitted) { 9595 S.Diag(Loc, diag::err_typecheck_assign_const) 9596 << ExprRange << ConstVariable << VD << VD->getType(); 9597 DiagnosticEmitted = true; 9598 } 9599 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9600 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9601 } 9602 } 9603 } else if (isa<CXXThisExpr>(E)) { 9604 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9605 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9606 if (MD->isConst()) { 9607 if (!DiagnosticEmitted) { 9608 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9609 << ConstMethod << MD; 9610 DiagnosticEmitted = true; 9611 } 9612 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9613 << ConstMethod << MD << MD->getSourceRange(); 9614 } 9615 } 9616 } 9617 } 9618 9619 if (DiagnosticEmitted) 9620 return; 9621 9622 // Can't determine a more specific message, so display the generic error. 9623 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9624 } 9625 9626 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9627 /// emit an error and return true. If so, return false. 9628 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9629 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9630 SourceLocation OrigLoc = Loc; 9631 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9632 &Loc); 9633 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9634 IsLV = Expr::MLV_InvalidMessageExpression; 9635 if (IsLV == Expr::MLV_Valid) 9636 return false; 9637 9638 unsigned DiagID = 0; 9639 bool NeedType = false; 9640 switch (IsLV) { // C99 6.5.16p2 9641 case Expr::MLV_ConstQualified: 9642 // Use a specialized diagnostic when we're assigning to an object 9643 // from an enclosing function or block. 9644 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9645 if (NCCK == NCCK_Block) 9646 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9647 else 9648 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9649 break; 9650 } 9651 9652 // In ARC, use some specialized diagnostics for occasions where we 9653 // infer 'const'. These are always pseudo-strong variables. 9654 if (S.getLangOpts().ObjCAutoRefCount) { 9655 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9656 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9657 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9658 9659 // Use the normal diagnostic if it's pseudo-__strong but the 9660 // user actually wrote 'const'. 9661 if (var->isARCPseudoStrong() && 9662 (!var->getTypeSourceInfo() || 9663 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9664 // There are two pseudo-strong cases: 9665 // - self 9666 ObjCMethodDecl *method = S.getCurMethodDecl(); 9667 if (method && var == method->getSelfDecl()) 9668 DiagID = method->isClassMethod() 9669 ? diag::err_typecheck_arc_assign_self_class_method 9670 : diag::err_typecheck_arc_assign_self; 9671 9672 // - fast enumeration variables 9673 else 9674 DiagID = diag::err_typecheck_arr_assign_enumeration; 9675 9676 SourceRange Assign; 9677 if (Loc != OrigLoc) 9678 Assign = SourceRange(OrigLoc, OrigLoc); 9679 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9680 // We need to preserve the AST regardless, so migration tool 9681 // can do its job. 9682 return false; 9683 } 9684 } 9685 } 9686 9687 // If none of the special cases above are triggered, then this is a 9688 // simple const assignment. 9689 if (DiagID == 0) { 9690 DiagnoseConstAssignment(S, E, Loc); 9691 return true; 9692 } 9693 9694 break; 9695 case Expr::MLV_ConstAddrSpace: 9696 DiagnoseConstAssignment(S, E, Loc); 9697 return true; 9698 case Expr::MLV_ArrayType: 9699 case Expr::MLV_ArrayTemporary: 9700 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9701 NeedType = true; 9702 break; 9703 case Expr::MLV_NotObjectType: 9704 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9705 NeedType = true; 9706 break; 9707 case Expr::MLV_LValueCast: 9708 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9709 break; 9710 case Expr::MLV_Valid: 9711 llvm_unreachable("did not take early return for MLV_Valid"); 9712 case Expr::MLV_InvalidExpression: 9713 case Expr::MLV_MemberFunction: 9714 case Expr::MLV_ClassTemporary: 9715 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9716 break; 9717 case Expr::MLV_IncompleteType: 9718 case Expr::MLV_IncompleteVoidType: 9719 return S.RequireCompleteType(Loc, E->getType(), 9720 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9721 case Expr::MLV_DuplicateVectorComponents: 9722 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9723 break; 9724 case Expr::MLV_NoSetterProperty: 9725 llvm_unreachable("readonly properties should be processed differently"); 9726 case Expr::MLV_InvalidMessageExpression: 9727 DiagID = diag::error_readonly_message_assignment; 9728 break; 9729 case Expr::MLV_SubObjCPropertySetting: 9730 DiagID = diag::error_no_subobject_property_setting; 9731 break; 9732 } 9733 9734 SourceRange Assign; 9735 if (Loc != OrigLoc) 9736 Assign = SourceRange(OrigLoc, OrigLoc); 9737 if (NeedType) 9738 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9739 else 9740 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9741 return true; 9742 } 9743 9744 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9745 SourceLocation Loc, 9746 Sema &Sema) { 9747 // C / C++ fields 9748 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9749 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9750 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9751 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9752 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9753 } 9754 9755 // Objective-C instance variables 9756 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9757 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9758 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9759 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9760 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9761 if (RL && RR && RL->getDecl() == RR->getDecl()) 9762 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9763 } 9764 } 9765 9766 // C99 6.5.16.1 9767 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9768 SourceLocation Loc, 9769 QualType CompoundType) { 9770 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9771 9772 // Verify that LHS is a modifiable lvalue, and emit error if not. 9773 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9774 return QualType(); 9775 9776 QualType LHSType = LHSExpr->getType(); 9777 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9778 CompoundType; 9779 AssignConvertType ConvTy; 9780 if (CompoundType.isNull()) { 9781 Expr *RHSCheck = RHS.get(); 9782 9783 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9784 9785 QualType LHSTy(LHSType); 9786 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9787 if (RHS.isInvalid()) 9788 return QualType(); 9789 // Special case of NSObject attributes on c-style pointer types. 9790 if (ConvTy == IncompatiblePointer && 9791 ((Context.isObjCNSObjectType(LHSType) && 9792 RHSType->isObjCObjectPointerType()) || 9793 (Context.isObjCNSObjectType(RHSType) && 9794 LHSType->isObjCObjectPointerType()))) 9795 ConvTy = Compatible; 9796 9797 if (ConvTy == Compatible && 9798 LHSType->isObjCObjectType()) 9799 Diag(Loc, diag::err_objc_object_assignment) 9800 << LHSType; 9801 9802 // If the RHS is a unary plus or minus, check to see if they = and + are 9803 // right next to each other. If so, the user may have typo'd "x =+ 4" 9804 // instead of "x += 4". 9805 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9806 RHSCheck = ICE->getSubExpr(); 9807 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9808 if ((UO->getOpcode() == UO_Plus || 9809 UO->getOpcode() == UO_Minus) && 9810 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9811 // Only if the two operators are exactly adjacent. 9812 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9813 // And there is a space or other character before the subexpr of the 9814 // unary +/-. We don't want to warn on "x=-1". 9815 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9816 UO->getSubExpr()->getLocStart().isFileID()) { 9817 Diag(Loc, diag::warn_not_compound_assign) 9818 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9819 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9820 } 9821 } 9822 9823 if (ConvTy == Compatible) { 9824 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9825 // Warn about retain cycles where a block captures the LHS, but 9826 // not if the LHS is a simple variable into which the block is 9827 // being stored...unless that variable can be captured by reference! 9828 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9829 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9830 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9831 checkRetainCycles(LHSExpr, RHS.get()); 9832 9833 // It is safe to assign a weak reference into a strong variable. 9834 // Although this code can still have problems: 9835 // id x = self.weakProp; 9836 // id y = self.weakProp; 9837 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9838 // paths through the function. This should be revisited if 9839 // -Wrepeated-use-of-weak is made flow-sensitive. 9840 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9841 RHS.get()->getLocStart())) 9842 getCurFunction()->markSafeWeakUse(RHS.get()); 9843 9844 } else if (getLangOpts().ObjCAutoRefCount) { 9845 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9846 } 9847 } 9848 } else { 9849 // Compound assignment "x += y" 9850 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9851 } 9852 9853 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9854 RHS.get(), AA_Assigning)) 9855 return QualType(); 9856 9857 CheckForNullPointerDereference(*this, LHSExpr); 9858 9859 // C99 6.5.16p3: The type of an assignment expression is the type of the 9860 // left operand unless the left operand has qualified type, in which case 9861 // it is the unqualified version of the type of the left operand. 9862 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9863 // is converted to the type of the assignment expression (above). 9864 // C++ 5.17p1: the type of the assignment expression is that of its left 9865 // operand. 9866 return (getLangOpts().CPlusPlus 9867 ? LHSType : LHSType.getUnqualifiedType()); 9868 } 9869 9870 // Only ignore explicit casts to void. 9871 static bool IgnoreCommaOperand(const Expr *E) { 9872 E = E->IgnoreParens(); 9873 9874 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 9875 if (CE->getCastKind() == CK_ToVoid) { 9876 return true; 9877 } 9878 } 9879 9880 return false; 9881 } 9882 9883 // Look for instances where it is likely the comma operator is confused with 9884 // another operator. There is a whitelist of acceptable expressions for the 9885 // left hand side of the comma operator, otherwise emit a warning. 9886 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 9887 // No warnings in macros 9888 if (Loc.isMacroID()) 9889 return; 9890 9891 // Don't warn in template instantiations. 9892 if (!ActiveTemplateInstantiations.empty()) 9893 return; 9894 9895 // Scope isn't fine-grained enough to whitelist the specific cases, so 9896 // instead, skip more than needed, then call back into here with the 9897 // CommaVisitor in SemaStmt.cpp. 9898 // The whitelisted locations are the initialization and increment portions 9899 // of a for loop. The additional checks are on the condition of 9900 // if statements, do/while loops, and for loops. 9901 const unsigned ForIncrementFlags = 9902 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 9903 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 9904 const unsigned ScopeFlags = getCurScope()->getFlags(); 9905 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 9906 (ScopeFlags & ForInitFlags) == ForInitFlags) 9907 return; 9908 9909 // If there are multiple comma operators used together, get the RHS of the 9910 // of the comma operator as the LHS. 9911 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 9912 if (BO->getOpcode() != BO_Comma) 9913 break; 9914 LHS = BO->getRHS(); 9915 } 9916 9917 // Only allow some expressions on LHS to not warn. 9918 if (IgnoreCommaOperand(LHS)) 9919 return; 9920 9921 Diag(Loc, diag::warn_comma_operator); 9922 Diag(LHS->getLocStart(), diag::note_cast_to_void) 9923 << LHS->getSourceRange() 9924 << FixItHint::CreateInsertion(LHS->getLocStart(), 9925 LangOpts.CPlusPlus ? "static_cast<void>(" 9926 : "(void)(") 9927 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 9928 ")"); 9929 } 9930 9931 // C99 6.5.17 9932 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9933 SourceLocation Loc) { 9934 LHS = S.CheckPlaceholderExpr(LHS.get()); 9935 RHS = S.CheckPlaceholderExpr(RHS.get()); 9936 if (LHS.isInvalid() || RHS.isInvalid()) 9937 return QualType(); 9938 9939 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9940 // operands, but not unary promotions. 9941 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9942 9943 // So we treat the LHS as a ignored value, and in C++ we allow the 9944 // containing site to determine what should be done with the RHS. 9945 LHS = S.IgnoredValueConversions(LHS.get()); 9946 if (LHS.isInvalid()) 9947 return QualType(); 9948 9949 S.DiagnoseUnusedExprResult(LHS.get()); 9950 9951 if (!S.getLangOpts().CPlusPlus) { 9952 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9953 if (RHS.isInvalid()) 9954 return QualType(); 9955 if (!RHS.get()->getType()->isVoidType()) 9956 S.RequireCompleteType(Loc, RHS.get()->getType(), 9957 diag::err_incomplete_type); 9958 } 9959 9960 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 9961 S.DiagnoseCommaOperator(LHS.get(), Loc); 9962 9963 return RHS.get()->getType(); 9964 } 9965 9966 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9967 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9968 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9969 ExprValueKind &VK, 9970 ExprObjectKind &OK, 9971 SourceLocation OpLoc, 9972 bool IsInc, bool IsPrefix) { 9973 if (Op->isTypeDependent()) 9974 return S.Context.DependentTy; 9975 9976 QualType ResType = Op->getType(); 9977 // Atomic types can be used for increment / decrement where the non-atomic 9978 // versions can, so ignore the _Atomic() specifier for the purpose of 9979 // checking. 9980 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9981 ResType = ResAtomicType->getValueType(); 9982 9983 assert(!ResType.isNull() && "no type for increment/decrement expression"); 9984 9985 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 9986 // Decrement of bool is not allowed. 9987 if (!IsInc) { 9988 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 9989 return QualType(); 9990 } 9991 // Increment of bool sets it to true, but is deprecated. 9992 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 9993 : diag::warn_increment_bool) 9994 << Op->getSourceRange(); 9995 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 9996 // Error on enum increments and decrements in C++ mode 9997 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 9998 return QualType(); 9999 } else if (ResType->isRealType()) { 10000 // OK! 10001 } else if (ResType->isPointerType()) { 10002 // C99 6.5.2.4p2, 6.5.6p2 10003 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10004 return QualType(); 10005 } else if (ResType->isObjCObjectPointerType()) { 10006 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10007 // Otherwise, we just need a complete type. 10008 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10009 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10010 return QualType(); 10011 } else if (ResType->isAnyComplexType()) { 10012 // C99 does not support ++/-- on complex types, we allow as an extension. 10013 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10014 << ResType << Op->getSourceRange(); 10015 } else if (ResType->isPlaceholderType()) { 10016 ExprResult PR = S.CheckPlaceholderExpr(Op); 10017 if (PR.isInvalid()) return QualType(); 10018 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10019 IsInc, IsPrefix); 10020 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10021 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10022 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10023 (ResType->getAs<VectorType>()->getVectorKind() != 10024 VectorType::AltiVecBool)) { 10025 // The z vector extensions allow ++ and -- for non-bool vectors. 10026 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10027 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10028 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10029 } else { 10030 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10031 << ResType << int(IsInc) << Op->getSourceRange(); 10032 return QualType(); 10033 } 10034 // At this point, we know we have a real, complex or pointer type. 10035 // Now make sure the operand is a modifiable lvalue. 10036 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10037 return QualType(); 10038 // In C++, a prefix increment is the same type as the operand. Otherwise 10039 // (in C or with postfix), the increment is the unqualified type of the 10040 // operand. 10041 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10042 VK = VK_LValue; 10043 OK = Op->getObjectKind(); 10044 return ResType; 10045 } else { 10046 VK = VK_RValue; 10047 return ResType.getUnqualifiedType(); 10048 } 10049 } 10050 10051 10052 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10053 /// This routine allows us to typecheck complex/recursive expressions 10054 /// where the declaration is needed for type checking. We only need to 10055 /// handle cases when the expression references a function designator 10056 /// or is an lvalue. Here are some examples: 10057 /// - &(x) => x 10058 /// - &*****f => f for f a function designator. 10059 /// - &s.xx => s 10060 /// - &s.zz[1].yy -> s, if zz is an array 10061 /// - *(x + 1) -> x, if x is an array 10062 /// - &"123"[2] -> 0 10063 /// - & __real__ x -> x 10064 static ValueDecl *getPrimaryDecl(Expr *E) { 10065 switch (E->getStmtClass()) { 10066 case Stmt::DeclRefExprClass: 10067 return cast<DeclRefExpr>(E)->getDecl(); 10068 case Stmt::MemberExprClass: 10069 // If this is an arrow operator, the address is an offset from 10070 // the base's value, so the object the base refers to is 10071 // irrelevant. 10072 if (cast<MemberExpr>(E)->isArrow()) 10073 return nullptr; 10074 // Otherwise, the expression refers to a part of the base 10075 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10076 case Stmt::ArraySubscriptExprClass: { 10077 // FIXME: This code shouldn't be necessary! We should catch the implicit 10078 // promotion of register arrays earlier. 10079 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10080 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10081 if (ICE->getSubExpr()->getType()->isArrayType()) 10082 return getPrimaryDecl(ICE->getSubExpr()); 10083 } 10084 return nullptr; 10085 } 10086 case Stmt::UnaryOperatorClass: { 10087 UnaryOperator *UO = cast<UnaryOperator>(E); 10088 10089 switch(UO->getOpcode()) { 10090 case UO_Real: 10091 case UO_Imag: 10092 case UO_Extension: 10093 return getPrimaryDecl(UO->getSubExpr()); 10094 default: 10095 return nullptr; 10096 } 10097 } 10098 case Stmt::ParenExprClass: 10099 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10100 case Stmt::ImplicitCastExprClass: 10101 // If the result of an implicit cast is an l-value, we care about 10102 // the sub-expression; otherwise, the result here doesn't matter. 10103 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10104 default: 10105 return nullptr; 10106 } 10107 } 10108 10109 namespace { 10110 enum { 10111 AO_Bit_Field = 0, 10112 AO_Vector_Element = 1, 10113 AO_Property_Expansion = 2, 10114 AO_Register_Variable = 3, 10115 AO_No_Error = 4 10116 }; 10117 } 10118 /// \brief Diagnose invalid operand for address of operations. 10119 /// 10120 /// \param Type The type of operand which cannot have its address taken. 10121 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10122 Expr *E, unsigned Type) { 10123 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10124 } 10125 10126 /// CheckAddressOfOperand - The operand of & must be either a function 10127 /// designator or an lvalue designating an object. If it is an lvalue, the 10128 /// object cannot be declared with storage class register or be a bit field. 10129 /// Note: The usual conversions are *not* applied to the operand of the & 10130 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10131 /// In C++, the operand might be an overloaded function name, in which case 10132 /// we allow the '&' but retain the overloaded-function type. 10133 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10134 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10135 if (PTy->getKind() == BuiltinType::Overload) { 10136 Expr *E = OrigOp.get()->IgnoreParens(); 10137 if (!isa<OverloadExpr>(E)) { 10138 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10139 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10140 << OrigOp.get()->getSourceRange(); 10141 return QualType(); 10142 } 10143 10144 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10145 if (isa<UnresolvedMemberExpr>(Ovl)) 10146 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10147 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10148 << OrigOp.get()->getSourceRange(); 10149 return QualType(); 10150 } 10151 10152 return Context.OverloadTy; 10153 } 10154 10155 if (PTy->getKind() == BuiltinType::UnknownAny) 10156 return Context.UnknownAnyTy; 10157 10158 if (PTy->getKind() == BuiltinType::BoundMember) { 10159 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10160 << OrigOp.get()->getSourceRange(); 10161 return QualType(); 10162 } 10163 10164 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10165 if (OrigOp.isInvalid()) return QualType(); 10166 } 10167 10168 if (OrigOp.get()->isTypeDependent()) 10169 return Context.DependentTy; 10170 10171 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10172 10173 // Make sure to ignore parentheses in subsequent checks 10174 Expr *op = OrigOp.get()->IgnoreParens(); 10175 10176 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10177 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10178 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10179 return QualType(); 10180 } 10181 10182 if (getLangOpts().C99) { 10183 // Implement C99-only parts of addressof rules. 10184 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10185 if (uOp->getOpcode() == UO_Deref) 10186 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10187 // (assuming the deref expression is valid). 10188 return uOp->getSubExpr()->getType(); 10189 } 10190 // Technically, there should be a check for array subscript 10191 // expressions here, but the result of one is always an lvalue anyway. 10192 } 10193 ValueDecl *dcl = getPrimaryDecl(op); 10194 10195 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10196 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10197 op->getLocStart())) 10198 return QualType(); 10199 10200 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10201 unsigned AddressOfError = AO_No_Error; 10202 10203 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10204 bool sfinae = (bool)isSFINAEContext(); 10205 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10206 : diag::ext_typecheck_addrof_temporary) 10207 << op->getType() << op->getSourceRange(); 10208 if (sfinae) 10209 return QualType(); 10210 // Materialize the temporary as an lvalue so that we can take its address. 10211 OrigOp = op = new (Context) 10212 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10213 } else if (isa<ObjCSelectorExpr>(op)) { 10214 return Context.getPointerType(op->getType()); 10215 } else if (lval == Expr::LV_MemberFunction) { 10216 // If it's an instance method, make a member pointer. 10217 // The expression must have exactly the form &A::foo. 10218 10219 // If the underlying expression isn't a decl ref, give up. 10220 if (!isa<DeclRefExpr>(op)) { 10221 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10222 << OrigOp.get()->getSourceRange(); 10223 return QualType(); 10224 } 10225 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10226 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10227 10228 // The id-expression was parenthesized. 10229 if (OrigOp.get() != DRE) { 10230 Diag(OpLoc, diag::err_parens_pointer_member_function) 10231 << OrigOp.get()->getSourceRange(); 10232 10233 // The method was named without a qualifier. 10234 } else if (!DRE->getQualifier()) { 10235 if (MD->getParent()->getName().empty()) 10236 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10237 << op->getSourceRange(); 10238 else { 10239 SmallString<32> Str; 10240 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10241 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10242 << op->getSourceRange() 10243 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10244 } 10245 } 10246 10247 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10248 if (isa<CXXDestructorDecl>(MD)) 10249 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10250 10251 QualType MPTy = Context.getMemberPointerType( 10252 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10253 // Under the MS ABI, lock down the inheritance model now. 10254 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10255 (void)isCompleteType(OpLoc, MPTy); 10256 return MPTy; 10257 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10258 // C99 6.5.3.2p1 10259 // The operand must be either an l-value or a function designator 10260 if (!op->getType()->isFunctionType()) { 10261 // Use a special diagnostic for loads from property references. 10262 if (isa<PseudoObjectExpr>(op)) { 10263 AddressOfError = AO_Property_Expansion; 10264 } else { 10265 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10266 << op->getType() << op->getSourceRange(); 10267 return QualType(); 10268 } 10269 } 10270 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10271 // The operand cannot be a bit-field 10272 AddressOfError = AO_Bit_Field; 10273 } else if (op->getObjectKind() == OK_VectorComponent) { 10274 // The operand cannot be an element of a vector 10275 AddressOfError = AO_Vector_Element; 10276 } else if (dcl) { // C99 6.5.3.2p1 10277 // We have an lvalue with a decl. Make sure the decl is not declared 10278 // with the register storage-class specifier. 10279 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10280 // in C++ it is not error to take address of a register 10281 // variable (c++03 7.1.1P3) 10282 if (vd->getStorageClass() == SC_Register && 10283 !getLangOpts().CPlusPlus) { 10284 AddressOfError = AO_Register_Variable; 10285 } 10286 } else if (isa<MSPropertyDecl>(dcl)) { 10287 AddressOfError = AO_Property_Expansion; 10288 } else if (isa<FunctionTemplateDecl>(dcl)) { 10289 return Context.OverloadTy; 10290 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10291 // Okay: we can take the address of a field. 10292 // Could be a pointer to member, though, if there is an explicit 10293 // scope qualifier for the class. 10294 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10295 DeclContext *Ctx = dcl->getDeclContext(); 10296 if (Ctx && Ctx->isRecord()) { 10297 if (dcl->getType()->isReferenceType()) { 10298 Diag(OpLoc, 10299 diag::err_cannot_form_pointer_to_member_of_reference_type) 10300 << dcl->getDeclName() << dcl->getType(); 10301 return QualType(); 10302 } 10303 10304 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10305 Ctx = Ctx->getParent(); 10306 10307 QualType MPTy = Context.getMemberPointerType( 10308 op->getType(), 10309 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10310 // Under the MS ABI, lock down the inheritance model now. 10311 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10312 (void)isCompleteType(OpLoc, MPTy); 10313 return MPTy; 10314 } 10315 } 10316 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10317 llvm_unreachable("Unknown/unexpected decl type"); 10318 } 10319 10320 if (AddressOfError != AO_No_Error) { 10321 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10322 return QualType(); 10323 } 10324 10325 if (lval == Expr::LV_IncompleteVoidType) { 10326 // Taking the address of a void variable is technically illegal, but we 10327 // allow it in cases which are otherwise valid. 10328 // Example: "extern void x; void* y = &x;". 10329 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10330 } 10331 10332 // If the operand has type "type", the result has type "pointer to type". 10333 if (op->getType()->isObjCObjectType()) 10334 return Context.getObjCObjectPointerType(op->getType()); 10335 return Context.getPointerType(op->getType()); 10336 } 10337 10338 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10339 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10340 if (!DRE) 10341 return; 10342 const Decl *D = DRE->getDecl(); 10343 if (!D) 10344 return; 10345 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10346 if (!Param) 10347 return; 10348 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10349 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10350 return; 10351 if (FunctionScopeInfo *FD = S.getCurFunction()) 10352 if (!FD->ModifiedNonNullParams.count(Param)) 10353 FD->ModifiedNonNullParams.insert(Param); 10354 } 10355 10356 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10357 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10358 SourceLocation OpLoc) { 10359 if (Op->isTypeDependent()) 10360 return S.Context.DependentTy; 10361 10362 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10363 if (ConvResult.isInvalid()) 10364 return QualType(); 10365 Op = ConvResult.get(); 10366 QualType OpTy = Op->getType(); 10367 QualType Result; 10368 10369 if (isa<CXXReinterpretCastExpr>(Op)) { 10370 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10371 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10372 Op->getSourceRange()); 10373 } 10374 10375 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10376 Result = PT->getPointeeType(); 10377 else if (const ObjCObjectPointerType *OPT = 10378 OpTy->getAs<ObjCObjectPointerType>()) 10379 Result = OPT->getPointeeType(); 10380 else { 10381 ExprResult PR = S.CheckPlaceholderExpr(Op); 10382 if (PR.isInvalid()) return QualType(); 10383 if (PR.get() != Op) 10384 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10385 } 10386 10387 if (Result.isNull()) { 10388 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10389 << OpTy << Op->getSourceRange(); 10390 return QualType(); 10391 } 10392 10393 // Note that per both C89 and C99, indirection is always legal, even if Result 10394 // is an incomplete type or void. It would be possible to warn about 10395 // dereferencing a void pointer, but it's completely well-defined, and such a 10396 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10397 // for pointers to 'void' but is fine for any other pointer type: 10398 // 10399 // C++ [expr.unary.op]p1: 10400 // [...] the expression to which [the unary * operator] is applied shall 10401 // be a pointer to an object type, or a pointer to a function type 10402 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10403 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10404 << OpTy << Op->getSourceRange(); 10405 10406 // Dereferences are usually l-values... 10407 VK = VK_LValue; 10408 10409 // ...except that certain expressions are never l-values in C. 10410 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10411 VK = VK_RValue; 10412 10413 return Result; 10414 } 10415 10416 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10417 BinaryOperatorKind Opc; 10418 switch (Kind) { 10419 default: llvm_unreachable("Unknown binop!"); 10420 case tok::periodstar: Opc = BO_PtrMemD; break; 10421 case tok::arrowstar: Opc = BO_PtrMemI; break; 10422 case tok::star: Opc = BO_Mul; break; 10423 case tok::slash: Opc = BO_Div; break; 10424 case tok::percent: Opc = BO_Rem; break; 10425 case tok::plus: Opc = BO_Add; break; 10426 case tok::minus: Opc = BO_Sub; break; 10427 case tok::lessless: Opc = BO_Shl; break; 10428 case tok::greatergreater: Opc = BO_Shr; break; 10429 case tok::lessequal: Opc = BO_LE; break; 10430 case tok::less: Opc = BO_LT; break; 10431 case tok::greaterequal: Opc = BO_GE; break; 10432 case tok::greater: Opc = BO_GT; break; 10433 case tok::exclaimequal: Opc = BO_NE; break; 10434 case tok::equalequal: Opc = BO_EQ; break; 10435 case tok::amp: Opc = BO_And; break; 10436 case tok::caret: Opc = BO_Xor; break; 10437 case tok::pipe: Opc = BO_Or; break; 10438 case tok::ampamp: Opc = BO_LAnd; break; 10439 case tok::pipepipe: Opc = BO_LOr; break; 10440 case tok::equal: Opc = BO_Assign; break; 10441 case tok::starequal: Opc = BO_MulAssign; break; 10442 case tok::slashequal: Opc = BO_DivAssign; break; 10443 case tok::percentequal: Opc = BO_RemAssign; break; 10444 case tok::plusequal: Opc = BO_AddAssign; break; 10445 case tok::minusequal: Opc = BO_SubAssign; break; 10446 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10447 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10448 case tok::ampequal: Opc = BO_AndAssign; break; 10449 case tok::caretequal: Opc = BO_XorAssign; break; 10450 case tok::pipeequal: Opc = BO_OrAssign; break; 10451 case tok::comma: Opc = BO_Comma; break; 10452 } 10453 return Opc; 10454 } 10455 10456 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10457 tok::TokenKind Kind) { 10458 UnaryOperatorKind Opc; 10459 switch (Kind) { 10460 default: llvm_unreachable("Unknown unary op!"); 10461 case tok::plusplus: Opc = UO_PreInc; break; 10462 case tok::minusminus: Opc = UO_PreDec; break; 10463 case tok::amp: Opc = UO_AddrOf; break; 10464 case tok::star: Opc = UO_Deref; break; 10465 case tok::plus: Opc = UO_Plus; break; 10466 case tok::minus: Opc = UO_Minus; break; 10467 case tok::tilde: Opc = UO_Not; break; 10468 case tok::exclaim: Opc = UO_LNot; break; 10469 case tok::kw___real: Opc = UO_Real; break; 10470 case tok::kw___imag: Opc = UO_Imag; break; 10471 case tok::kw___extension__: Opc = UO_Extension; break; 10472 } 10473 return Opc; 10474 } 10475 10476 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10477 /// This warning is only emitted for builtin assignment operations. It is also 10478 /// suppressed in the event of macro expansions. 10479 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10480 SourceLocation OpLoc) { 10481 if (!S.ActiveTemplateInstantiations.empty()) 10482 return; 10483 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10484 return; 10485 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10486 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10487 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10488 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10489 if (!LHSDeclRef || !RHSDeclRef || 10490 LHSDeclRef->getLocation().isMacroID() || 10491 RHSDeclRef->getLocation().isMacroID()) 10492 return; 10493 const ValueDecl *LHSDecl = 10494 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10495 const ValueDecl *RHSDecl = 10496 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10497 if (LHSDecl != RHSDecl) 10498 return; 10499 if (LHSDecl->getType().isVolatileQualified()) 10500 return; 10501 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10502 if (RefTy->getPointeeType().isVolatileQualified()) 10503 return; 10504 10505 S.Diag(OpLoc, diag::warn_self_assignment) 10506 << LHSDeclRef->getType() 10507 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10508 } 10509 10510 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10511 /// is usually indicative of introspection within the Objective-C pointer. 10512 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10513 SourceLocation OpLoc) { 10514 if (!S.getLangOpts().ObjC1) 10515 return; 10516 10517 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10518 const Expr *LHS = L.get(); 10519 const Expr *RHS = R.get(); 10520 10521 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10522 ObjCPointerExpr = LHS; 10523 OtherExpr = RHS; 10524 } 10525 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10526 ObjCPointerExpr = RHS; 10527 OtherExpr = LHS; 10528 } 10529 10530 // This warning is deliberately made very specific to reduce false 10531 // positives with logic that uses '&' for hashing. This logic mainly 10532 // looks for code trying to introspect into tagged pointers, which 10533 // code should generally never do. 10534 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10535 unsigned Diag = diag::warn_objc_pointer_masking; 10536 // Determine if we are introspecting the result of performSelectorXXX. 10537 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10538 // Special case messages to -performSelector and friends, which 10539 // can return non-pointer values boxed in a pointer value. 10540 // Some clients may wish to silence warnings in this subcase. 10541 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10542 Selector S = ME->getSelector(); 10543 StringRef SelArg0 = S.getNameForSlot(0); 10544 if (SelArg0.startswith("performSelector")) 10545 Diag = diag::warn_objc_pointer_masking_performSelector; 10546 } 10547 10548 S.Diag(OpLoc, Diag) 10549 << ObjCPointerExpr->getSourceRange(); 10550 } 10551 } 10552 10553 static NamedDecl *getDeclFromExpr(Expr *E) { 10554 if (!E) 10555 return nullptr; 10556 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10557 return DRE->getDecl(); 10558 if (auto *ME = dyn_cast<MemberExpr>(E)) 10559 return ME->getMemberDecl(); 10560 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10561 return IRE->getDecl(); 10562 return nullptr; 10563 } 10564 10565 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10566 /// operator @p Opc at location @c TokLoc. This routine only supports 10567 /// built-in operations; ActOnBinOp handles overloaded operators. 10568 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10569 BinaryOperatorKind Opc, 10570 Expr *LHSExpr, Expr *RHSExpr) { 10571 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10572 // The syntax only allows initializer lists on the RHS of assignment, 10573 // so we don't need to worry about accepting invalid code for 10574 // non-assignment operators. 10575 // C++11 5.17p9: 10576 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10577 // of x = {} is x = T(). 10578 InitializationKind Kind = 10579 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10580 InitializedEntity Entity = 10581 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10582 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10583 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10584 if (Init.isInvalid()) 10585 return Init; 10586 RHSExpr = Init.get(); 10587 } 10588 10589 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10590 QualType ResultTy; // Result type of the binary operator. 10591 // The following two variables are used for compound assignment operators 10592 QualType CompLHSTy; // Type of LHS after promotions for computation 10593 QualType CompResultTy; // Type of computation result 10594 ExprValueKind VK = VK_RValue; 10595 ExprObjectKind OK = OK_Ordinary; 10596 10597 if (!getLangOpts().CPlusPlus) { 10598 // C cannot handle TypoExpr nodes on either side of a binop because it 10599 // doesn't handle dependent types properly, so make sure any TypoExprs have 10600 // been dealt with before checking the operands. 10601 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10602 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10603 if (Opc != BO_Assign) 10604 return ExprResult(E); 10605 // Avoid correcting the RHS to the same Expr as the LHS. 10606 Decl *D = getDeclFromExpr(E); 10607 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10608 }); 10609 if (!LHS.isUsable() || !RHS.isUsable()) 10610 return ExprError(); 10611 } 10612 10613 if (getLangOpts().OpenCL) { 10614 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10615 // the ATOMIC_VAR_INIT macro. 10616 if (LHSExpr->getType()->isAtomicType() || 10617 RHSExpr->getType()->isAtomicType()) { 10618 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10619 if (BO_Assign == Opc) 10620 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10621 else 10622 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10623 return ExprError(); 10624 } 10625 } 10626 10627 switch (Opc) { 10628 case BO_Assign: 10629 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10630 if (getLangOpts().CPlusPlus && 10631 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10632 VK = LHS.get()->getValueKind(); 10633 OK = LHS.get()->getObjectKind(); 10634 } 10635 if (!ResultTy.isNull()) { 10636 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10637 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10638 } 10639 RecordModifiableNonNullParam(*this, LHS.get()); 10640 break; 10641 case BO_PtrMemD: 10642 case BO_PtrMemI: 10643 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10644 Opc == BO_PtrMemI); 10645 break; 10646 case BO_Mul: 10647 case BO_Div: 10648 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10649 Opc == BO_Div); 10650 break; 10651 case BO_Rem: 10652 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10653 break; 10654 case BO_Add: 10655 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10656 break; 10657 case BO_Sub: 10658 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10659 break; 10660 case BO_Shl: 10661 case BO_Shr: 10662 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10663 break; 10664 case BO_LE: 10665 case BO_LT: 10666 case BO_GE: 10667 case BO_GT: 10668 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10669 break; 10670 case BO_EQ: 10671 case BO_NE: 10672 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10673 break; 10674 case BO_And: 10675 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10676 case BO_Xor: 10677 case BO_Or: 10678 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10679 break; 10680 case BO_LAnd: 10681 case BO_LOr: 10682 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10683 break; 10684 case BO_MulAssign: 10685 case BO_DivAssign: 10686 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10687 Opc == BO_DivAssign); 10688 CompLHSTy = CompResultTy; 10689 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10690 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10691 break; 10692 case BO_RemAssign: 10693 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10694 CompLHSTy = CompResultTy; 10695 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10696 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10697 break; 10698 case BO_AddAssign: 10699 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10700 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10701 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10702 break; 10703 case BO_SubAssign: 10704 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10705 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10706 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10707 break; 10708 case BO_ShlAssign: 10709 case BO_ShrAssign: 10710 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10711 CompLHSTy = CompResultTy; 10712 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10713 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10714 break; 10715 case BO_AndAssign: 10716 case BO_OrAssign: // fallthrough 10717 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10718 case BO_XorAssign: 10719 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10720 CompLHSTy = CompResultTy; 10721 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10722 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10723 break; 10724 case BO_Comma: 10725 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10726 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10727 VK = RHS.get()->getValueKind(); 10728 OK = RHS.get()->getObjectKind(); 10729 } 10730 break; 10731 } 10732 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10733 return ExprError(); 10734 10735 // Check for array bounds violations for both sides of the BinaryOperator 10736 CheckArrayAccess(LHS.get()); 10737 CheckArrayAccess(RHS.get()); 10738 10739 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10740 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10741 &Context.Idents.get("object_setClass"), 10742 SourceLocation(), LookupOrdinaryName); 10743 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10744 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 10745 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10746 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10747 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10748 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10749 } 10750 else 10751 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10752 } 10753 else if (const ObjCIvarRefExpr *OIRE = 10754 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10755 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10756 10757 if (CompResultTy.isNull()) 10758 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10759 OK, OpLoc, FPFeatures.fp_contract); 10760 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10761 OK_ObjCProperty) { 10762 VK = VK_LValue; 10763 OK = LHS.get()->getObjectKind(); 10764 } 10765 return new (Context) CompoundAssignOperator( 10766 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10767 OpLoc, FPFeatures.fp_contract); 10768 } 10769 10770 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10771 /// operators are mixed in a way that suggests that the programmer forgot that 10772 /// comparison operators have higher precedence. The most typical example of 10773 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10774 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10775 SourceLocation OpLoc, Expr *LHSExpr, 10776 Expr *RHSExpr) { 10777 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10778 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10779 10780 // Check that one of the sides is a comparison operator and the other isn't. 10781 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10782 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10783 if (isLeftComp == isRightComp) 10784 return; 10785 10786 // Bitwise operations are sometimes used as eager logical ops. 10787 // Don't diagnose this. 10788 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10789 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10790 if (isLeftBitwise || isRightBitwise) 10791 return; 10792 10793 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10794 OpLoc) 10795 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10796 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10797 SourceRange ParensRange = isLeftComp ? 10798 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10799 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10800 10801 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10802 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10803 SuggestParentheses(Self, OpLoc, 10804 Self.PDiag(diag::note_precedence_silence) << OpStr, 10805 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10806 SuggestParentheses(Self, OpLoc, 10807 Self.PDiag(diag::note_precedence_bitwise_first) 10808 << BinaryOperator::getOpcodeStr(Opc), 10809 ParensRange); 10810 } 10811 10812 /// \brief It accepts a '&&' expr that is inside a '||' one. 10813 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10814 /// in parentheses. 10815 static void 10816 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10817 BinaryOperator *Bop) { 10818 assert(Bop->getOpcode() == BO_LAnd); 10819 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10820 << Bop->getSourceRange() << OpLoc; 10821 SuggestParentheses(Self, Bop->getOperatorLoc(), 10822 Self.PDiag(diag::note_precedence_silence) 10823 << Bop->getOpcodeStr(), 10824 Bop->getSourceRange()); 10825 } 10826 10827 /// \brief Returns true if the given expression can be evaluated as a constant 10828 /// 'true'. 10829 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10830 bool Res; 10831 return !E->isValueDependent() && 10832 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10833 } 10834 10835 /// \brief Returns true if the given expression can be evaluated as a constant 10836 /// 'false'. 10837 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10838 bool Res; 10839 return !E->isValueDependent() && 10840 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10841 } 10842 10843 /// \brief Look for '&&' in the left hand of a '||' expr. 10844 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10845 Expr *LHSExpr, Expr *RHSExpr) { 10846 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10847 if (Bop->getOpcode() == BO_LAnd) { 10848 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10849 if (EvaluatesAsFalse(S, RHSExpr)) 10850 return; 10851 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10852 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10853 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10854 } else if (Bop->getOpcode() == BO_LOr) { 10855 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10856 // If it's "a || b && 1 || c" we didn't warn earlier for 10857 // "a || b && 1", but warn now. 10858 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10859 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10860 } 10861 } 10862 } 10863 } 10864 10865 /// \brief Look for '&&' in the right hand of a '||' expr. 10866 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10867 Expr *LHSExpr, Expr *RHSExpr) { 10868 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10869 if (Bop->getOpcode() == BO_LAnd) { 10870 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10871 if (EvaluatesAsFalse(S, LHSExpr)) 10872 return; 10873 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10874 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10875 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10876 } 10877 } 10878 } 10879 10880 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 10881 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 10882 /// the '&' expression in parentheses. 10883 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 10884 SourceLocation OpLoc, Expr *SubExpr) { 10885 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10886 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 10887 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 10888 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 10889 << Bop->getSourceRange() << OpLoc; 10890 SuggestParentheses(S, Bop->getOperatorLoc(), 10891 S.PDiag(diag::note_precedence_silence) 10892 << Bop->getOpcodeStr(), 10893 Bop->getSourceRange()); 10894 } 10895 } 10896 } 10897 10898 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10899 Expr *SubExpr, StringRef Shift) { 10900 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10901 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10902 StringRef Op = Bop->getOpcodeStr(); 10903 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10904 << Bop->getSourceRange() << OpLoc << Shift << Op; 10905 SuggestParentheses(S, Bop->getOperatorLoc(), 10906 S.PDiag(diag::note_precedence_silence) << Op, 10907 Bop->getSourceRange()); 10908 } 10909 } 10910 } 10911 10912 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10913 Expr *LHSExpr, Expr *RHSExpr) { 10914 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10915 if (!OCE) 10916 return; 10917 10918 FunctionDecl *FD = OCE->getDirectCallee(); 10919 if (!FD || !FD->isOverloadedOperator()) 10920 return; 10921 10922 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10923 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10924 return; 10925 10926 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10927 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10928 << (Kind == OO_LessLess); 10929 SuggestParentheses(S, OCE->getOperatorLoc(), 10930 S.PDiag(diag::note_precedence_silence) 10931 << (Kind == OO_LessLess ? "<<" : ">>"), 10932 OCE->getSourceRange()); 10933 SuggestParentheses(S, OpLoc, 10934 S.PDiag(diag::note_evaluate_comparison_first), 10935 SourceRange(OCE->getArg(1)->getLocStart(), 10936 RHSExpr->getLocEnd())); 10937 } 10938 10939 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10940 /// precedence. 10941 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10942 SourceLocation OpLoc, Expr *LHSExpr, 10943 Expr *RHSExpr){ 10944 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10945 if (BinaryOperator::isBitwiseOp(Opc)) 10946 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10947 10948 // Diagnose "arg1 & arg2 | arg3" 10949 if ((Opc == BO_Or || Opc == BO_Xor) && 10950 !OpLoc.isMacroID()/* Don't warn in macros. */) { 10951 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 10952 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 10953 } 10954 10955 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10956 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10957 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10958 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10959 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10960 } 10961 10962 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 10963 || Opc == BO_Shr) { 10964 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 10965 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 10966 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 10967 } 10968 10969 // Warn on overloaded shift operators and comparisons, such as: 10970 // cout << 5 == 4; 10971 if (BinaryOperator::isComparisonOp(Opc)) 10972 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 10973 } 10974 10975 // Binary Operators. 'Tok' is the token for the operator. 10976 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 10977 tok::TokenKind Kind, 10978 Expr *LHSExpr, Expr *RHSExpr) { 10979 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 10980 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 10981 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 10982 10983 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 10984 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 10985 10986 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 10987 } 10988 10989 /// Build an overloaded binary operator expression in the given scope. 10990 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 10991 BinaryOperatorKind Opc, 10992 Expr *LHS, Expr *RHS) { 10993 // Find all of the overloaded operators visible from this 10994 // point. We perform both an operator-name lookup from the local 10995 // scope and an argument-dependent lookup based on the types of 10996 // the arguments. 10997 UnresolvedSet<16> Functions; 10998 OverloadedOperatorKind OverOp 10999 = BinaryOperator::getOverloadedOperator(Opc); 11000 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11001 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11002 RHS->getType(), Functions); 11003 11004 // Build the (potentially-overloaded, potentially-dependent) 11005 // binary operation. 11006 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11007 } 11008 11009 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11010 BinaryOperatorKind Opc, 11011 Expr *LHSExpr, Expr *RHSExpr) { 11012 // We want to end up calling one of checkPseudoObjectAssignment 11013 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11014 // both expressions are overloadable or either is type-dependent), 11015 // or CreateBuiltinBinOp (in any other case). We also want to get 11016 // any placeholder types out of the way. 11017 11018 // Handle pseudo-objects in the LHS. 11019 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11020 // Assignments with a pseudo-object l-value need special analysis. 11021 if (pty->getKind() == BuiltinType::PseudoObject && 11022 BinaryOperator::isAssignmentOp(Opc)) 11023 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11024 11025 // Don't resolve overloads if the other type is overloadable. 11026 if (pty->getKind() == BuiltinType::Overload) { 11027 // We can't actually test that if we still have a placeholder, 11028 // though. Fortunately, none of the exceptions we see in that 11029 // code below are valid when the LHS is an overload set. Note 11030 // that an overload set can be dependently-typed, but it never 11031 // instantiates to having an overloadable type. 11032 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11033 if (resolvedRHS.isInvalid()) return ExprError(); 11034 RHSExpr = resolvedRHS.get(); 11035 11036 if (RHSExpr->isTypeDependent() || 11037 RHSExpr->getType()->isOverloadableType()) 11038 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11039 } 11040 11041 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11042 if (LHS.isInvalid()) return ExprError(); 11043 LHSExpr = LHS.get(); 11044 } 11045 11046 // Handle pseudo-objects in the RHS. 11047 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11048 // An overload in the RHS can potentially be resolved by the type 11049 // being assigned to. 11050 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11051 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11052 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11053 11054 if (LHSExpr->getType()->isOverloadableType()) 11055 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11056 11057 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11058 } 11059 11060 // Don't resolve overloads if the other type is overloadable. 11061 if (pty->getKind() == BuiltinType::Overload && 11062 LHSExpr->getType()->isOverloadableType()) 11063 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11064 11065 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11066 if (!resolvedRHS.isUsable()) return ExprError(); 11067 RHSExpr = resolvedRHS.get(); 11068 } 11069 11070 if (getLangOpts().CPlusPlus) { 11071 // If either expression is type-dependent, always build an 11072 // overloaded op. 11073 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11074 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11075 11076 // Otherwise, build an overloaded op if either expression has an 11077 // overloadable type. 11078 if (LHSExpr->getType()->isOverloadableType() || 11079 RHSExpr->getType()->isOverloadableType()) 11080 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11081 } 11082 11083 // Build a built-in binary operation. 11084 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11085 } 11086 11087 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11088 UnaryOperatorKind Opc, 11089 Expr *InputExpr) { 11090 ExprResult Input = InputExpr; 11091 ExprValueKind VK = VK_RValue; 11092 ExprObjectKind OK = OK_Ordinary; 11093 QualType resultType; 11094 if (getLangOpts().OpenCL) { 11095 // The only legal unary operation for atomics is '&'. 11096 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 11097 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11098 << InputExpr->getType() 11099 << Input.get()->getSourceRange()); 11100 } 11101 } 11102 switch (Opc) { 11103 case UO_PreInc: 11104 case UO_PreDec: 11105 case UO_PostInc: 11106 case UO_PostDec: 11107 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11108 OpLoc, 11109 Opc == UO_PreInc || 11110 Opc == UO_PostInc, 11111 Opc == UO_PreInc || 11112 Opc == UO_PreDec); 11113 break; 11114 case UO_AddrOf: 11115 resultType = CheckAddressOfOperand(Input, OpLoc); 11116 RecordModifiableNonNullParam(*this, InputExpr); 11117 break; 11118 case UO_Deref: { 11119 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11120 if (Input.isInvalid()) return ExprError(); 11121 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11122 break; 11123 } 11124 case UO_Plus: 11125 case UO_Minus: 11126 Input = UsualUnaryConversions(Input.get()); 11127 if (Input.isInvalid()) return ExprError(); 11128 resultType = Input.get()->getType(); 11129 if (resultType->isDependentType()) 11130 break; 11131 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11132 break; 11133 else if (resultType->isVectorType() && 11134 // The z vector extensions don't allow + or - with bool vectors. 11135 (!Context.getLangOpts().ZVector || 11136 resultType->getAs<VectorType>()->getVectorKind() != 11137 VectorType::AltiVecBool)) 11138 break; 11139 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11140 Opc == UO_Plus && 11141 resultType->isPointerType()) 11142 break; 11143 11144 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11145 << resultType << Input.get()->getSourceRange()); 11146 11147 case UO_Not: // bitwise complement 11148 Input = UsualUnaryConversions(Input.get()); 11149 if (Input.isInvalid()) 11150 return ExprError(); 11151 resultType = Input.get()->getType(); 11152 if (resultType->isDependentType()) 11153 break; 11154 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11155 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11156 // C99 does not support '~' for complex conjugation. 11157 Diag(OpLoc, diag::ext_integer_complement_complex) 11158 << resultType << Input.get()->getSourceRange(); 11159 else if (resultType->hasIntegerRepresentation()) 11160 break; 11161 else if (resultType->isExtVectorType()) { 11162 if (Context.getLangOpts().OpenCL) { 11163 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11164 // on vector float types. 11165 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11166 if (!T->isIntegerType()) 11167 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11168 << resultType << Input.get()->getSourceRange()); 11169 } 11170 break; 11171 } else { 11172 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11173 << resultType << Input.get()->getSourceRange()); 11174 } 11175 break; 11176 11177 case UO_LNot: // logical negation 11178 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11179 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11180 if (Input.isInvalid()) return ExprError(); 11181 resultType = Input.get()->getType(); 11182 11183 // Though we still have to promote half FP to float... 11184 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11185 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11186 resultType = Context.FloatTy; 11187 } 11188 11189 if (resultType->isDependentType()) 11190 break; 11191 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11192 // C99 6.5.3.3p1: ok, fallthrough; 11193 if (Context.getLangOpts().CPlusPlus) { 11194 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11195 // operand contextually converted to bool. 11196 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11197 ScalarTypeToBooleanCastKind(resultType)); 11198 } else if (Context.getLangOpts().OpenCL && 11199 Context.getLangOpts().OpenCLVersion < 120) { 11200 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11201 // operate on scalar float types. 11202 if (!resultType->isIntegerType()) 11203 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11204 << resultType << Input.get()->getSourceRange()); 11205 } 11206 } else if (resultType->isExtVectorType()) { 11207 if (Context.getLangOpts().OpenCL && 11208 Context.getLangOpts().OpenCLVersion < 120) { 11209 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11210 // operate on vector float types. 11211 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11212 if (!T->isIntegerType()) 11213 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11214 << resultType << Input.get()->getSourceRange()); 11215 } 11216 // Vector logical not returns the signed variant of the operand type. 11217 resultType = GetSignedVectorType(resultType); 11218 break; 11219 } else { 11220 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11221 << resultType << Input.get()->getSourceRange()); 11222 } 11223 11224 // LNot always has type int. C99 6.5.3.3p5. 11225 // In C++, it's bool. C++ 5.3.1p8 11226 resultType = Context.getLogicalOperationType(); 11227 break; 11228 case UO_Real: 11229 case UO_Imag: 11230 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11231 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11232 // complex l-values to ordinary l-values and all other values to r-values. 11233 if (Input.isInvalid()) return ExprError(); 11234 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11235 if (Input.get()->getValueKind() != VK_RValue && 11236 Input.get()->getObjectKind() == OK_Ordinary) 11237 VK = Input.get()->getValueKind(); 11238 } else if (!getLangOpts().CPlusPlus) { 11239 // In C, a volatile scalar is read by __imag. In C++, it is not. 11240 Input = DefaultLvalueConversion(Input.get()); 11241 } 11242 break; 11243 case UO_Extension: 11244 case UO_Coawait: 11245 resultType = Input.get()->getType(); 11246 VK = Input.get()->getValueKind(); 11247 OK = Input.get()->getObjectKind(); 11248 break; 11249 } 11250 if (resultType.isNull() || Input.isInvalid()) 11251 return ExprError(); 11252 11253 // Check for array bounds violations in the operand of the UnaryOperator, 11254 // except for the '*' and '&' operators that have to be handled specially 11255 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11256 // that are explicitly defined as valid by the standard). 11257 if (Opc != UO_AddrOf && Opc != UO_Deref) 11258 CheckArrayAccess(Input.get()); 11259 11260 return new (Context) 11261 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11262 } 11263 11264 /// \brief Determine whether the given expression is a qualified member 11265 /// access expression, of a form that could be turned into a pointer to member 11266 /// with the address-of operator. 11267 static bool isQualifiedMemberAccess(Expr *E) { 11268 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11269 if (!DRE->getQualifier()) 11270 return false; 11271 11272 ValueDecl *VD = DRE->getDecl(); 11273 if (!VD->isCXXClassMember()) 11274 return false; 11275 11276 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11277 return true; 11278 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11279 return Method->isInstance(); 11280 11281 return false; 11282 } 11283 11284 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11285 if (!ULE->getQualifier()) 11286 return false; 11287 11288 for (NamedDecl *D : ULE->decls()) { 11289 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11290 if (Method->isInstance()) 11291 return true; 11292 } else { 11293 // Overload set does not contain methods. 11294 break; 11295 } 11296 } 11297 11298 return false; 11299 } 11300 11301 return false; 11302 } 11303 11304 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11305 UnaryOperatorKind Opc, Expr *Input) { 11306 // First things first: handle placeholders so that the 11307 // overloaded-operator check considers the right type. 11308 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11309 // Increment and decrement of pseudo-object references. 11310 if (pty->getKind() == BuiltinType::PseudoObject && 11311 UnaryOperator::isIncrementDecrementOp(Opc)) 11312 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11313 11314 // extension is always a builtin operator. 11315 if (Opc == UO_Extension) 11316 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11317 11318 // & gets special logic for several kinds of placeholder. 11319 // The builtin code knows what to do. 11320 if (Opc == UO_AddrOf && 11321 (pty->getKind() == BuiltinType::Overload || 11322 pty->getKind() == BuiltinType::UnknownAny || 11323 pty->getKind() == BuiltinType::BoundMember)) 11324 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11325 11326 // Anything else needs to be handled now. 11327 ExprResult Result = CheckPlaceholderExpr(Input); 11328 if (Result.isInvalid()) return ExprError(); 11329 Input = Result.get(); 11330 } 11331 11332 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11333 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11334 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11335 // Find all of the overloaded operators visible from this 11336 // point. We perform both an operator-name lookup from the local 11337 // scope and an argument-dependent lookup based on the types of 11338 // the arguments. 11339 UnresolvedSet<16> Functions; 11340 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11341 if (S && OverOp != OO_None) 11342 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11343 Functions); 11344 11345 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11346 } 11347 11348 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11349 } 11350 11351 // Unary Operators. 'Tok' is the token for the operator. 11352 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11353 tok::TokenKind Op, Expr *Input) { 11354 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11355 } 11356 11357 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11358 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11359 LabelDecl *TheDecl) { 11360 TheDecl->markUsed(Context); 11361 // Create the AST node. The address of a label always has type 'void*'. 11362 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11363 Context.getPointerType(Context.VoidTy)); 11364 } 11365 11366 /// Given the last statement in a statement-expression, check whether 11367 /// the result is a producing expression (like a call to an 11368 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11369 /// release out of the full-expression. Otherwise, return null. 11370 /// Cannot fail. 11371 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11372 // Should always be wrapped with one of these. 11373 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11374 if (!cleanups) return nullptr; 11375 11376 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11377 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11378 return nullptr; 11379 11380 // Splice out the cast. This shouldn't modify any interesting 11381 // features of the statement. 11382 Expr *producer = cast->getSubExpr(); 11383 assert(producer->getType() == cast->getType()); 11384 assert(producer->getValueKind() == cast->getValueKind()); 11385 cleanups->setSubExpr(producer); 11386 return cleanups; 11387 } 11388 11389 void Sema::ActOnStartStmtExpr() { 11390 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11391 } 11392 11393 void Sema::ActOnStmtExprError() { 11394 // Note that function is also called by TreeTransform when leaving a 11395 // StmtExpr scope without rebuilding anything. 11396 11397 DiscardCleanupsInEvaluationContext(); 11398 PopExpressionEvaluationContext(); 11399 } 11400 11401 ExprResult 11402 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11403 SourceLocation RPLoc) { // "({..})" 11404 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11405 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11406 11407 if (hasAnyUnrecoverableErrorsInThisFunction()) 11408 DiscardCleanupsInEvaluationContext(); 11409 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11410 PopExpressionEvaluationContext(); 11411 11412 // FIXME: there are a variety of strange constraints to enforce here, for 11413 // example, it is not possible to goto into a stmt expression apparently. 11414 // More semantic analysis is needed. 11415 11416 // If there are sub-stmts in the compound stmt, take the type of the last one 11417 // as the type of the stmtexpr. 11418 QualType Ty = Context.VoidTy; 11419 bool StmtExprMayBindToTemp = false; 11420 if (!Compound->body_empty()) { 11421 Stmt *LastStmt = Compound->body_back(); 11422 LabelStmt *LastLabelStmt = nullptr; 11423 // If LastStmt is a label, skip down through into the body. 11424 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11425 LastLabelStmt = Label; 11426 LastStmt = Label->getSubStmt(); 11427 } 11428 11429 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11430 // Do function/array conversion on the last expression, but not 11431 // lvalue-to-rvalue. However, initialize an unqualified type. 11432 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11433 if (LastExpr.isInvalid()) 11434 return ExprError(); 11435 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11436 11437 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11438 // In ARC, if the final expression ends in a consume, splice 11439 // the consume out and bind it later. In the alternate case 11440 // (when dealing with a retainable type), the result 11441 // initialization will create a produce. In both cases the 11442 // result will be +1, and we'll need to balance that out with 11443 // a bind. 11444 if (Expr *rebuiltLastStmt 11445 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11446 LastExpr = rebuiltLastStmt; 11447 } else { 11448 LastExpr = PerformCopyInitialization( 11449 InitializedEntity::InitializeResult(LPLoc, 11450 Ty, 11451 false), 11452 SourceLocation(), 11453 LastExpr); 11454 } 11455 11456 if (LastExpr.isInvalid()) 11457 return ExprError(); 11458 if (LastExpr.get() != nullptr) { 11459 if (!LastLabelStmt) 11460 Compound->setLastStmt(LastExpr.get()); 11461 else 11462 LastLabelStmt->setSubStmt(LastExpr.get()); 11463 StmtExprMayBindToTemp = true; 11464 } 11465 } 11466 } 11467 } 11468 11469 // FIXME: Check that expression type is complete/non-abstract; statement 11470 // expressions are not lvalues. 11471 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11472 if (StmtExprMayBindToTemp) 11473 return MaybeBindToTemporary(ResStmtExpr); 11474 return ResStmtExpr; 11475 } 11476 11477 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11478 TypeSourceInfo *TInfo, 11479 ArrayRef<OffsetOfComponent> Components, 11480 SourceLocation RParenLoc) { 11481 QualType ArgTy = TInfo->getType(); 11482 bool Dependent = ArgTy->isDependentType(); 11483 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11484 11485 // We must have at least one component that refers to the type, and the first 11486 // one is known to be a field designator. Verify that the ArgTy represents 11487 // a struct/union/class. 11488 if (!Dependent && !ArgTy->isRecordType()) 11489 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11490 << ArgTy << TypeRange); 11491 11492 // Type must be complete per C99 7.17p3 because a declaring a variable 11493 // with an incomplete type would be ill-formed. 11494 if (!Dependent 11495 && RequireCompleteType(BuiltinLoc, ArgTy, 11496 diag::err_offsetof_incomplete_type, TypeRange)) 11497 return ExprError(); 11498 11499 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11500 // GCC extension, diagnose them. 11501 // FIXME: This diagnostic isn't actually visible because the location is in 11502 // a system header! 11503 if (Components.size() != 1) 11504 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11505 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11506 11507 bool DidWarnAboutNonPOD = false; 11508 QualType CurrentType = ArgTy; 11509 SmallVector<OffsetOfNode, 4> Comps; 11510 SmallVector<Expr*, 4> Exprs; 11511 for (const OffsetOfComponent &OC : Components) { 11512 if (OC.isBrackets) { 11513 // Offset of an array sub-field. TODO: Should we allow vector elements? 11514 if (!CurrentType->isDependentType()) { 11515 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11516 if(!AT) 11517 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11518 << CurrentType); 11519 CurrentType = AT->getElementType(); 11520 } else 11521 CurrentType = Context.DependentTy; 11522 11523 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11524 if (IdxRval.isInvalid()) 11525 return ExprError(); 11526 Expr *Idx = IdxRval.get(); 11527 11528 // The expression must be an integral expression. 11529 // FIXME: An integral constant expression? 11530 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11531 !Idx->getType()->isIntegerType()) 11532 return ExprError(Diag(Idx->getLocStart(), 11533 diag::err_typecheck_subscript_not_integer) 11534 << Idx->getSourceRange()); 11535 11536 // Record this array index. 11537 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11538 Exprs.push_back(Idx); 11539 continue; 11540 } 11541 11542 // Offset of a field. 11543 if (CurrentType->isDependentType()) { 11544 // We have the offset of a field, but we can't look into the dependent 11545 // type. Just record the identifier of the field. 11546 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11547 CurrentType = Context.DependentTy; 11548 continue; 11549 } 11550 11551 // We need to have a complete type to look into. 11552 if (RequireCompleteType(OC.LocStart, CurrentType, 11553 diag::err_offsetof_incomplete_type)) 11554 return ExprError(); 11555 11556 // Look for the designated field. 11557 const RecordType *RC = CurrentType->getAs<RecordType>(); 11558 if (!RC) 11559 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11560 << CurrentType); 11561 RecordDecl *RD = RC->getDecl(); 11562 11563 // C++ [lib.support.types]p5: 11564 // The macro offsetof accepts a restricted set of type arguments in this 11565 // International Standard. type shall be a POD structure or a POD union 11566 // (clause 9). 11567 // C++11 [support.types]p4: 11568 // If type is not a standard-layout class (Clause 9), the results are 11569 // undefined. 11570 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11571 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11572 unsigned DiagID = 11573 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11574 : diag::ext_offsetof_non_pod_type; 11575 11576 if (!IsSafe && !DidWarnAboutNonPOD && 11577 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11578 PDiag(DiagID) 11579 << SourceRange(Components[0].LocStart, OC.LocEnd) 11580 << CurrentType)) 11581 DidWarnAboutNonPOD = true; 11582 } 11583 11584 // Look for the field. 11585 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11586 LookupQualifiedName(R, RD); 11587 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11588 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11589 if (!MemberDecl) { 11590 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11591 MemberDecl = IndirectMemberDecl->getAnonField(); 11592 } 11593 11594 if (!MemberDecl) 11595 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11596 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11597 OC.LocEnd)); 11598 11599 // C99 7.17p3: 11600 // (If the specified member is a bit-field, the behavior is undefined.) 11601 // 11602 // We diagnose this as an error. 11603 if (MemberDecl->isBitField()) { 11604 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11605 << MemberDecl->getDeclName() 11606 << SourceRange(BuiltinLoc, RParenLoc); 11607 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11608 return ExprError(); 11609 } 11610 11611 RecordDecl *Parent = MemberDecl->getParent(); 11612 if (IndirectMemberDecl) 11613 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11614 11615 // If the member was found in a base class, introduce OffsetOfNodes for 11616 // the base class indirections. 11617 CXXBasePaths Paths; 11618 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11619 Paths)) { 11620 if (Paths.getDetectedVirtual()) { 11621 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11622 << MemberDecl->getDeclName() 11623 << SourceRange(BuiltinLoc, RParenLoc); 11624 return ExprError(); 11625 } 11626 11627 CXXBasePath &Path = Paths.front(); 11628 for (const CXXBasePathElement &B : Path) 11629 Comps.push_back(OffsetOfNode(B.Base)); 11630 } 11631 11632 if (IndirectMemberDecl) { 11633 for (auto *FI : IndirectMemberDecl->chain()) { 11634 assert(isa<FieldDecl>(FI)); 11635 Comps.push_back(OffsetOfNode(OC.LocStart, 11636 cast<FieldDecl>(FI), OC.LocEnd)); 11637 } 11638 } else 11639 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11640 11641 CurrentType = MemberDecl->getType().getNonReferenceType(); 11642 } 11643 11644 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11645 Comps, Exprs, RParenLoc); 11646 } 11647 11648 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11649 SourceLocation BuiltinLoc, 11650 SourceLocation TypeLoc, 11651 ParsedType ParsedArgTy, 11652 ArrayRef<OffsetOfComponent> Components, 11653 SourceLocation RParenLoc) { 11654 11655 TypeSourceInfo *ArgTInfo; 11656 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11657 if (ArgTy.isNull()) 11658 return ExprError(); 11659 11660 if (!ArgTInfo) 11661 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11662 11663 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11664 } 11665 11666 11667 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11668 Expr *CondExpr, 11669 Expr *LHSExpr, Expr *RHSExpr, 11670 SourceLocation RPLoc) { 11671 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11672 11673 ExprValueKind VK = VK_RValue; 11674 ExprObjectKind OK = OK_Ordinary; 11675 QualType resType; 11676 bool ValueDependent = false; 11677 bool CondIsTrue = false; 11678 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11679 resType = Context.DependentTy; 11680 ValueDependent = true; 11681 } else { 11682 // The conditional expression is required to be a constant expression. 11683 llvm::APSInt condEval(32); 11684 ExprResult CondICE 11685 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11686 diag::err_typecheck_choose_expr_requires_constant, false); 11687 if (CondICE.isInvalid()) 11688 return ExprError(); 11689 CondExpr = CondICE.get(); 11690 CondIsTrue = condEval.getZExtValue(); 11691 11692 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11693 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11694 11695 resType = ActiveExpr->getType(); 11696 ValueDependent = ActiveExpr->isValueDependent(); 11697 VK = ActiveExpr->getValueKind(); 11698 OK = ActiveExpr->getObjectKind(); 11699 } 11700 11701 return new (Context) 11702 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11703 CondIsTrue, resType->isDependentType(), ValueDependent); 11704 } 11705 11706 //===----------------------------------------------------------------------===// 11707 // Clang Extensions. 11708 //===----------------------------------------------------------------------===// 11709 11710 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11711 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11712 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11713 11714 if (LangOpts.CPlusPlus) { 11715 Decl *ManglingContextDecl; 11716 if (MangleNumberingContext *MCtx = 11717 getCurrentMangleNumberContext(Block->getDeclContext(), 11718 ManglingContextDecl)) { 11719 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11720 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11721 } 11722 } 11723 11724 PushBlockScope(CurScope, Block); 11725 CurContext->addDecl(Block); 11726 if (CurScope) 11727 PushDeclContext(CurScope, Block); 11728 else 11729 CurContext = Block; 11730 11731 getCurBlock()->HasImplicitReturnType = true; 11732 11733 // Enter a new evaluation context to insulate the block from any 11734 // cleanups from the enclosing full-expression. 11735 PushExpressionEvaluationContext(PotentiallyEvaluated); 11736 } 11737 11738 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11739 Scope *CurScope) { 11740 assert(ParamInfo.getIdentifier() == nullptr && 11741 "block-id should have no identifier!"); 11742 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11743 BlockScopeInfo *CurBlock = getCurBlock(); 11744 11745 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11746 QualType T = Sig->getType(); 11747 11748 // FIXME: We should allow unexpanded parameter packs here, but that would, 11749 // in turn, make the block expression contain unexpanded parameter packs. 11750 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11751 // Drop the parameters. 11752 FunctionProtoType::ExtProtoInfo EPI; 11753 EPI.HasTrailingReturn = false; 11754 EPI.TypeQuals |= DeclSpec::TQ_const; 11755 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11756 Sig = Context.getTrivialTypeSourceInfo(T); 11757 } 11758 11759 // GetTypeForDeclarator always produces a function type for a block 11760 // literal signature. Furthermore, it is always a FunctionProtoType 11761 // unless the function was written with a typedef. 11762 assert(T->isFunctionType() && 11763 "GetTypeForDeclarator made a non-function block signature"); 11764 11765 // Look for an explicit signature in that function type. 11766 FunctionProtoTypeLoc ExplicitSignature; 11767 11768 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11769 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11770 11771 // Check whether that explicit signature was synthesized by 11772 // GetTypeForDeclarator. If so, don't save that as part of the 11773 // written signature. 11774 if (ExplicitSignature.getLocalRangeBegin() == 11775 ExplicitSignature.getLocalRangeEnd()) { 11776 // This would be much cheaper if we stored TypeLocs instead of 11777 // TypeSourceInfos. 11778 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11779 unsigned Size = Result.getFullDataSize(); 11780 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11781 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11782 11783 ExplicitSignature = FunctionProtoTypeLoc(); 11784 } 11785 } 11786 11787 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11788 CurBlock->FunctionType = T; 11789 11790 const FunctionType *Fn = T->getAs<FunctionType>(); 11791 QualType RetTy = Fn->getReturnType(); 11792 bool isVariadic = 11793 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11794 11795 CurBlock->TheDecl->setIsVariadic(isVariadic); 11796 11797 // Context.DependentTy is used as a placeholder for a missing block 11798 // return type. TODO: what should we do with declarators like: 11799 // ^ * { ... } 11800 // If the answer is "apply template argument deduction".... 11801 if (RetTy != Context.DependentTy) { 11802 CurBlock->ReturnType = RetTy; 11803 CurBlock->TheDecl->setBlockMissingReturnType(false); 11804 CurBlock->HasImplicitReturnType = false; 11805 } 11806 11807 // Push block parameters from the declarator if we had them. 11808 SmallVector<ParmVarDecl*, 8> Params; 11809 if (ExplicitSignature) { 11810 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11811 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11812 if (Param->getIdentifier() == nullptr && 11813 !Param->isImplicit() && 11814 !Param->isInvalidDecl() && 11815 !getLangOpts().CPlusPlus) 11816 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11817 Params.push_back(Param); 11818 } 11819 11820 // Fake up parameter variables if we have a typedef, like 11821 // ^ fntype { ... } 11822 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11823 for (const auto &I : Fn->param_types()) { 11824 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11825 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11826 Params.push_back(Param); 11827 } 11828 } 11829 11830 // Set the parameters on the block decl. 11831 if (!Params.empty()) { 11832 CurBlock->TheDecl->setParams(Params); 11833 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11834 CurBlock->TheDecl->param_end(), 11835 /*CheckParameterNames=*/false); 11836 } 11837 11838 // Finally we can process decl attributes. 11839 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11840 11841 // Put the parameter variables in scope. 11842 for (auto AI : CurBlock->TheDecl->params()) { 11843 AI->setOwningFunction(CurBlock->TheDecl); 11844 11845 // If this has an identifier, add it to the scope stack. 11846 if (AI->getIdentifier()) { 11847 CheckShadow(CurBlock->TheScope, AI); 11848 11849 PushOnScopeChains(AI, CurBlock->TheScope); 11850 } 11851 } 11852 } 11853 11854 /// ActOnBlockError - If there is an error parsing a block, this callback 11855 /// is invoked to pop the information about the block from the action impl. 11856 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11857 // Leave the expression-evaluation context. 11858 DiscardCleanupsInEvaluationContext(); 11859 PopExpressionEvaluationContext(); 11860 11861 // Pop off CurBlock, handle nested blocks. 11862 PopDeclContext(); 11863 PopFunctionScopeInfo(); 11864 } 11865 11866 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11867 /// literal was successfully completed. ^(int x){...} 11868 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11869 Stmt *Body, Scope *CurScope) { 11870 // If blocks are disabled, emit an error. 11871 if (!LangOpts.Blocks) 11872 Diag(CaretLoc, diag::err_blocks_disable); 11873 11874 // Leave the expression-evaluation context. 11875 if (hasAnyUnrecoverableErrorsInThisFunction()) 11876 DiscardCleanupsInEvaluationContext(); 11877 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11878 PopExpressionEvaluationContext(); 11879 11880 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11881 11882 if (BSI->HasImplicitReturnType) 11883 deduceClosureReturnType(*BSI); 11884 11885 PopDeclContext(); 11886 11887 QualType RetTy = Context.VoidTy; 11888 if (!BSI->ReturnType.isNull()) 11889 RetTy = BSI->ReturnType; 11890 11891 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11892 QualType BlockTy; 11893 11894 // Set the captured variables on the block. 11895 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11896 SmallVector<BlockDecl::Capture, 4> Captures; 11897 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 11898 if (Cap.isThisCapture()) 11899 continue; 11900 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11901 Cap.isNested(), Cap.getInitExpr()); 11902 Captures.push_back(NewCap); 11903 } 11904 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 11905 11906 // If the user wrote a function type in some form, try to use that. 11907 if (!BSI->FunctionType.isNull()) { 11908 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11909 11910 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11911 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11912 11913 // Turn protoless block types into nullary block types. 11914 if (isa<FunctionNoProtoType>(FTy)) { 11915 FunctionProtoType::ExtProtoInfo EPI; 11916 EPI.ExtInfo = Ext; 11917 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11918 11919 // Otherwise, if we don't need to change anything about the function type, 11920 // preserve its sugar structure. 11921 } else if (FTy->getReturnType() == RetTy && 11922 (!NoReturn || FTy->getNoReturnAttr())) { 11923 BlockTy = BSI->FunctionType; 11924 11925 // Otherwise, make the minimal modifications to the function type. 11926 } else { 11927 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11928 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11929 EPI.TypeQuals = 0; // FIXME: silently? 11930 EPI.ExtInfo = Ext; 11931 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11932 } 11933 11934 // If we don't have a function type, just build one from nothing. 11935 } else { 11936 FunctionProtoType::ExtProtoInfo EPI; 11937 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11938 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11939 } 11940 11941 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11942 BSI->TheDecl->param_end()); 11943 BlockTy = Context.getBlockPointerType(BlockTy); 11944 11945 // If needed, diagnose invalid gotos and switches in the block. 11946 if (getCurFunction()->NeedsScopeChecking() && 11947 !PP.isCodeCompletionEnabled()) 11948 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11949 11950 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11951 11952 // Try to apply the named return value optimization. We have to check again 11953 // if we can do this, though, because blocks keep return statements around 11954 // to deduce an implicit return type. 11955 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11956 !BSI->TheDecl->isDependentContext()) 11957 computeNRVO(Body, BSI); 11958 11959 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11960 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11961 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11962 11963 // If the block isn't obviously global, i.e. it captures anything at 11964 // all, then we need to do a few things in the surrounding context: 11965 if (Result->getBlockDecl()->hasCaptures()) { 11966 // First, this expression has a new cleanup object. 11967 ExprCleanupObjects.push_back(Result->getBlockDecl()); 11968 ExprNeedsCleanups = true; 11969 11970 // It also gets a branch-protected scope if any of the captured 11971 // variables needs destruction. 11972 for (const auto &CI : Result->getBlockDecl()->captures()) { 11973 const VarDecl *var = CI.getVariable(); 11974 if (var->getType().isDestructedType() != QualType::DK_none) { 11975 getCurFunction()->setHasBranchProtectedScope(); 11976 break; 11977 } 11978 } 11979 } 11980 11981 return Result; 11982 } 11983 11984 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 11985 SourceLocation RPLoc) { 11986 TypeSourceInfo *TInfo; 11987 GetTypeFromParser(Ty, &TInfo); 11988 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 11989 } 11990 11991 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 11992 Expr *E, TypeSourceInfo *TInfo, 11993 SourceLocation RPLoc) { 11994 Expr *OrigExpr = E; 11995 bool IsMS = false; 11996 11997 // CUDA device code does not support varargs. 11998 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 11999 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12000 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12001 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12002 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12003 } 12004 } 12005 12006 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12007 // as Microsoft ABI on an actual Microsoft platform, where 12008 // __builtin_ms_va_list and __builtin_va_list are the same.) 12009 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12010 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12011 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12012 if (Context.hasSameType(MSVaListType, E->getType())) { 12013 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12014 return ExprError(); 12015 IsMS = true; 12016 } 12017 } 12018 12019 // Get the va_list type 12020 QualType VaListType = Context.getBuiltinVaListType(); 12021 if (!IsMS) { 12022 if (VaListType->isArrayType()) { 12023 // Deal with implicit array decay; for example, on x86-64, 12024 // va_list is an array, but it's supposed to decay to 12025 // a pointer for va_arg. 12026 VaListType = Context.getArrayDecayedType(VaListType); 12027 // Make sure the input expression also decays appropriately. 12028 ExprResult Result = UsualUnaryConversions(E); 12029 if (Result.isInvalid()) 12030 return ExprError(); 12031 E = Result.get(); 12032 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12033 // If va_list is a record type and we are compiling in C++ mode, 12034 // check the argument using reference binding. 12035 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12036 Context, Context.getLValueReferenceType(VaListType), false); 12037 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12038 if (Init.isInvalid()) 12039 return ExprError(); 12040 E = Init.getAs<Expr>(); 12041 } else { 12042 // Otherwise, the va_list argument must be an l-value because 12043 // it is modified by va_arg. 12044 if (!E->isTypeDependent() && 12045 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12046 return ExprError(); 12047 } 12048 } 12049 12050 if (!IsMS && !E->isTypeDependent() && 12051 !Context.hasSameType(VaListType, E->getType())) 12052 return ExprError(Diag(E->getLocStart(), 12053 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12054 << OrigExpr->getType() << E->getSourceRange()); 12055 12056 if (!TInfo->getType()->isDependentType()) { 12057 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12058 diag::err_second_parameter_to_va_arg_incomplete, 12059 TInfo->getTypeLoc())) 12060 return ExprError(); 12061 12062 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12063 TInfo->getType(), 12064 diag::err_second_parameter_to_va_arg_abstract, 12065 TInfo->getTypeLoc())) 12066 return ExprError(); 12067 12068 if (!TInfo->getType().isPODType(Context)) { 12069 Diag(TInfo->getTypeLoc().getBeginLoc(), 12070 TInfo->getType()->isObjCLifetimeType() 12071 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12072 : diag::warn_second_parameter_to_va_arg_not_pod) 12073 << TInfo->getType() 12074 << TInfo->getTypeLoc().getSourceRange(); 12075 } 12076 12077 // Check for va_arg where arguments of the given type will be promoted 12078 // (i.e. this va_arg is guaranteed to have undefined behavior). 12079 QualType PromoteType; 12080 if (TInfo->getType()->isPromotableIntegerType()) { 12081 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12082 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12083 PromoteType = QualType(); 12084 } 12085 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12086 PromoteType = Context.DoubleTy; 12087 if (!PromoteType.isNull()) 12088 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12089 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12090 << TInfo->getType() 12091 << PromoteType 12092 << TInfo->getTypeLoc().getSourceRange()); 12093 } 12094 12095 QualType T = TInfo->getType().getNonLValueExprType(Context); 12096 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12097 } 12098 12099 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12100 // The type of __null will be int or long, depending on the size of 12101 // pointers on the target. 12102 QualType Ty; 12103 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12104 if (pw == Context.getTargetInfo().getIntWidth()) 12105 Ty = Context.IntTy; 12106 else if (pw == Context.getTargetInfo().getLongWidth()) 12107 Ty = Context.LongTy; 12108 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12109 Ty = Context.LongLongTy; 12110 else { 12111 llvm_unreachable("I don't know size of pointer!"); 12112 } 12113 12114 return new (Context) GNUNullExpr(Ty, TokenLoc); 12115 } 12116 12117 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12118 bool Diagnose) { 12119 if (!getLangOpts().ObjC1) 12120 return false; 12121 12122 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12123 if (!PT) 12124 return false; 12125 12126 if (!PT->isObjCIdType()) { 12127 // Check if the destination is the 'NSString' interface. 12128 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12129 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12130 return false; 12131 } 12132 12133 // Ignore any parens, implicit casts (should only be 12134 // array-to-pointer decays), and not-so-opaque values. The last is 12135 // important for making this trigger for property assignments. 12136 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12137 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12138 if (OV->getSourceExpr()) 12139 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12140 12141 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12142 if (!SL || !SL->isAscii()) 12143 return false; 12144 if (Diagnose) { 12145 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12146 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12147 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12148 } 12149 return true; 12150 } 12151 12152 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12153 const Expr *SrcExpr) { 12154 if (!DstType->isFunctionPointerType() || 12155 !SrcExpr->getType()->isFunctionType()) 12156 return false; 12157 12158 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12159 if (!DRE) 12160 return false; 12161 12162 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12163 if (!FD) 12164 return false; 12165 12166 return !S.checkAddressOfFunctionIsAvailable(FD, 12167 /*Complain=*/true, 12168 SrcExpr->getLocStart()); 12169 } 12170 12171 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12172 SourceLocation Loc, 12173 QualType DstType, QualType SrcType, 12174 Expr *SrcExpr, AssignmentAction Action, 12175 bool *Complained) { 12176 if (Complained) 12177 *Complained = false; 12178 12179 // Decode the result (notice that AST's are still created for extensions). 12180 bool CheckInferredResultType = false; 12181 bool isInvalid = false; 12182 unsigned DiagKind = 0; 12183 FixItHint Hint; 12184 ConversionFixItGenerator ConvHints; 12185 bool MayHaveConvFixit = false; 12186 bool MayHaveFunctionDiff = false; 12187 const ObjCInterfaceDecl *IFace = nullptr; 12188 const ObjCProtocolDecl *PDecl = nullptr; 12189 12190 switch (ConvTy) { 12191 case Compatible: 12192 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12193 return false; 12194 12195 case PointerToInt: 12196 DiagKind = diag::ext_typecheck_convert_pointer_int; 12197 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12198 MayHaveConvFixit = true; 12199 break; 12200 case IntToPointer: 12201 DiagKind = diag::ext_typecheck_convert_int_pointer; 12202 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12203 MayHaveConvFixit = true; 12204 break; 12205 case IncompatiblePointer: 12206 DiagKind = 12207 (Action == AA_Passing_CFAudited ? 12208 diag::err_arc_typecheck_convert_incompatible_pointer : 12209 diag::ext_typecheck_convert_incompatible_pointer); 12210 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12211 SrcType->isObjCObjectPointerType(); 12212 if (Hint.isNull() && !CheckInferredResultType) { 12213 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12214 } 12215 else if (CheckInferredResultType) { 12216 SrcType = SrcType.getUnqualifiedType(); 12217 DstType = DstType.getUnqualifiedType(); 12218 } 12219 MayHaveConvFixit = true; 12220 break; 12221 case IncompatiblePointerSign: 12222 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12223 break; 12224 case FunctionVoidPointer: 12225 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12226 break; 12227 case IncompatiblePointerDiscardsQualifiers: { 12228 // Perform array-to-pointer decay if necessary. 12229 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12230 12231 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12232 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12233 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12234 DiagKind = diag::err_typecheck_incompatible_address_space; 12235 break; 12236 12237 12238 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12239 DiagKind = diag::err_typecheck_incompatible_ownership; 12240 break; 12241 } 12242 12243 llvm_unreachable("unknown error case for discarding qualifiers!"); 12244 // fallthrough 12245 } 12246 case CompatiblePointerDiscardsQualifiers: 12247 // If the qualifiers lost were because we were applying the 12248 // (deprecated) C++ conversion from a string literal to a char* 12249 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12250 // Ideally, this check would be performed in 12251 // checkPointerTypesForAssignment. However, that would require a 12252 // bit of refactoring (so that the second argument is an 12253 // expression, rather than a type), which should be done as part 12254 // of a larger effort to fix checkPointerTypesForAssignment for 12255 // C++ semantics. 12256 if (getLangOpts().CPlusPlus && 12257 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12258 return false; 12259 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12260 break; 12261 case IncompatibleNestedPointerQualifiers: 12262 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12263 break; 12264 case IntToBlockPointer: 12265 DiagKind = diag::err_int_to_block_pointer; 12266 break; 12267 case IncompatibleBlockPointer: 12268 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12269 break; 12270 case IncompatibleObjCQualifiedId: { 12271 if (SrcType->isObjCQualifiedIdType()) { 12272 const ObjCObjectPointerType *srcOPT = 12273 SrcType->getAs<ObjCObjectPointerType>(); 12274 for (auto *srcProto : srcOPT->quals()) { 12275 PDecl = srcProto; 12276 break; 12277 } 12278 if (const ObjCInterfaceType *IFaceT = 12279 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12280 IFace = IFaceT->getDecl(); 12281 } 12282 else if (DstType->isObjCQualifiedIdType()) { 12283 const ObjCObjectPointerType *dstOPT = 12284 DstType->getAs<ObjCObjectPointerType>(); 12285 for (auto *dstProto : dstOPT->quals()) { 12286 PDecl = dstProto; 12287 break; 12288 } 12289 if (const ObjCInterfaceType *IFaceT = 12290 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12291 IFace = IFaceT->getDecl(); 12292 } 12293 DiagKind = diag::warn_incompatible_qualified_id; 12294 break; 12295 } 12296 case IncompatibleVectors: 12297 DiagKind = diag::warn_incompatible_vectors; 12298 break; 12299 case IncompatibleObjCWeakRef: 12300 DiagKind = diag::err_arc_weak_unavailable_assign; 12301 break; 12302 case Incompatible: 12303 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12304 if (Complained) 12305 *Complained = true; 12306 return true; 12307 } 12308 12309 DiagKind = diag::err_typecheck_convert_incompatible; 12310 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12311 MayHaveConvFixit = true; 12312 isInvalid = true; 12313 MayHaveFunctionDiff = true; 12314 break; 12315 } 12316 12317 QualType FirstType, SecondType; 12318 switch (Action) { 12319 case AA_Assigning: 12320 case AA_Initializing: 12321 // The destination type comes first. 12322 FirstType = DstType; 12323 SecondType = SrcType; 12324 break; 12325 12326 case AA_Returning: 12327 case AA_Passing: 12328 case AA_Passing_CFAudited: 12329 case AA_Converting: 12330 case AA_Sending: 12331 case AA_Casting: 12332 // The source type comes first. 12333 FirstType = SrcType; 12334 SecondType = DstType; 12335 break; 12336 } 12337 12338 PartialDiagnostic FDiag = PDiag(DiagKind); 12339 if (Action == AA_Passing_CFAudited) 12340 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12341 else 12342 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12343 12344 // If we can fix the conversion, suggest the FixIts. 12345 assert(ConvHints.isNull() || Hint.isNull()); 12346 if (!ConvHints.isNull()) { 12347 for (FixItHint &H : ConvHints.Hints) 12348 FDiag << H; 12349 } else { 12350 FDiag << Hint; 12351 } 12352 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12353 12354 if (MayHaveFunctionDiff) 12355 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12356 12357 Diag(Loc, FDiag); 12358 if (DiagKind == diag::warn_incompatible_qualified_id && 12359 PDecl && IFace && !IFace->hasDefinition()) 12360 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12361 << IFace->getName() << PDecl->getName(); 12362 12363 if (SecondType == Context.OverloadTy) 12364 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12365 FirstType, /*TakingAddress=*/true); 12366 12367 if (CheckInferredResultType) 12368 EmitRelatedResultTypeNote(SrcExpr); 12369 12370 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12371 EmitRelatedResultTypeNoteForReturn(DstType); 12372 12373 if (Complained) 12374 *Complained = true; 12375 return isInvalid; 12376 } 12377 12378 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12379 llvm::APSInt *Result) { 12380 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12381 public: 12382 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12383 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12384 } 12385 } Diagnoser; 12386 12387 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12388 } 12389 12390 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12391 llvm::APSInt *Result, 12392 unsigned DiagID, 12393 bool AllowFold) { 12394 class IDDiagnoser : public VerifyICEDiagnoser { 12395 unsigned DiagID; 12396 12397 public: 12398 IDDiagnoser(unsigned DiagID) 12399 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12400 12401 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12402 S.Diag(Loc, DiagID) << SR; 12403 } 12404 } Diagnoser(DiagID); 12405 12406 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12407 } 12408 12409 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12410 SourceRange SR) { 12411 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12412 } 12413 12414 ExprResult 12415 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12416 VerifyICEDiagnoser &Diagnoser, 12417 bool AllowFold) { 12418 SourceLocation DiagLoc = E->getLocStart(); 12419 12420 if (getLangOpts().CPlusPlus11) { 12421 // C++11 [expr.const]p5: 12422 // If an expression of literal class type is used in a context where an 12423 // integral constant expression is required, then that class type shall 12424 // have a single non-explicit conversion function to an integral or 12425 // unscoped enumeration type 12426 ExprResult Converted; 12427 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12428 public: 12429 CXX11ConvertDiagnoser(bool Silent) 12430 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12431 Silent, true) {} 12432 12433 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12434 QualType T) override { 12435 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12436 } 12437 12438 SemaDiagnosticBuilder diagnoseIncomplete( 12439 Sema &S, SourceLocation Loc, QualType T) override { 12440 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12441 } 12442 12443 SemaDiagnosticBuilder diagnoseExplicitConv( 12444 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12445 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12446 } 12447 12448 SemaDiagnosticBuilder noteExplicitConv( 12449 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12450 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12451 << ConvTy->isEnumeralType() << ConvTy; 12452 } 12453 12454 SemaDiagnosticBuilder diagnoseAmbiguous( 12455 Sema &S, SourceLocation Loc, QualType T) override { 12456 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12457 } 12458 12459 SemaDiagnosticBuilder noteAmbiguous( 12460 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12461 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12462 << ConvTy->isEnumeralType() << ConvTy; 12463 } 12464 12465 SemaDiagnosticBuilder diagnoseConversion( 12466 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12467 llvm_unreachable("conversion functions are permitted"); 12468 } 12469 } ConvertDiagnoser(Diagnoser.Suppress); 12470 12471 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12472 ConvertDiagnoser); 12473 if (Converted.isInvalid()) 12474 return Converted; 12475 E = Converted.get(); 12476 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12477 return ExprError(); 12478 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12479 // An ICE must be of integral or unscoped enumeration type. 12480 if (!Diagnoser.Suppress) 12481 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12482 return ExprError(); 12483 } 12484 12485 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12486 // in the non-ICE case. 12487 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12488 if (Result) 12489 *Result = E->EvaluateKnownConstInt(Context); 12490 return E; 12491 } 12492 12493 Expr::EvalResult EvalResult; 12494 SmallVector<PartialDiagnosticAt, 8> Notes; 12495 EvalResult.Diag = &Notes; 12496 12497 // Try to evaluate the expression, and produce diagnostics explaining why it's 12498 // not a constant expression as a side-effect. 12499 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12500 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12501 12502 // In C++11, we can rely on diagnostics being produced for any expression 12503 // which is not a constant expression. If no diagnostics were produced, then 12504 // this is a constant expression. 12505 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12506 if (Result) 12507 *Result = EvalResult.Val.getInt(); 12508 return E; 12509 } 12510 12511 // If our only note is the usual "invalid subexpression" note, just point 12512 // the caret at its location rather than producing an essentially 12513 // redundant note. 12514 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12515 diag::note_invalid_subexpr_in_const_expr) { 12516 DiagLoc = Notes[0].first; 12517 Notes.clear(); 12518 } 12519 12520 if (!Folded || !AllowFold) { 12521 if (!Diagnoser.Suppress) { 12522 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12523 for (const PartialDiagnosticAt &Note : Notes) 12524 Diag(Note.first, Note.second); 12525 } 12526 12527 return ExprError(); 12528 } 12529 12530 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12531 for (const PartialDiagnosticAt &Note : Notes) 12532 Diag(Note.first, Note.second); 12533 12534 if (Result) 12535 *Result = EvalResult.Val.getInt(); 12536 return E; 12537 } 12538 12539 namespace { 12540 // Handle the case where we conclude a expression which we speculatively 12541 // considered to be unevaluated is actually evaluated. 12542 class TransformToPE : public TreeTransform<TransformToPE> { 12543 typedef TreeTransform<TransformToPE> BaseTransform; 12544 12545 public: 12546 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12547 12548 // Make sure we redo semantic analysis 12549 bool AlwaysRebuild() { return true; } 12550 12551 // Make sure we handle LabelStmts correctly. 12552 // FIXME: This does the right thing, but maybe we need a more general 12553 // fix to TreeTransform? 12554 StmtResult TransformLabelStmt(LabelStmt *S) { 12555 S->getDecl()->setStmt(nullptr); 12556 return BaseTransform::TransformLabelStmt(S); 12557 } 12558 12559 // We need to special-case DeclRefExprs referring to FieldDecls which 12560 // are not part of a member pointer formation; normal TreeTransforming 12561 // doesn't catch this case because of the way we represent them in the AST. 12562 // FIXME: This is a bit ugly; is it really the best way to handle this 12563 // case? 12564 // 12565 // Error on DeclRefExprs referring to FieldDecls. 12566 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12567 if (isa<FieldDecl>(E->getDecl()) && 12568 !SemaRef.isUnevaluatedContext()) 12569 return SemaRef.Diag(E->getLocation(), 12570 diag::err_invalid_non_static_member_use) 12571 << E->getDecl() << E->getSourceRange(); 12572 12573 return BaseTransform::TransformDeclRefExpr(E); 12574 } 12575 12576 // Exception: filter out member pointer formation 12577 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12578 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12579 return E; 12580 12581 return BaseTransform::TransformUnaryOperator(E); 12582 } 12583 12584 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12585 // Lambdas never need to be transformed. 12586 return E; 12587 } 12588 }; 12589 } 12590 12591 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12592 assert(isUnevaluatedContext() && 12593 "Should only transform unevaluated expressions"); 12594 ExprEvalContexts.back().Context = 12595 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12596 if (isUnevaluatedContext()) 12597 return E; 12598 return TransformToPE(*this).TransformExpr(E); 12599 } 12600 12601 void 12602 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12603 Decl *LambdaContextDecl, 12604 bool IsDecltype) { 12605 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12606 ExprNeedsCleanups, LambdaContextDecl, 12607 IsDecltype); 12608 ExprNeedsCleanups = false; 12609 if (!MaybeODRUseExprs.empty()) 12610 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12611 } 12612 12613 void 12614 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12615 ReuseLambdaContextDecl_t, 12616 bool IsDecltype) { 12617 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12618 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12619 } 12620 12621 void Sema::PopExpressionEvaluationContext() { 12622 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12623 unsigned NumTypos = Rec.NumTypos; 12624 12625 if (!Rec.Lambdas.empty()) { 12626 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12627 unsigned D; 12628 if (Rec.isUnevaluated()) { 12629 // C++11 [expr.prim.lambda]p2: 12630 // A lambda-expression shall not appear in an unevaluated operand 12631 // (Clause 5). 12632 D = diag::err_lambda_unevaluated_operand; 12633 } else { 12634 // C++1y [expr.const]p2: 12635 // A conditional-expression e is a core constant expression unless the 12636 // evaluation of e, following the rules of the abstract machine, would 12637 // evaluate [...] a lambda-expression. 12638 D = diag::err_lambda_in_constant_expression; 12639 } 12640 for (const auto *L : Rec.Lambdas) 12641 Diag(L->getLocStart(), D); 12642 } else { 12643 // Mark the capture expressions odr-used. This was deferred 12644 // during lambda expression creation. 12645 for (auto *Lambda : Rec.Lambdas) { 12646 for (auto *C : Lambda->capture_inits()) 12647 MarkDeclarationsReferencedInExpr(C); 12648 } 12649 } 12650 } 12651 12652 // When are coming out of an unevaluated context, clear out any 12653 // temporaries that we may have created as part of the evaluation of 12654 // the expression in that context: they aren't relevant because they 12655 // will never be constructed. 12656 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12657 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12658 ExprCleanupObjects.end()); 12659 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12660 CleanupVarDeclMarking(); 12661 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12662 // Otherwise, merge the contexts together. 12663 } else { 12664 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12665 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12666 Rec.SavedMaybeODRUseExprs.end()); 12667 } 12668 12669 // Pop the current expression evaluation context off the stack. 12670 ExprEvalContexts.pop_back(); 12671 12672 if (!ExprEvalContexts.empty()) 12673 ExprEvalContexts.back().NumTypos += NumTypos; 12674 else 12675 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12676 "last ExpressionEvaluationContextRecord"); 12677 } 12678 12679 void Sema::DiscardCleanupsInEvaluationContext() { 12680 ExprCleanupObjects.erase( 12681 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12682 ExprCleanupObjects.end()); 12683 ExprNeedsCleanups = false; 12684 MaybeODRUseExprs.clear(); 12685 } 12686 12687 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12688 if (!E->getType()->isVariablyModifiedType()) 12689 return E; 12690 return TransformToPotentiallyEvaluated(E); 12691 } 12692 12693 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12694 // Do not mark anything as "used" within a dependent context; wait for 12695 // an instantiation. 12696 if (SemaRef.CurContext->isDependentContext()) 12697 return false; 12698 12699 switch (SemaRef.ExprEvalContexts.back().Context) { 12700 case Sema::Unevaluated: 12701 case Sema::UnevaluatedAbstract: 12702 // We are in an expression that is not potentially evaluated; do nothing. 12703 // (Depending on how you read the standard, we actually do need to do 12704 // something here for null pointer constants, but the standard's 12705 // definition of a null pointer constant is completely crazy.) 12706 return false; 12707 12708 case Sema::ConstantEvaluated: 12709 case Sema::PotentiallyEvaluated: 12710 // We are in a potentially evaluated expression (or a constant-expression 12711 // in C++03); we need to do implicit template instantiation, implicitly 12712 // define class members, and mark most declarations as used. 12713 return true; 12714 12715 case Sema::PotentiallyEvaluatedIfUsed: 12716 // Referenced declarations will only be used if the construct in the 12717 // containing expression is used. 12718 return false; 12719 } 12720 llvm_unreachable("Invalid context"); 12721 } 12722 12723 /// \brief Mark a function referenced, and check whether it is odr-used 12724 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12725 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12726 bool OdrUse) { 12727 assert(Func && "No function?"); 12728 12729 Func->setReferenced(); 12730 12731 // C++11 [basic.def.odr]p3: 12732 // A function whose name appears as a potentially-evaluated expression is 12733 // odr-used if it is the unique lookup result or the selected member of a 12734 // set of overloaded functions [...]. 12735 // 12736 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12737 // can just check that here. Skip the rest of this function if we've already 12738 // marked the function as used. 12739 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12740 !IsPotentiallyEvaluatedContext(*this)) { 12741 // C++11 [temp.inst]p3: 12742 // Unless a function template specialization has been explicitly 12743 // instantiated or explicitly specialized, the function template 12744 // specialization is implicitly instantiated when the specialization is 12745 // referenced in a context that requires a function definition to exist. 12746 // 12747 // We consider constexpr function templates to be referenced in a context 12748 // that requires a definition to exist whenever they are referenced. 12749 // 12750 // FIXME: This instantiates constexpr functions too frequently. If this is 12751 // really an unevaluated context (and we're not just in the definition of a 12752 // function template or overload resolution or other cases which we 12753 // incorrectly consider to be unevaluated contexts), and we're not in a 12754 // subexpression which we actually need to evaluate (for instance, a 12755 // template argument, array bound or an expression in a braced-init-list), 12756 // we are not permitted to instantiate this constexpr function definition. 12757 // 12758 // FIXME: This also implicitly defines special members too frequently. They 12759 // are only supposed to be implicitly defined if they are odr-used, but they 12760 // are not odr-used from constant expressions in unevaluated contexts. 12761 // However, they cannot be referenced if they are deleted, and they are 12762 // deleted whenever the implicit definition of the special member would 12763 // fail. 12764 if (!Func->isConstexpr() || Func->getBody()) 12765 return; 12766 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12767 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12768 return; 12769 } 12770 12771 // Note that this declaration has been used. 12772 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12773 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12774 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12775 if (Constructor->isDefaultConstructor()) { 12776 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12777 return; 12778 DefineImplicitDefaultConstructor(Loc, Constructor); 12779 } else if (Constructor->isCopyConstructor()) { 12780 DefineImplicitCopyConstructor(Loc, Constructor); 12781 } else if (Constructor->isMoveConstructor()) { 12782 DefineImplicitMoveConstructor(Loc, Constructor); 12783 } 12784 } else if (Constructor->getInheritedConstructor()) { 12785 DefineInheritingConstructor(Loc, Constructor); 12786 } 12787 } else if (CXXDestructorDecl *Destructor = 12788 dyn_cast<CXXDestructorDecl>(Func)) { 12789 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12790 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12791 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12792 return; 12793 DefineImplicitDestructor(Loc, Destructor); 12794 } 12795 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12796 MarkVTableUsed(Loc, Destructor->getParent()); 12797 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12798 if (MethodDecl->isOverloadedOperator() && 12799 MethodDecl->getOverloadedOperator() == OO_Equal) { 12800 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12801 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12802 if (MethodDecl->isCopyAssignmentOperator()) 12803 DefineImplicitCopyAssignment(Loc, MethodDecl); 12804 else 12805 DefineImplicitMoveAssignment(Loc, MethodDecl); 12806 } 12807 } else if (isa<CXXConversionDecl>(MethodDecl) && 12808 MethodDecl->getParent()->isLambda()) { 12809 CXXConversionDecl *Conversion = 12810 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12811 if (Conversion->isLambdaToBlockPointerConversion()) 12812 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12813 else 12814 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12815 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12816 MarkVTableUsed(Loc, MethodDecl->getParent()); 12817 } 12818 12819 // Recursive functions should be marked when used from another function. 12820 // FIXME: Is this really right? 12821 if (CurContext == Func) return; 12822 12823 // Resolve the exception specification for any function which is 12824 // used: CodeGen will need it. 12825 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12826 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12827 ResolveExceptionSpec(Loc, FPT); 12828 12829 if (!OdrUse) return; 12830 12831 // Implicit instantiation of function templates and member functions of 12832 // class templates. 12833 if (Func->isImplicitlyInstantiable()) { 12834 bool AlreadyInstantiated = false; 12835 SourceLocation PointOfInstantiation = Loc; 12836 if (FunctionTemplateSpecializationInfo *SpecInfo 12837 = Func->getTemplateSpecializationInfo()) { 12838 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12839 SpecInfo->setPointOfInstantiation(Loc); 12840 else if (SpecInfo->getTemplateSpecializationKind() 12841 == TSK_ImplicitInstantiation) { 12842 AlreadyInstantiated = true; 12843 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12844 } 12845 } else if (MemberSpecializationInfo *MSInfo 12846 = Func->getMemberSpecializationInfo()) { 12847 if (MSInfo->getPointOfInstantiation().isInvalid()) 12848 MSInfo->setPointOfInstantiation(Loc); 12849 else if (MSInfo->getTemplateSpecializationKind() 12850 == TSK_ImplicitInstantiation) { 12851 AlreadyInstantiated = true; 12852 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12853 } 12854 } 12855 12856 if (!AlreadyInstantiated || Func->isConstexpr()) { 12857 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12858 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12859 ActiveTemplateInstantiations.size()) 12860 PendingLocalImplicitInstantiations.push_back( 12861 std::make_pair(Func, PointOfInstantiation)); 12862 else if (Func->isConstexpr()) 12863 // Do not defer instantiations of constexpr functions, to avoid the 12864 // expression evaluator needing to call back into Sema if it sees a 12865 // call to such a function. 12866 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12867 else { 12868 PendingInstantiations.push_back(std::make_pair(Func, 12869 PointOfInstantiation)); 12870 // Notify the consumer that a function was implicitly instantiated. 12871 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12872 } 12873 } 12874 } else { 12875 // Walk redefinitions, as some of them may be instantiable. 12876 for (auto i : Func->redecls()) { 12877 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12878 MarkFunctionReferenced(Loc, i); 12879 } 12880 } 12881 12882 // Keep track of used but undefined functions. 12883 if (!Func->isDefined()) { 12884 if (mightHaveNonExternalLinkage(Func)) 12885 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12886 else if (Func->getMostRecentDecl()->isInlined() && 12887 !LangOpts.GNUInline && 12888 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12889 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12890 } 12891 12892 // Normally the most current decl is marked used while processing the use and 12893 // any subsequent decls are marked used by decl merging. This fails with 12894 // template instantiation since marking can happen at the end of the file 12895 // and, because of the two phase lookup, this function is called with at 12896 // decl in the middle of a decl chain. We loop to maintain the invariant 12897 // that once a decl is used, all decls after it are also used. 12898 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12899 F->markUsed(Context); 12900 if (F == Func) 12901 break; 12902 } 12903 } 12904 12905 static void 12906 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12907 VarDecl *var, DeclContext *DC) { 12908 DeclContext *VarDC = var->getDeclContext(); 12909 12910 // If the parameter still belongs to the translation unit, then 12911 // we're actually just using one parameter in the declaration of 12912 // the next. 12913 if (isa<ParmVarDecl>(var) && 12914 isa<TranslationUnitDecl>(VarDC)) 12915 return; 12916 12917 // For C code, don't diagnose about capture if we're not actually in code 12918 // right now; it's impossible to write a non-constant expression outside of 12919 // function context, so we'll get other (more useful) diagnostics later. 12920 // 12921 // For C++, things get a bit more nasty... it would be nice to suppress this 12922 // diagnostic for certain cases like using a local variable in an array bound 12923 // for a member of a local class, but the correct predicate is not obvious. 12924 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12925 return; 12926 12927 if (isa<CXXMethodDecl>(VarDC) && 12928 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12929 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12930 << var->getIdentifier(); 12931 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12932 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12933 << var->getIdentifier() << fn->getDeclName(); 12934 } else if (isa<BlockDecl>(VarDC)) { 12935 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12936 << var->getIdentifier(); 12937 } else { 12938 // FIXME: Is there any other context where a local variable can be 12939 // declared? 12940 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12941 << var->getIdentifier(); 12942 } 12943 12944 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12945 << var->getIdentifier(); 12946 12947 // FIXME: Add additional diagnostic info about class etc. which prevents 12948 // capture. 12949 } 12950 12951 12952 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12953 bool &SubCapturesAreNested, 12954 QualType &CaptureType, 12955 QualType &DeclRefType) { 12956 // Check whether we've already captured it. 12957 if (CSI->CaptureMap.count(Var)) { 12958 // If we found a capture, any subcaptures are nested. 12959 SubCapturesAreNested = true; 12960 12961 // Retrieve the capture type for this variable. 12962 CaptureType = CSI->getCapture(Var).getCaptureType(); 12963 12964 // Compute the type of an expression that refers to this variable. 12965 DeclRefType = CaptureType.getNonReferenceType(); 12966 12967 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 12968 // are mutable in the sense that user can change their value - they are 12969 // private instances of the captured declarations. 12970 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 12971 if (Cap.isCopyCapture() && 12972 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 12973 !(isa<CapturedRegionScopeInfo>(CSI) && 12974 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 12975 DeclRefType.addConst(); 12976 return true; 12977 } 12978 return false; 12979 } 12980 12981 // Only block literals, captured statements, and lambda expressions can 12982 // capture; other scopes don't work. 12983 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 12984 SourceLocation Loc, 12985 const bool Diagnose, Sema &S) { 12986 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 12987 return getLambdaAwareParentOfDeclContext(DC); 12988 else if (Var->hasLocalStorage()) { 12989 if (Diagnose) 12990 diagnoseUncapturableValueReference(S, Loc, Var, DC); 12991 } 12992 return nullptr; 12993 } 12994 12995 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12996 // certain types of variables (unnamed, variably modified types etc.) 12997 // so check for eligibility. 12998 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 12999 SourceLocation Loc, 13000 const bool Diagnose, Sema &S) { 13001 13002 bool IsBlock = isa<BlockScopeInfo>(CSI); 13003 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13004 13005 // Lambdas are not allowed to capture unnamed variables 13006 // (e.g. anonymous unions). 13007 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13008 // assuming that's the intent. 13009 if (IsLambda && !Var->getDeclName()) { 13010 if (Diagnose) { 13011 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13012 S.Diag(Var->getLocation(), diag::note_declared_at); 13013 } 13014 return false; 13015 } 13016 13017 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13018 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13019 if (Diagnose) { 13020 S.Diag(Loc, diag::err_ref_vm_type); 13021 S.Diag(Var->getLocation(), diag::note_previous_decl) 13022 << Var->getDeclName(); 13023 } 13024 return false; 13025 } 13026 // Prohibit structs with flexible array members too. 13027 // We cannot capture what is in the tail end of the struct. 13028 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13029 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13030 if (Diagnose) { 13031 if (IsBlock) 13032 S.Diag(Loc, diag::err_ref_flexarray_type); 13033 else 13034 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13035 << Var->getDeclName(); 13036 S.Diag(Var->getLocation(), diag::note_previous_decl) 13037 << Var->getDeclName(); 13038 } 13039 return false; 13040 } 13041 } 13042 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13043 // Lambdas and captured statements are not allowed to capture __block 13044 // variables; they don't support the expected semantics. 13045 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13046 if (Diagnose) { 13047 S.Diag(Loc, diag::err_capture_block_variable) 13048 << Var->getDeclName() << !IsLambda; 13049 S.Diag(Var->getLocation(), diag::note_previous_decl) 13050 << Var->getDeclName(); 13051 } 13052 return false; 13053 } 13054 13055 return true; 13056 } 13057 13058 // Returns true if the capture by block was successful. 13059 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13060 SourceLocation Loc, 13061 const bool BuildAndDiagnose, 13062 QualType &CaptureType, 13063 QualType &DeclRefType, 13064 const bool Nested, 13065 Sema &S) { 13066 Expr *CopyExpr = nullptr; 13067 bool ByRef = false; 13068 13069 // Blocks are not allowed to capture arrays. 13070 if (CaptureType->isArrayType()) { 13071 if (BuildAndDiagnose) { 13072 S.Diag(Loc, diag::err_ref_array_type); 13073 S.Diag(Var->getLocation(), diag::note_previous_decl) 13074 << Var->getDeclName(); 13075 } 13076 return false; 13077 } 13078 13079 // Forbid the block-capture of autoreleasing variables. 13080 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13081 if (BuildAndDiagnose) { 13082 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13083 << /*block*/ 0; 13084 S.Diag(Var->getLocation(), diag::note_previous_decl) 13085 << Var->getDeclName(); 13086 } 13087 return false; 13088 } 13089 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13090 if (HasBlocksAttr || CaptureType->isReferenceType()) { 13091 // Block capture by reference does not change the capture or 13092 // declaration reference types. 13093 ByRef = true; 13094 } else { 13095 // Block capture by copy introduces 'const'. 13096 CaptureType = CaptureType.getNonReferenceType().withConst(); 13097 DeclRefType = CaptureType; 13098 13099 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13100 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13101 // The capture logic needs the destructor, so make sure we mark it. 13102 // Usually this is unnecessary because most local variables have 13103 // their destructors marked at declaration time, but parameters are 13104 // an exception because it's technically only the call site that 13105 // actually requires the destructor. 13106 if (isa<ParmVarDecl>(Var)) 13107 S.FinalizeVarWithDestructor(Var, Record); 13108 13109 // Enter a new evaluation context to insulate the copy 13110 // full-expression. 13111 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13112 13113 // According to the blocks spec, the capture of a variable from 13114 // the stack requires a const copy constructor. This is not true 13115 // of the copy/move done to move a __block variable to the heap. 13116 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13117 DeclRefType.withConst(), 13118 VK_LValue, Loc); 13119 13120 ExprResult Result 13121 = S.PerformCopyInitialization( 13122 InitializedEntity::InitializeBlock(Var->getLocation(), 13123 CaptureType, false), 13124 Loc, DeclRef); 13125 13126 // Build a full-expression copy expression if initialization 13127 // succeeded and used a non-trivial constructor. Recover from 13128 // errors by pretending that the copy isn't necessary. 13129 if (!Result.isInvalid() && 13130 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13131 ->isTrivial()) { 13132 Result = S.MaybeCreateExprWithCleanups(Result); 13133 CopyExpr = Result.get(); 13134 } 13135 } 13136 } 13137 } 13138 13139 // Actually capture the variable. 13140 if (BuildAndDiagnose) 13141 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13142 SourceLocation(), CaptureType, CopyExpr); 13143 13144 return true; 13145 13146 } 13147 13148 13149 /// \brief Capture the given variable in the captured region. 13150 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13151 VarDecl *Var, 13152 SourceLocation Loc, 13153 const bool BuildAndDiagnose, 13154 QualType &CaptureType, 13155 QualType &DeclRefType, 13156 const bool RefersToCapturedVariable, 13157 Sema &S) { 13158 13159 // By default, capture variables by reference. 13160 bool ByRef = true; 13161 // Using an LValue reference type is consistent with Lambdas (see below). 13162 if (S.getLangOpts().OpenMP) { 13163 ByRef = S.IsOpenMPCapturedByRef(Var, RSI); 13164 if (S.IsOpenMPCapturedDecl(Var)) 13165 DeclRefType = DeclRefType.getUnqualifiedType(); 13166 } 13167 13168 if (ByRef) 13169 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13170 else 13171 CaptureType = DeclRefType; 13172 13173 Expr *CopyExpr = nullptr; 13174 if (BuildAndDiagnose) { 13175 // The current implementation assumes that all variables are captured 13176 // by references. Since there is no capture by copy, no expression 13177 // evaluation will be needed. 13178 RecordDecl *RD = RSI->TheRecordDecl; 13179 13180 FieldDecl *Field 13181 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13182 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13183 nullptr, false, ICIS_NoInit); 13184 Field->setImplicit(true); 13185 Field->setAccess(AS_private); 13186 RD->addDecl(Field); 13187 13188 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13189 DeclRefType, VK_LValue, Loc); 13190 Var->setReferenced(true); 13191 Var->markUsed(S.Context); 13192 } 13193 13194 // Actually capture the variable. 13195 if (BuildAndDiagnose) 13196 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13197 SourceLocation(), CaptureType, CopyExpr); 13198 13199 13200 return true; 13201 } 13202 13203 /// \brief Create a field within the lambda class for the variable 13204 /// being captured. 13205 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 13206 QualType FieldType, QualType DeclRefType, 13207 SourceLocation Loc, 13208 bool RefersToCapturedVariable) { 13209 CXXRecordDecl *Lambda = LSI->Lambda; 13210 13211 // Build the non-static data member. 13212 FieldDecl *Field 13213 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13214 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13215 nullptr, false, ICIS_NoInit); 13216 Field->setImplicit(true); 13217 Field->setAccess(AS_private); 13218 Lambda->addDecl(Field); 13219 } 13220 13221 /// \brief Capture the given variable in the lambda. 13222 static bool captureInLambda(LambdaScopeInfo *LSI, 13223 VarDecl *Var, 13224 SourceLocation Loc, 13225 const bool BuildAndDiagnose, 13226 QualType &CaptureType, 13227 QualType &DeclRefType, 13228 const bool RefersToCapturedVariable, 13229 const Sema::TryCaptureKind Kind, 13230 SourceLocation EllipsisLoc, 13231 const bool IsTopScope, 13232 Sema &S) { 13233 13234 // Determine whether we are capturing by reference or by value. 13235 bool ByRef = false; 13236 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13237 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13238 } else { 13239 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13240 } 13241 13242 // Compute the type of the field that will capture this variable. 13243 if (ByRef) { 13244 // C++11 [expr.prim.lambda]p15: 13245 // An entity is captured by reference if it is implicitly or 13246 // explicitly captured but not captured by copy. It is 13247 // unspecified whether additional unnamed non-static data 13248 // members are declared in the closure type for entities 13249 // captured by reference. 13250 // 13251 // FIXME: It is not clear whether we want to build an lvalue reference 13252 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13253 // to do the former, while EDG does the latter. Core issue 1249 will 13254 // clarify, but for now we follow GCC because it's a more permissive and 13255 // easily defensible position. 13256 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13257 } else { 13258 // C++11 [expr.prim.lambda]p14: 13259 // For each entity captured by copy, an unnamed non-static 13260 // data member is declared in the closure type. The 13261 // declaration order of these members is unspecified. The type 13262 // of such a data member is the type of the corresponding 13263 // captured entity if the entity is not a reference to an 13264 // object, or the referenced type otherwise. [Note: If the 13265 // captured entity is a reference to a function, the 13266 // corresponding data member is also a reference to a 13267 // function. - end note ] 13268 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13269 if (!RefType->getPointeeType()->isFunctionType()) 13270 CaptureType = RefType->getPointeeType(); 13271 } 13272 13273 // Forbid the lambda copy-capture of autoreleasing variables. 13274 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13275 if (BuildAndDiagnose) { 13276 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13277 S.Diag(Var->getLocation(), diag::note_previous_decl) 13278 << Var->getDeclName(); 13279 } 13280 return false; 13281 } 13282 13283 // Make sure that by-copy captures are of a complete and non-abstract type. 13284 if (BuildAndDiagnose) { 13285 if (!CaptureType->isDependentType() && 13286 S.RequireCompleteType(Loc, CaptureType, 13287 diag::err_capture_of_incomplete_type, 13288 Var->getDeclName())) 13289 return false; 13290 13291 if (S.RequireNonAbstractType(Loc, CaptureType, 13292 diag::err_capture_of_abstract_type)) 13293 return false; 13294 } 13295 } 13296 13297 // Capture this variable in the lambda. 13298 if (BuildAndDiagnose) 13299 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 13300 RefersToCapturedVariable); 13301 13302 // Compute the type of a reference to this captured variable. 13303 if (ByRef) 13304 DeclRefType = CaptureType.getNonReferenceType(); 13305 else { 13306 // C++ [expr.prim.lambda]p5: 13307 // The closure type for a lambda-expression has a public inline 13308 // function call operator [...]. This function call operator is 13309 // declared const (9.3.1) if and only if the lambda-expression’s 13310 // parameter-declaration-clause is not followed by mutable. 13311 DeclRefType = CaptureType.getNonReferenceType(); 13312 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13313 DeclRefType.addConst(); 13314 } 13315 13316 // Add the capture. 13317 if (BuildAndDiagnose) 13318 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13319 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13320 13321 return true; 13322 } 13323 13324 bool Sema::tryCaptureVariable( 13325 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13326 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13327 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13328 // An init-capture is notionally from the context surrounding its 13329 // declaration, but its parent DC is the lambda class. 13330 DeclContext *VarDC = Var->getDeclContext(); 13331 if (Var->isInitCapture()) 13332 VarDC = VarDC->getParent(); 13333 13334 DeclContext *DC = CurContext; 13335 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13336 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13337 // We need to sync up the Declaration Context with the 13338 // FunctionScopeIndexToStopAt 13339 if (FunctionScopeIndexToStopAt) { 13340 unsigned FSIndex = FunctionScopes.size() - 1; 13341 while (FSIndex != MaxFunctionScopesIndex) { 13342 DC = getLambdaAwareParentOfDeclContext(DC); 13343 --FSIndex; 13344 } 13345 } 13346 13347 13348 // If the variable is declared in the current context, there is no need to 13349 // capture it. 13350 if (VarDC == DC) return true; 13351 13352 // Capture global variables if it is required to use private copy of this 13353 // variable. 13354 bool IsGlobal = !Var->hasLocalStorage(); 13355 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13356 return true; 13357 13358 // Walk up the stack to determine whether we can capture the variable, 13359 // performing the "simple" checks that don't depend on type. We stop when 13360 // we've either hit the declared scope of the variable or find an existing 13361 // capture of that variable. We start from the innermost capturing-entity 13362 // (the DC) and ensure that all intervening capturing-entities 13363 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13364 // declcontext can either capture the variable or have already captured 13365 // the variable. 13366 CaptureType = Var->getType(); 13367 DeclRefType = CaptureType.getNonReferenceType(); 13368 bool Nested = false; 13369 bool Explicit = (Kind != TryCapture_Implicit); 13370 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13371 unsigned OpenMPLevel = 0; 13372 do { 13373 // Only block literals, captured statements, and lambda expressions can 13374 // capture; other scopes don't work. 13375 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13376 ExprLoc, 13377 BuildAndDiagnose, 13378 *this); 13379 // We need to check for the parent *first* because, if we *have* 13380 // private-captured a global variable, we need to recursively capture it in 13381 // intermediate blocks, lambdas, etc. 13382 if (!ParentDC) { 13383 if (IsGlobal) { 13384 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13385 break; 13386 } 13387 return true; 13388 } 13389 13390 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13391 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13392 13393 13394 // Check whether we've already captured it. 13395 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13396 DeclRefType)) 13397 break; 13398 // If we are instantiating a generic lambda call operator body, 13399 // we do not want to capture new variables. What was captured 13400 // during either a lambdas transformation or initial parsing 13401 // should be used. 13402 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13403 if (BuildAndDiagnose) { 13404 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13405 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13406 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13407 Diag(Var->getLocation(), diag::note_previous_decl) 13408 << Var->getDeclName(); 13409 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13410 } else 13411 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13412 } 13413 return true; 13414 } 13415 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13416 // certain types of variables (unnamed, variably modified types etc.) 13417 // so check for eligibility. 13418 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13419 return true; 13420 13421 // Try to capture variable-length arrays types. 13422 if (Var->getType()->isVariablyModifiedType()) { 13423 // We're going to walk down into the type and look for VLA 13424 // expressions. 13425 QualType QTy = Var->getType(); 13426 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13427 QTy = PVD->getOriginalType(); 13428 captureVariablyModifiedType(Context, QTy, CSI); 13429 } 13430 13431 if (getLangOpts().OpenMP) { 13432 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13433 // OpenMP private variables should not be captured in outer scope, so 13434 // just break here. Similarly, global variables that are captured in a 13435 // target region should not be captured outside the scope of the region. 13436 if (RSI->CapRegionKind == CR_OpenMP) { 13437 auto isTargetCap = isOpenMPTargetCapturedDecl(Var, OpenMPLevel); 13438 // When we detect target captures we are looking from inside the 13439 // target region, therefore we need to propagate the capture from the 13440 // enclosing region. Therefore, the capture is not initially nested. 13441 if (isTargetCap) 13442 FunctionScopesIndex--; 13443 13444 if (isTargetCap || isOpenMPPrivateDecl(Var, OpenMPLevel)) { 13445 Nested = !isTargetCap; 13446 DeclRefType = DeclRefType.getUnqualifiedType(); 13447 CaptureType = Context.getLValueReferenceType(DeclRefType); 13448 break; 13449 } 13450 ++OpenMPLevel; 13451 } 13452 } 13453 } 13454 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13455 // No capture-default, and this is not an explicit capture 13456 // so cannot capture this variable. 13457 if (BuildAndDiagnose) { 13458 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13459 Diag(Var->getLocation(), diag::note_previous_decl) 13460 << Var->getDeclName(); 13461 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13462 diag::note_lambda_decl); 13463 // FIXME: If we error out because an outer lambda can not implicitly 13464 // capture a variable that an inner lambda explicitly captures, we 13465 // should have the inner lambda do the explicit capture - because 13466 // it makes for cleaner diagnostics later. This would purely be done 13467 // so that the diagnostic does not misleadingly claim that a variable 13468 // can not be captured by a lambda implicitly even though it is captured 13469 // explicitly. Suggestion: 13470 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13471 // at the function head 13472 // - cache the StartingDeclContext - this must be a lambda 13473 // - captureInLambda in the innermost lambda the variable. 13474 } 13475 return true; 13476 } 13477 13478 FunctionScopesIndex--; 13479 DC = ParentDC; 13480 Explicit = false; 13481 } while (!VarDC->Equals(DC)); 13482 13483 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13484 // computing the type of the capture at each step, checking type-specific 13485 // requirements, and adding captures if requested. 13486 // If the variable had already been captured previously, we start capturing 13487 // at the lambda nested within that one. 13488 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13489 ++I) { 13490 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13491 13492 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13493 if (!captureInBlock(BSI, Var, ExprLoc, 13494 BuildAndDiagnose, CaptureType, 13495 DeclRefType, Nested, *this)) 13496 return true; 13497 Nested = true; 13498 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13499 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13500 BuildAndDiagnose, CaptureType, 13501 DeclRefType, Nested, *this)) 13502 return true; 13503 Nested = true; 13504 } else { 13505 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13506 if (!captureInLambda(LSI, Var, ExprLoc, 13507 BuildAndDiagnose, CaptureType, 13508 DeclRefType, Nested, Kind, EllipsisLoc, 13509 /*IsTopScope*/I == N - 1, *this)) 13510 return true; 13511 Nested = true; 13512 } 13513 } 13514 return false; 13515 } 13516 13517 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13518 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13519 QualType CaptureType; 13520 QualType DeclRefType; 13521 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13522 /*BuildAndDiagnose=*/true, CaptureType, 13523 DeclRefType, nullptr); 13524 } 13525 13526 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13527 QualType CaptureType; 13528 QualType DeclRefType; 13529 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13530 /*BuildAndDiagnose=*/false, CaptureType, 13531 DeclRefType, nullptr); 13532 } 13533 13534 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13535 QualType CaptureType; 13536 QualType DeclRefType; 13537 13538 // Determine whether we can capture this variable. 13539 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13540 /*BuildAndDiagnose=*/false, CaptureType, 13541 DeclRefType, nullptr)) 13542 return QualType(); 13543 13544 return DeclRefType; 13545 } 13546 13547 13548 13549 // If either the type of the variable or the initializer is dependent, 13550 // return false. Otherwise, determine whether the variable is a constant 13551 // expression. Use this if you need to know if a variable that might or 13552 // might not be dependent is truly a constant expression. 13553 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13554 ASTContext &Context) { 13555 13556 if (Var->getType()->isDependentType()) 13557 return false; 13558 const VarDecl *DefVD = nullptr; 13559 Var->getAnyInitializer(DefVD); 13560 if (!DefVD) 13561 return false; 13562 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13563 Expr *Init = cast<Expr>(Eval->Value); 13564 if (Init->isValueDependent()) 13565 return false; 13566 return IsVariableAConstantExpression(Var, Context); 13567 } 13568 13569 13570 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13571 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13572 // an object that satisfies the requirements for appearing in a 13573 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13574 // is immediately applied." This function handles the lvalue-to-rvalue 13575 // conversion part. 13576 MaybeODRUseExprs.erase(E->IgnoreParens()); 13577 13578 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13579 // to a variable that is a constant expression, and if so, identify it as 13580 // a reference to a variable that does not involve an odr-use of that 13581 // variable. 13582 if (LambdaScopeInfo *LSI = getCurLambda()) { 13583 Expr *SansParensExpr = E->IgnoreParens(); 13584 VarDecl *Var = nullptr; 13585 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13586 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13587 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13588 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13589 13590 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13591 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13592 } 13593 } 13594 13595 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13596 Res = CorrectDelayedTyposInExpr(Res); 13597 13598 if (!Res.isUsable()) 13599 return Res; 13600 13601 // If a constant-expression is a reference to a variable where we delay 13602 // deciding whether it is an odr-use, just assume we will apply the 13603 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13604 // (a non-type template argument), we have special handling anyway. 13605 UpdateMarkingForLValueToRValue(Res.get()); 13606 return Res; 13607 } 13608 13609 void Sema::CleanupVarDeclMarking() { 13610 for (Expr *E : MaybeODRUseExprs) { 13611 VarDecl *Var; 13612 SourceLocation Loc; 13613 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13614 Var = cast<VarDecl>(DRE->getDecl()); 13615 Loc = DRE->getLocation(); 13616 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13617 Var = cast<VarDecl>(ME->getMemberDecl()); 13618 Loc = ME->getMemberLoc(); 13619 } else { 13620 llvm_unreachable("Unexpected expression"); 13621 } 13622 13623 MarkVarDeclODRUsed(Var, Loc, *this, 13624 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13625 } 13626 13627 MaybeODRUseExprs.clear(); 13628 } 13629 13630 13631 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13632 VarDecl *Var, Expr *E) { 13633 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13634 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13635 Var->setReferenced(); 13636 13637 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13638 bool MarkODRUsed = true; 13639 13640 // If the context is not potentially evaluated, this is not an odr-use and 13641 // does not trigger instantiation. 13642 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13643 if (SemaRef.isUnevaluatedContext()) 13644 return; 13645 13646 // If we don't yet know whether this context is going to end up being an 13647 // evaluated context, and we're referencing a variable from an enclosing 13648 // scope, add a potential capture. 13649 // 13650 // FIXME: Is this necessary? These contexts are only used for default 13651 // arguments, where local variables can't be used. 13652 const bool RefersToEnclosingScope = 13653 (SemaRef.CurContext != Var->getDeclContext() && 13654 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13655 if (RefersToEnclosingScope) { 13656 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13657 // If a variable could potentially be odr-used, defer marking it so 13658 // until we finish analyzing the full expression for any 13659 // lvalue-to-rvalue 13660 // or discarded value conversions that would obviate odr-use. 13661 // Add it to the list of potential captures that will be analyzed 13662 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13663 // unless the variable is a reference that was initialized by a constant 13664 // expression (this will never need to be captured or odr-used). 13665 assert(E && "Capture variable should be used in an expression."); 13666 if (!Var->getType()->isReferenceType() || 13667 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13668 LSI->addPotentialCapture(E->IgnoreParens()); 13669 } 13670 } 13671 13672 if (!isTemplateInstantiation(TSK)) 13673 return; 13674 13675 // Instantiate, but do not mark as odr-used, variable templates. 13676 MarkODRUsed = false; 13677 } 13678 13679 VarTemplateSpecializationDecl *VarSpec = 13680 dyn_cast<VarTemplateSpecializationDecl>(Var); 13681 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13682 "Can't instantiate a partial template specialization."); 13683 13684 // Perform implicit instantiation of static data members, static data member 13685 // templates of class templates, and variable template specializations. Delay 13686 // instantiations of variable templates, except for those that could be used 13687 // in a constant expression. 13688 if (isTemplateInstantiation(TSK)) { 13689 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13690 13691 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13692 if (Var->getPointOfInstantiation().isInvalid()) { 13693 // This is a modification of an existing AST node. Notify listeners. 13694 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13695 L->StaticDataMemberInstantiated(Var); 13696 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13697 // Don't bother trying to instantiate it again, unless we might need 13698 // its initializer before we get to the end of the TU. 13699 TryInstantiating = false; 13700 } 13701 13702 if (Var->getPointOfInstantiation().isInvalid()) 13703 Var->setTemplateSpecializationKind(TSK, Loc); 13704 13705 if (TryInstantiating) { 13706 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13707 bool InstantiationDependent = false; 13708 bool IsNonDependent = 13709 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13710 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13711 : true; 13712 13713 // Do not instantiate specializations that are still type-dependent. 13714 if (IsNonDependent) { 13715 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13716 // Do not defer instantiations of variables which could be used in a 13717 // constant expression. 13718 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13719 } else { 13720 SemaRef.PendingInstantiations 13721 .push_back(std::make_pair(Var, PointOfInstantiation)); 13722 } 13723 } 13724 } 13725 } 13726 13727 if(!MarkODRUsed) return; 13728 13729 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13730 // the requirements for appearing in a constant expression (5.19) and, if 13731 // it is an object, the lvalue-to-rvalue conversion (4.1) 13732 // is immediately applied." We check the first part here, and 13733 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13734 // Note that we use the C++11 definition everywhere because nothing in 13735 // C++03 depends on whether we get the C++03 version correct. The second 13736 // part does not apply to references, since they are not objects. 13737 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13738 // A reference initialized by a constant expression can never be 13739 // odr-used, so simply ignore it. 13740 if (!Var->getType()->isReferenceType()) 13741 SemaRef.MaybeODRUseExprs.insert(E); 13742 } else 13743 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13744 /*MaxFunctionScopeIndex ptr*/ nullptr); 13745 } 13746 13747 /// \brief Mark a variable referenced, and check whether it is odr-used 13748 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13749 /// used directly for normal expressions referring to VarDecl. 13750 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13751 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13752 } 13753 13754 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13755 Decl *D, Expr *E, bool OdrUse) { 13756 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13757 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13758 return; 13759 } 13760 13761 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13762 13763 // If this is a call to a method via a cast, also mark the method in the 13764 // derived class used in case codegen can devirtualize the call. 13765 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13766 if (!ME) 13767 return; 13768 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13769 if (!MD) 13770 return; 13771 // Only attempt to devirtualize if this is truly a virtual call. 13772 bool IsVirtualCall = MD->isVirtual() && 13773 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13774 if (!IsVirtualCall) 13775 return; 13776 const Expr *Base = ME->getBase(); 13777 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13778 if (!MostDerivedClassDecl) 13779 return; 13780 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13781 if (!DM || DM->isPure()) 13782 return; 13783 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13784 } 13785 13786 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13787 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13788 // TODO: update this with DR# once a defect report is filed. 13789 // C++11 defect. The address of a pure member should not be an ODR use, even 13790 // if it's a qualified reference. 13791 bool OdrUse = true; 13792 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13793 if (Method->isVirtual()) 13794 OdrUse = false; 13795 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13796 } 13797 13798 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13799 void Sema::MarkMemberReferenced(MemberExpr *E) { 13800 // C++11 [basic.def.odr]p2: 13801 // A non-overloaded function whose name appears as a potentially-evaluated 13802 // expression or a member of a set of candidate functions, if selected by 13803 // overload resolution when referred to from a potentially-evaluated 13804 // expression, is odr-used, unless it is a pure virtual function and its 13805 // name is not explicitly qualified. 13806 bool OdrUse = true; 13807 if (E->performsVirtualDispatch(getLangOpts())) { 13808 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13809 if (Method->isPure()) 13810 OdrUse = false; 13811 } 13812 SourceLocation Loc = E->getMemberLoc().isValid() ? 13813 E->getMemberLoc() : E->getLocStart(); 13814 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13815 } 13816 13817 /// \brief Perform marking for a reference to an arbitrary declaration. It 13818 /// marks the declaration referenced, and performs odr-use checking for 13819 /// functions and variables. This method should not be used when building a 13820 /// normal expression which refers to a variable. 13821 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13822 if (OdrUse) { 13823 if (auto *VD = dyn_cast<VarDecl>(D)) { 13824 MarkVariableReferenced(Loc, VD); 13825 return; 13826 } 13827 } 13828 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13829 MarkFunctionReferenced(Loc, FD, OdrUse); 13830 return; 13831 } 13832 D->setReferenced(); 13833 } 13834 13835 namespace { 13836 // Mark all of the declarations referenced 13837 // FIXME: Not fully implemented yet! We need to have a better understanding 13838 // of when we're entering 13839 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13840 Sema &S; 13841 SourceLocation Loc; 13842 13843 public: 13844 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13845 13846 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13847 13848 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13849 bool TraverseRecordType(RecordType *T); 13850 }; 13851 } 13852 13853 bool MarkReferencedDecls::TraverseTemplateArgument( 13854 const TemplateArgument &Arg) { 13855 if (Arg.getKind() == TemplateArgument::Declaration) { 13856 if (Decl *D = Arg.getAsDecl()) 13857 S.MarkAnyDeclReferenced(Loc, D, true); 13858 } 13859 13860 return Inherited::TraverseTemplateArgument(Arg); 13861 } 13862 13863 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13864 if (ClassTemplateSpecializationDecl *Spec 13865 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13866 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13867 return TraverseTemplateArguments(Args.data(), Args.size()); 13868 } 13869 13870 return true; 13871 } 13872 13873 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13874 MarkReferencedDecls Marker(*this, Loc); 13875 Marker.TraverseType(Context.getCanonicalType(T)); 13876 } 13877 13878 namespace { 13879 /// \brief Helper class that marks all of the declarations referenced by 13880 /// potentially-evaluated subexpressions as "referenced". 13881 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13882 Sema &S; 13883 bool SkipLocalVariables; 13884 13885 public: 13886 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13887 13888 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13889 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13890 13891 void VisitDeclRefExpr(DeclRefExpr *E) { 13892 // If we were asked not to visit local variables, don't. 13893 if (SkipLocalVariables) { 13894 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13895 if (VD->hasLocalStorage()) 13896 return; 13897 } 13898 13899 S.MarkDeclRefReferenced(E); 13900 } 13901 13902 void VisitMemberExpr(MemberExpr *E) { 13903 S.MarkMemberReferenced(E); 13904 Inherited::VisitMemberExpr(E); 13905 } 13906 13907 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13908 S.MarkFunctionReferenced(E->getLocStart(), 13909 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13910 Visit(E->getSubExpr()); 13911 } 13912 13913 void VisitCXXNewExpr(CXXNewExpr *E) { 13914 if (E->getOperatorNew()) 13915 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13916 if (E->getOperatorDelete()) 13917 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13918 Inherited::VisitCXXNewExpr(E); 13919 } 13920 13921 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13922 if (E->getOperatorDelete()) 13923 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13924 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13925 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13926 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13927 S.MarkFunctionReferenced(E->getLocStart(), 13928 S.LookupDestructor(Record)); 13929 } 13930 13931 Inherited::VisitCXXDeleteExpr(E); 13932 } 13933 13934 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13935 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13936 Inherited::VisitCXXConstructExpr(E); 13937 } 13938 13939 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13940 Visit(E->getExpr()); 13941 } 13942 13943 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13944 Inherited::VisitImplicitCastExpr(E); 13945 13946 if (E->getCastKind() == CK_LValueToRValue) 13947 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13948 } 13949 }; 13950 } 13951 13952 /// \brief Mark any declarations that appear within this expression or any 13953 /// potentially-evaluated subexpressions as "referenced". 13954 /// 13955 /// \param SkipLocalVariables If true, don't mark local variables as 13956 /// 'referenced'. 13957 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13958 bool SkipLocalVariables) { 13959 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13960 } 13961 13962 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 13963 /// of the program being compiled. 13964 /// 13965 /// This routine emits the given diagnostic when the code currently being 13966 /// type-checked is "potentially evaluated", meaning that there is a 13967 /// possibility that the code will actually be executable. Code in sizeof() 13968 /// expressions, code used only during overload resolution, etc., are not 13969 /// potentially evaluated. This routine will suppress such diagnostics or, 13970 /// in the absolutely nutty case of potentially potentially evaluated 13971 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 13972 /// later. 13973 /// 13974 /// This routine should be used for all diagnostics that describe the run-time 13975 /// behavior of a program, such as passing a non-POD value through an ellipsis. 13976 /// Failure to do so will likely result in spurious diagnostics or failures 13977 /// during overload resolution or within sizeof/alignof/typeof/typeid. 13978 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 13979 const PartialDiagnostic &PD) { 13980 switch (ExprEvalContexts.back().Context) { 13981 case Unevaluated: 13982 case UnevaluatedAbstract: 13983 // The argument will never be evaluated, so don't complain. 13984 break; 13985 13986 case ConstantEvaluated: 13987 // Relevant diagnostics should be produced by constant evaluation. 13988 break; 13989 13990 case PotentiallyEvaluated: 13991 case PotentiallyEvaluatedIfUsed: 13992 if (Statement && getCurFunctionOrMethodDecl()) { 13993 FunctionScopes.back()->PossiblyUnreachableDiags. 13994 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 13995 } 13996 else 13997 Diag(Loc, PD); 13998 13999 return true; 14000 } 14001 14002 return false; 14003 } 14004 14005 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14006 CallExpr *CE, FunctionDecl *FD) { 14007 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14008 return false; 14009 14010 // If we're inside a decltype's expression, don't check for a valid return 14011 // type or construct temporaries until we know whether this is the last call. 14012 if (ExprEvalContexts.back().IsDecltype) { 14013 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14014 return false; 14015 } 14016 14017 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14018 FunctionDecl *FD; 14019 CallExpr *CE; 14020 14021 public: 14022 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14023 : FD(FD), CE(CE) { } 14024 14025 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14026 if (!FD) { 14027 S.Diag(Loc, diag::err_call_incomplete_return) 14028 << T << CE->getSourceRange(); 14029 return; 14030 } 14031 14032 S.Diag(Loc, diag::err_call_function_incomplete_return) 14033 << CE->getSourceRange() << FD->getDeclName() << T; 14034 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14035 << FD->getDeclName(); 14036 } 14037 } Diagnoser(FD, CE); 14038 14039 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14040 return true; 14041 14042 return false; 14043 } 14044 14045 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14046 // will prevent this condition from triggering, which is what we want. 14047 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14048 SourceLocation Loc; 14049 14050 unsigned diagnostic = diag::warn_condition_is_assignment; 14051 bool IsOrAssign = false; 14052 14053 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14054 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14055 return; 14056 14057 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14058 14059 // Greylist some idioms by putting them into a warning subcategory. 14060 if (ObjCMessageExpr *ME 14061 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14062 Selector Sel = ME->getSelector(); 14063 14064 // self = [<foo> init...] 14065 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14066 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14067 14068 // <foo> = [<bar> nextObject] 14069 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14070 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14071 } 14072 14073 Loc = Op->getOperatorLoc(); 14074 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14075 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14076 return; 14077 14078 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14079 Loc = Op->getOperatorLoc(); 14080 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14081 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14082 else { 14083 // Not an assignment. 14084 return; 14085 } 14086 14087 Diag(Loc, diagnostic) << E->getSourceRange(); 14088 14089 SourceLocation Open = E->getLocStart(); 14090 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14091 Diag(Loc, diag::note_condition_assign_silence) 14092 << FixItHint::CreateInsertion(Open, "(") 14093 << FixItHint::CreateInsertion(Close, ")"); 14094 14095 if (IsOrAssign) 14096 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14097 << FixItHint::CreateReplacement(Loc, "!="); 14098 else 14099 Diag(Loc, diag::note_condition_assign_to_comparison) 14100 << FixItHint::CreateReplacement(Loc, "=="); 14101 } 14102 14103 /// \brief Redundant parentheses over an equality comparison can indicate 14104 /// that the user intended an assignment used as condition. 14105 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14106 // Don't warn if the parens came from a macro. 14107 SourceLocation parenLoc = ParenE->getLocStart(); 14108 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14109 return; 14110 // Don't warn for dependent expressions. 14111 if (ParenE->isTypeDependent()) 14112 return; 14113 14114 Expr *E = ParenE->IgnoreParens(); 14115 14116 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14117 if (opE->getOpcode() == BO_EQ && 14118 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14119 == Expr::MLV_Valid) { 14120 SourceLocation Loc = opE->getOperatorLoc(); 14121 14122 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14123 SourceRange ParenERange = ParenE->getSourceRange(); 14124 Diag(Loc, diag::note_equality_comparison_silence) 14125 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14126 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14127 Diag(Loc, diag::note_equality_comparison_to_assign) 14128 << FixItHint::CreateReplacement(Loc, "="); 14129 } 14130 } 14131 14132 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 14133 DiagnoseAssignmentAsCondition(E); 14134 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14135 DiagnoseEqualityWithExtraParens(parenE); 14136 14137 ExprResult result = CheckPlaceholderExpr(E); 14138 if (result.isInvalid()) return ExprError(); 14139 E = result.get(); 14140 14141 if (!E->isTypeDependent()) { 14142 if (getLangOpts().CPlusPlus) 14143 return CheckCXXBooleanCondition(E); // C++ 6.4p4 14144 14145 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14146 if (ERes.isInvalid()) 14147 return ExprError(); 14148 E = ERes.get(); 14149 14150 QualType T = E->getType(); 14151 if (!T->isScalarType()) { // C99 6.8.4.1p1 14152 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14153 << T << E->getSourceRange(); 14154 return ExprError(); 14155 } 14156 CheckBoolLikeConversion(E, Loc); 14157 } 14158 14159 return E; 14160 } 14161 14162 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 14163 Expr *SubExpr) { 14164 if (!SubExpr) 14165 return ExprError(); 14166 14167 return CheckBooleanCondition(SubExpr, Loc); 14168 } 14169 14170 namespace { 14171 /// A visitor for rebuilding a call to an __unknown_any expression 14172 /// to have an appropriate type. 14173 struct RebuildUnknownAnyFunction 14174 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14175 14176 Sema &S; 14177 14178 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14179 14180 ExprResult VisitStmt(Stmt *S) { 14181 llvm_unreachable("unexpected statement!"); 14182 } 14183 14184 ExprResult VisitExpr(Expr *E) { 14185 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14186 << E->getSourceRange(); 14187 return ExprError(); 14188 } 14189 14190 /// Rebuild an expression which simply semantically wraps another 14191 /// expression which it shares the type and value kind of. 14192 template <class T> ExprResult rebuildSugarExpr(T *E) { 14193 ExprResult SubResult = Visit(E->getSubExpr()); 14194 if (SubResult.isInvalid()) return ExprError(); 14195 14196 Expr *SubExpr = SubResult.get(); 14197 E->setSubExpr(SubExpr); 14198 E->setType(SubExpr->getType()); 14199 E->setValueKind(SubExpr->getValueKind()); 14200 assert(E->getObjectKind() == OK_Ordinary); 14201 return E; 14202 } 14203 14204 ExprResult VisitParenExpr(ParenExpr *E) { 14205 return rebuildSugarExpr(E); 14206 } 14207 14208 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14209 return rebuildSugarExpr(E); 14210 } 14211 14212 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14213 ExprResult SubResult = Visit(E->getSubExpr()); 14214 if (SubResult.isInvalid()) return ExprError(); 14215 14216 Expr *SubExpr = SubResult.get(); 14217 E->setSubExpr(SubExpr); 14218 E->setType(S.Context.getPointerType(SubExpr->getType())); 14219 assert(E->getValueKind() == VK_RValue); 14220 assert(E->getObjectKind() == OK_Ordinary); 14221 return E; 14222 } 14223 14224 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14225 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14226 14227 E->setType(VD->getType()); 14228 14229 assert(E->getValueKind() == VK_RValue); 14230 if (S.getLangOpts().CPlusPlus && 14231 !(isa<CXXMethodDecl>(VD) && 14232 cast<CXXMethodDecl>(VD)->isInstance())) 14233 E->setValueKind(VK_LValue); 14234 14235 return E; 14236 } 14237 14238 ExprResult VisitMemberExpr(MemberExpr *E) { 14239 return resolveDecl(E, E->getMemberDecl()); 14240 } 14241 14242 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14243 return resolveDecl(E, E->getDecl()); 14244 } 14245 }; 14246 } 14247 14248 /// Given a function expression of unknown-any type, try to rebuild it 14249 /// to have a function type. 14250 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14251 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14252 if (Result.isInvalid()) return ExprError(); 14253 return S.DefaultFunctionArrayConversion(Result.get()); 14254 } 14255 14256 namespace { 14257 /// A visitor for rebuilding an expression of type __unknown_anytype 14258 /// into one which resolves the type directly on the referring 14259 /// expression. Strict preservation of the original source 14260 /// structure is not a goal. 14261 struct RebuildUnknownAnyExpr 14262 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14263 14264 Sema &S; 14265 14266 /// The current destination type. 14267 QualType DestType; 14268 14269 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14270 : S(S), DestType(CastType) {} 14271 14272 ExprResult VisitStmt(Stmt *S) { 14273 llvm_unreachable("unexpected statement!"); 14274 } 14275 14276 ExprResult VisitExpr(Expr *E) { 14277 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14278 << E->getSourceRange(); 14279 return ExprError(); 14280 } 14281 14282 ExprResult VisitCallExpr(CallExpr *E); 14283 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14284 14285 /// Rebuild an expression which simply semantically wraps another 14286 /// expression which it shares the type and value kind of. 14287 template <class T> ExprResult rebuildSugarExpr(T *E) { 14288 ExprResult SubResult = Visit(E->getSubExpr()); 14289 if (SubResult.isInvalid()) return ExprError(); 14290 Expr *SubExpr = SubResult.get(); 14291 E->setSubExpr(SubExpr); 14292 E->setType(SubExpr->getType()); 14293 E->setValueKind(SubExpr->getValueKind()); 14294 assert(E->getObjectKind() == OK_Ordinary); 14295 return E; 14296 } 14297 14298 ExprResult VisitParenExpr(ParenExpr *E) { 14299 return rebuildSugarExpr(E); 14300 } 14301 14302 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14303 return rebuildSugarExpr(E); 14304 } 14305 14306 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14307 const PointerType *Ptr = DestType->getAs<PointerType>(); 14308 if (!Ptr) { 14309 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14310 << E->getSourceRange(); 14311 return ExprError(); 14312 } 14313 assert(E->getValueKind() == VK_RValue); 14314 assert(E->getObjectKind() == OK_Ordinary); 14315 E->setType(DestType); 14316 14317 // Build the sub-expression as if it were an object of the pointee type. 14318 DestType = Ptr->getPointeeType(); 14319 ExprResult SubResult = Visit(E->getSubExpr()); 14320 if (SubResult.isInvalid()) return ExprError(); 14321 E->setSubExpr(SubResult.get()); 14322 return E; 14323 } 14324 14325 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14326 14327 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14328 14329 ExprResult VisitMemberExpr(MemberExpr *E) { 14330 return resolveDecl(E, E->getMemberDecl()); 14331 } 14332 14333 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14334 return resolveDecl(E, E->getDecl()); 14335 } 14336 }; 14337 } 14338 14339 /// Rebuilds a call expression which yielded __unknown_anytype. 14340 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14341 Expr *CalleeExpr = E->getCallee(); 14342 14343 enum FnKind { 14344 FK_MemberFunction, 14345 FK_FunctionPointer, 14346 FK_BlockPointer 14347 }; 14348 14349 FnKind Kind; 14350 QualType CalleeType = CalleeExpr->getType(); 14351 if (CalleeType == S.Context.BoundMemberTy) { 14352 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14353 Kind = FK_MemberFunction; 14354 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14355 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14356 CalleeType = Ptr->getPointeeType(); 14357 Kind = FK_FunctionPointer; 14358 } else { 14359 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14360 Kind = FK_BlockPointer; 14361 } 14362 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14363 14364 // Verify that this is a legal result type of a function. 14365 if (DestType->isArrayType() || DestType->isFunctionType()) { 14366 unsigned diagID = diag::err_func_returning_array_function; 14367 if (Kind == FK_BlockPointer) 14368 diagID = diag::err_block_returning_array_function; 14369 14370 S.Diag(E->getExprLoc(), diagID) 14371 << DestType->isFunctionType() << DestType; 14372 return ExprError(); 14373 } 14374 14375 // Otherwise, go ahead and set DestType as the call's result. 14376 E->setType(DestType.getNonLValueExprType(S.Context)); 14377 E->setValueKind(Expr::getValueKindForType(DestType)); 14378 assert(E->getObjectKind() == OK_Ordinary); 14379 14380 // Rebuild the function type, replacing the result type with DestType. 14381 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14382 if (Proto) { 14383 // __unknown_anytype(...) is a special case used by the debugger when 14384 // it has no idea what a function's signature is. 14385 // 14386 // We want to build this call essentially under the K&R 14387 // unprototyped rules, but making a FunctionNoProtoType in C++ 14388 // would foul up all sorts of assumptions. However, we cannot 14389 // simply pass all arguments as variadic arguments, nor can we 14390 // portably just call the function under a non-variadic type; see 14391 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14392 // However, it turns out that in practice it is generally safe to 14393 // call a function declared as "A foo(B,C,D);" under the prototype 14394 // "A foo(B,C,D,...);". The only known exception is with the 14395 // Windows ABI, where any variadic function is implicitly cdecl 14396 // regardless of its normal CC. Therefore we change the parameter 14397 // types to match the types of the arguments. 14398 // 14399 // This is a hack, but it is far superior to moving the 14400 // corresponding target-specific code from IR-gen to Sema/AST. 14401 14402 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14403 SmallVector<QualType, 8> ArgTypes; 14404 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14405 ArgTypes.reserve(E->getNumArgs()); 14406 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14407 Expr *Arg = E->getArg(i); 14408 QualType ArgType = Arg->getType(); 14409 if (E->isLValue()) { 14410 ArgType = S.Context.getLValueReferenceType(ArgType); 14411 } else if (E->isXValue()) { 14412 ArgType = S.Context.getRValueReferenceType(ArgType); 14413 } 14414 ArgTypes.push_back(ArgType); 14415 } 14416 ParamTypes = ArgTypes; 14417 } 14418 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14419 Proto->getExtProtoInfo()); 14420 } else { 14421 DestType = S.Context.getFunctionNoProtoType(DestType, 14422 FnType->getExtInfo()); 14423 } 14424 14425 // Rebuild the appropriate pointer-to-function type. 14426 switch (Kind) { 14427 case FK_MemberFunction: 14428 // Nothing to do. 14429 break; 14430 14431 case FK_FunctionPointer: 14432 DestType = S.Context.getPointerType(DestType); 14433 break; 14434 14435 case FK_BlockPointer: 14436 DestType = S.Context.getBlockPointerType(DestType); 14437 break; 14438 } 14439 14440 // Finally, we can recurse. 14441 ExprResult CalleeResult = Visit(CalleeExpr); 14442 if (!CalleeResult.isUsable()) return ExprError(); 14443 E->setCallee(CalleeResult.get()); 14444 14445 // Bind a temporary if necessary. 14446 return S.MaybeBindToTemporary(E); 14447 } 14448 14449 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14450 // Verify that this is a legal result type of a call. 14451 if (DestType->isArrayType() || DestType->isFunctionType()) { 14452 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14453 << DestType->isFunctionType() << DestType; 14454 return ExprError(); 14455 } 14456 14457 // Rewrite the method result type if available. 14458 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14459 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14460 Method->setReturnType(DestType); 14461 } 14462 14463 // Change the type of the message. 14464 E->setType(DestType.getNonReferenceType()); 14465 E->setValueKind(Expr::getValueKindForType(DestType)); 14466 14467 return S.MaybeBindToTemporary(E); 14468 } 14469 14470 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14471 // The only case we should ever see here is a function-to-pointer decay. 14472 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14473 assert(E->getValueKind() == VK_RValue); 14474 assert(E->getObjectKind() == OK_Ordinary); 14475 14476 E->setType(DestType); 14477 14478 // Rebuild the sub-expression as the pointee (function) type. 14479 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14480 14481 ExprResult Result = Visit(E->getSubExpr()); 14482 if (!Result.isUsable()) return ExprError(); 14483 14484 E->setSubExpr(Result.get()); 14485 return E; 14486 } else if (E->getCastKind() == CK_LValueToRValue) { 14487 assert(E->getValueKind() == VK_RValue); 14488 assert(E->getObjectKind() == OK_Ordinary); 14489 14490 assert(isa<BlockPointerType>(E->getType())); 14491 14492 E->setType(DestType); 14493 14494 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14495 DestType = S.Context.getLValueReferenceType(DestType); 14496 14497 ExprResult Result = Visit(E->getSubExpr()); 14498 if (!Result.isUsable()) return ExprError(); 14499 14500 E->setSubExpr(Result.get()); 14501 return E; 14502 } else { 14503 llvm_unreachable("Unhandled cast type!"); 14504 } 14505 } 14506 14507 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14508 ExprValueKind ValueKind = VK_LValue; 14509 QualType Type = DestType; 14510 14511 // We know how to make this work for certain kinds of decls: 14512 14513 // - functions 14514 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14515 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14516 DestType = Ptr->getPointeeType(); 14517 ExprResult Result = resolveDecl(E, VD); 14518 if (Result.isInvalid()) return ExprError(); 14519 return S.ImpCastExprToType(Result.get(), Type, 14520 CK_FunctionToPointerDecay, VK_RValue); 14521 } 14522 14523 if (!Type->isFunctionType()) { 14524 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14525 << VD << E->getSourceRange(); 14526 return ExprError(); 14527 } 14528 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14529 // We must match the FunctionDecl's type to the hack introduced in 14530 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14531 // type. See the lengthy commentary in that routine. 14532 QualType FDT = FD->getType(); 14533 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14534 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14535 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14536 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14537 SourceLocation Loc = FD->getLocation(); 14538 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14539 FD->getDeclContext(), 14540 Loc, Loc, FD->getNameInfo().getName(), 14541 DestType, FD->getTypeSourceInfo(), 14542 SC_None, false/*isInlineSpecified*/, 14543 FD->hasPrototype(), 14544 false/*isConstexprSpecified*/); 14545 14546 if (FD->getQualifier()) 14547 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14548 14549 SmallVector<ParmVarDecl*, 16> Params; 14550 for (const auto &AI : FT->param_types()) { 14551 ParmVarDecl *Param = 14552 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14553 Param->setScopeInfo(0, Params.size()); 14554 Params.push_back(Param); 14555 } 14556 NewFD->setParams(Params); 14557 DRE->setDecl(NewFD); 14558 VD = DRE->getDecl(); 14559 } 14560 } 14561 14562 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14563 if (MD->isInstance()) { 14564 ValueKind = VK_RValue; 14565 Type = S.Context.BoundMemberTy; 14566 } 14567 14568 // Function references aren't l-values in C. 14569 if (!S.getLangOpts().CPlusPlus) 14570 ValueKind = VK_RValue; 14571 14572 // - variables 14573 } else if (isa<VarDecl>(VD)) { 14574 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14575 Type = RefTy->getPointeeType(); 14576 } else if (Type->isFunctionType()) { 14577 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14578 << VD << E->getSourceRange(); 14579 return ExprError(); 14580 } 14581 14582 // - nothing else 14583 } else { 14584 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14585 << VD << E->getSourceRange(); 14586 return ExprError(); 14587 } 14588 14589 // Modifying the declaration like this is friendly to IR-gen but 14590 // also really dangerous. 14591 VD->setType(DestType); 14592 E->setType(Type); 14593 E->setValueKind(ValueKind); 14594 return E; 14595 } 14596 14597 /// Check a cast of an unknown-any type. We intentionally only 14598 /// trigger this for C-style casts. 14599 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14600 Expr *CastExpr, CastKind &CastKind, 14601 ExprValueKind &VK, CXXCastPath &Path) { 14602 // The type we're casting to must be either void or complete. 14603 if (!CastType->isVoidType() && 14604 RequireCompleteType(TypeRange.getBegin(), CastType, 14605 diag::err_typecheck_cast_to_incomplete)) 14606 return ExprError(); 14607 14608 // Rewrite the casted expression from scratch. 14609 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14610 if (!result.isUsable()) return ExprError(); 14611 14612 CastExpr = result.get(); 14613 VK = CastExpr->getValueKind(); 14614 CastKind = CK_NoOp; 14615 14616 return CastExpr; 14617 } 14618 14619 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14620 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14621 } 14622 14623 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14624 Expr *arg, QualType ¶mType) { 14625 // If the syntactic form of the argument is not an explicit cast of 14626 // any sort, just do default argument promotion. 14627 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14628 if (!castArg) { 14629 ExprResult result = DefaultArgumentPromotion(arg); 14630 if (result.isInvalid()) return ExprError(); 14631 paramType = result.get()->getType(); 14632 return result; 14633 } 14634 14635 // Otherwise, use the type that was written in the explicit cast. 14636 assert(!arg->hasPlaceholderType()); 14637 paramType = castArg->getTypeAsWritten(); 14638 14639 // Copy-initialize a parameter of that type. 14640 InitializedEntity entity = 14641 InitializedEntity::InitializeParameter(Context, paramType, 14642 /*consumed*/ false); 14643 return PerformCopyInitialization(entity, callLoc, arg); 14644 } 14645 14646 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14647 Expr *orig = E; 14648 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14649 while (true) { 14650 E = E->IgnoreParenImpCasts(); 14651 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14652 E = call->getCallee(); 14653 diagID = diag::err_uncasted_call_of_unknown_any; 14654 } else { 14655 break; 14656 } 14657 } 14658 14659 SourceLocation loc; 14660 NamedDecl *d; 14661 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14662 loc = ref->getLocation(); 14663 d = ref->getDecl(); 14664 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14665 loc = mem->getMemberLoc(); 14666 d = mem->getMemberDecl(); 14667 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14668 diagID = diag::err_uncasted_call_of_unknown_any; 14669 loc = msg->getSelectorStartLoc(); 14670 d = msg->getMethodDecl(); 14671 if (!d) { 14672 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14673 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14674 << orig->getSourceRange(); 14675 return ExprError(); 14676 } 14677 } else { 14678 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14679 << E->getSourceRange(); 14680 return ExprError(); 14681 } 14682 14683 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14684 14685 // Never recoverable. 14686 return ExprError(); 14687 } 14688 14689 /// Check for operands with placeholder types and complain if found. 14690 /// Returns true if there was an error and no recovery was possible. 14691 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14692 if (!getLangOpts().CPlusPlus) { 14693 // C cannot handle TypoExpr nodes on either side of a binop because it 14694 // doesn't handle dependent types properly, so make sure any TypoExprs have 14695 // been dealt with before checking the operands. 14696 ExprResult Result = CorrectDelayedTyposInExpr(E); 14697 if (!Result.isUsable()) return ExprError(); 14698 E = Result.get(); 14699 } 14700 14701 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14702 if (!placeholderType) return E; 14703 14704 switch (placeholderType->getKind()) { 14705 14706 // Overloaded expressions. 14707 case BuiltinType::Overload: { 14708 // Try to resolve a single function template specialization. 14709 // This is obligatory. 14710 ExprResult result = E; 14711 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14712 return result; 14713 14714 // If that failed, try to recover with a call. 14715 } else { 14716 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14717 /*complain*/ true); 14718 return result; 14719 } 14720 } 14721 14722 // Bound member functions. 14723 case BuiltinType::BoundMember: { 14724 ExprResult result = E; 14725 const Expr *BME = E->IgnoreParens(); 14726 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14727 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14728 if (isa<CXXPseudoDestructorExpr>(BME)) { 14729 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14730 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14731 if (ME->getMemberNameInfo().getName().getNameKind() == 14732 DeclarationName::CXXDestructorName) 14733 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14734 } 14735 tryToRecoverWithCall(result, PD, 14736 /*complain*/ true); 14737 return result; 14738 } 14739 14740 // ARC unbridged casts. 14741 case BuiltinType::ARCUnbridgedCast: { 14742 Expr *realCast = stripARCUnbridgedCast(E); 14743 diagnoseARCUnbridgedCast(realCast); 14744 return realCast; 14745 } 14746 14747 // Expressions of unknown type. 14748 case BuiltinType::UnknownAny: 14749 return diagnoseUnknownAnyExpr(*this, E); 14750 14751 // Pseudo-objects. 14752 case BuiltinType::PseudoObject: 14753 return checkPseudoObjectRValue(E); 14754 14755 case BuiltinType::BuiltinFn: { 14756 // Accept __noop without parens by implicitly converting it to a call expr. 14757 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14758 if (DRE) { 14759 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14760 if (FD->getBuiltinID() == Builtin::BI__noop) { 14761 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14762 CK_BuiltinFnToFnPtr).get(); 14763 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14764 VK_RValue, SourceLocation()); 14765 } 14766 } 14767 14768 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14769 return ExprError(); 14770 } 14771 14772 // Expressions of unknown type. 14773 case BuiltinType::OMPArraySection: 14774 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14775 return ExprError(); 14776 14777 // Everything else should be impossible. 14778 #define BUILTIN_TYPE(Id, SingletonId) \ 14779 case BuiltinType::Id: 14780 #define PLACEHOLDER_TYPE(Id, SingletonId) 14781 #include "clang/AST/BuiltinTypes.def" 14782 break; 14783 } 14784 14785 llvm_unreachable("invalid placeholder type!"); 14786 } 14787 14788 bool Sema::CheckCaseExpression(Expr *E) { 14789 if (E->isTypeDependent()) 14790 return true; 14791 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14792 return E->getType()->isIntegralOrEnumerationType(); 14793 return false; 14794 } 14795 14796 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14797 ExprResult 14798 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14799 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14800 "Unknown Objective-C Boolean value!"); 14801 QualType BoolT = Context.ObjCBuiltinBoolTy; 14802 if (!Context.getBOOLDecl()) { 14803 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14804 Sema::LookupOrdinaryName); 14805 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14806 NamedDecl *ND = Result.getFoundDecl(); 14807 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14808 Context.setBOOLDecl(TD); 14809 } 14810 } 14811 if (Context.getBOOLDecl()) 14812 BoolT = Context.getBOOLType(); 14813 return new (Context) 14814 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14815 } 14816