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 "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.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, bool TreatUnavailableAsInvalid) { 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 (TreatUnavailableAsInvalid && 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 (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 83 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 84 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 85 if (DC && !DC->hasAttr<UnusedAttr>()) 86 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 87 } 88 } 89 } 90 91 /// \brief Emit a note explaining that this function is deleted. 92 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 93 assert(Decl->isDeleted()); 94 95 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 96 97 if (Method && Method->isDeleted() && Method->isDefaulted()) { 98 // If the method was explicitly defaulted, point at that declaration. 99 if (!Method->isImplicit()) 100 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 101 102 // Try to diagnose why this special member function was implicitly 103 // deleted. This might fail, if that reason no longer applies. 104 CXXSpecialMember CSM = getSpecialMember(Method); 105 if (CSM != CXXInvalid) 106 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 107 108 return; 109 } 110 111 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 112 if (Ctor && Ctor->isInheritingConstructor()) 113 return NoteDeletedInheritingConstructor(Ctor); 114 115 Diag(Decl->getLocation(), diag::note_availability_specified_here) 116 << Decl << true; 117 } 118 119 /// \brief Determine whether a FunctionDecl was ever declared with an 120 /// explicit storage class. 121 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 122 for (auto I : D->redecls()) { 123 if (I->getStorageClass() != SC_None) 124 return true; 125 } 126 return false; 127 } 128 129 /// \brief Check whether we're in an extern inline function and referring to a 130 /// variable or function with internal linkage (C11 6.7.4p3). 131 /// 132 /// This is only a warning because we used to silently accept this code, but 133 /// in many cases it will not behave correctly. This is not enabled in C++ mode 134 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 135 /// and so while there may still be user mistakes, most of the time we can't 136 /// prove that there are errors. 137 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 138 const NamedDecl *D, 139 SourceLocation Loc) { 140 // This is disabled under C++; there are too many ways for this to fire in 141 // contexts where the warning is a false positive, or where it is technically 142 // correct but benign. 143 if (S.getLangOpts().CPlusPlus) 144 return; 145 146 // Check if this is an inlined function or method. 147 FunctionDecl *Current = S.getCurFunctionDecl(); 148 if (!Current) 149 return; 150 if (!Current->isInlined()) 151 return; 152 if (!Current->isExternallyVisible()) 153 return; 154 155 // Check if the decl has internal linkage. 156 if (D->getFormalLinkage() != InternalLinkage) 157 return; 158 159 // Downgrade from ExtWarn to Extension if 160 // (1) the supposedly external inline function is in the main file, 161 // and probably won't be included anywhere else. 162 // (2) the thing we're referencing is a pure function. 163 // (3) the thing we're referencing is another inline function. 164 // This last can give us false negatives, but it's better than warning on 165 // wrappers for simple C library functions. 166 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 167 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 168 if (!DowngradeWarning && UsedFn) 169 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 170 171 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 172 : diag::ext_internal_in_extern_inline) 173 << /*IsVar=*/!UsedFn << D; 174 175 S.MaybeSuggestAddingStaticToDecl(Current); 176 177 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 178 << D; 179 } 180 181 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 182 const FunctionDecl *First = Cur->getFirstDecl(); 183 184 // Suggest "static" on the function, if possible. 185 if (!hasAnyExplicitStorageClass(First)) { 186 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 187 Diag(DeclBegin, diag::note_convert_inline_to_static) 188 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 189 } 190 } 191 192 /// \brief Determine whether the use of this declaration is valid, and 193 /// emit any corresponding diagnostics. 194 /// 195 /// This routine diagnoses various problems with referencing 196 /// declarations that can occur when using a declaration. For example, 197 /// it might warn if a deprecated or unavailable declaration is being 198 /// used, or produce an error (and return true) if a C++0x deleted 199 /// function is being used. 200 /// 201 /// \returns true if there was an error (this declaration cannot be 202 /// referenced), false otherwise. 203 /// 204 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 205 const ObjCInterfaceDecl *UnknownObjCClass, 206 bool ObjCPropertyAccess, 207 bool AvoidPartialAvailabilityChecks) { 208 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 209 // If there were any diagnostics suppressed by template argument deduction, 210 // emit them now. 211 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 212 if (Pos != SuppressedDiagnostics.end()) { 213 for (const PartialDiagnosticAt &Suppressed : Pos->second) 214 Diag(Suppressed.first, Suppressed.second); 215 216 // Clear out the list of suppressed diagnostics, so that we don't emit 217 // them again for this specialization. However, we don't obsolete this 218 // entry from the table, because we want to avoid ever emitting these 219 // diagnostics again. 220 Pos->second.clear(); 221 } 222 223 // C++ [basic.start.main]p3: 224 // The function 'main' shall not be used within a program. 225 if (cast<FunctionDecl>(D)->isMain()) 226 Diag(Loc, diag::ext_main_used); 227 } 228 229 // See if this is an auto-typed variable whose initializer we are parsing. 230 if (ParsingInitForAutoVars.count(D)) { 231 if (isa<BindingDecl>(D)) { 232 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 233 << D->getDeclName(); 234 } else { 235 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 236 << D->getDeclName() << cast<VarDecl>(D)->getType(); 237 } 238 return true; 239 } 240 241 // See if this is a deleted function. 242 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 243 if (FD->isDeleted()) { 244 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 245 if (Ctor && Ctor->isInheritingConstructor()) 246 Diag(Loc, diag::err_deleted_inherited_ctor_use) 247 << Ctor->getParent() 248 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 249 else 250 Diag(Loc, diag::err_deleted_function_use); 251 NoteDeletedFunction(FD); 252 return true; 253 } 254 255 // If the function has a deduced return type, and we can't deduce it, 256 // then we can't use it either. 257 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 258 DeduceReturnType(FD, Loc)) 259 return true; 260 261 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 262 return true; 263 } 264 265 auto getReferencedObjCProp = [](const NamedDecl *D) -> 266 const ObjCPropertyDecl * { 267 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 268 return MD->findPropertyDecl(); 269 return nullptr; 270 }; 271 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 272 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 273 return true; 274 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 275 return true; 276 } 277 278 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 279 // Only the variables omp_in and omp_out are allowed in the combiner. 280 // Only the variables omp_priv and omp_orig are allowed in the 281 // initializer-clause. 282 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 283 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 284 isa<VarDecl>(D)) { 285 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 286 << getCurFunction()->HasOMPDeclareReductionCombiner; 287 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 288 return true; 289 } 290 291 DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess, 292 AvoidPartialAvailabilityChecks); 293 294 DiagnoseUnusedOfDecl(*this, D, Loc); 295 296 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 297 298 return false; 299 } 300 301 /// \brief Retrieve the message suffix that should be added to a 302 /// diagnostic complaining about the given function being deleted or 303 /// unavailable. 304 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 305 std::string Message; 306 if (FD->getAvailability(&Message)) 307 return ": " + Message; 308 309 return std::string(); 310 } 311 312 /// DiagnoseSentinelCalls - This routine checks whether a call or 313 /// message-send is to a declaration with the sentinel attribute, and 314 /// if so, it checks that the requirements of the sentinel are 315 /// satisfied. 316 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 317 ArrayRef<Expr *> Args) { 318 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 319 if (!attr) 320 return; 321 322 // The number of formal parameters of the declaration. 323 unsigned numFormalParams; 324 325 // The kind of declaration. This is also an index into a %select in 326 // the diagnostic. 327 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 328 329 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 330 numFormalParams = MD->param_size(); 331 calleeType = CT_Method; 332 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 333 numFormalParams = FD->param_size(); 334 calleeType = CT_Function; 335 } else if (isa<VarDecl>(D)) { 336 QualType type = cast<ValueDecl>(D)->getType(); 337 const FunctionType *fn = nullptr; 338 if (const PointerType *ptr = type->getAs<PointerType>()) { 339 fn = ptr->getPointeeType()->getAs<FunctionType>(); 340 if (!fn) return; 341 calleeType = CT_Function; 342 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 343 fn = ptr->getPointeeType()->castAs<FunctionType>(); 344 calleeType = CT_Block; 345 } else { 346 return; 347 } 348 349 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 350 numFormalParams = proto->getNumParams(); 351 } else { 352 numFormalParams = 0; 353 } 354 } else { 355 return; 356 } 357 358 // "nullPos" is the number of formal parameters at the end which 359 // effectively count as part of the variadic arguments. This is 360 // useful if you would prefer to not have *any* formal parameters, 361 // but the language forces you to have at least one. 362 unsigned nullPos = attr->getNullPos(); 363 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 364 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 365 366 // The number of arguments which should follow the sentinel. 367 unsigned numArgsAfterSentinel = attr->getSentinel(); 368 369 // If there aren't enough arguments for all the formal parameters, 370 // the sentinel, and the args after the sentinel, complain. 371 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 372 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 373 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 374 return; 375 } 376 377 // Otherwise, find the sentinel expression. 378 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 379 if (!sentinelExpr) return; 380 if (sentinelExpr->isValueDependent()) return; 381 if (Context.isSentinelNullExpr(sentinelExpr)) return; 382 383 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 384 // or 'NULL' if those are actually defined in the context. Only use 385 // 'nil' for ObjC methods, where it's much more likely that the 386 // variadic arguments form a list of object pointers. 387 SourceLocation MissingNilLoc 388 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 389 std::string NullValue; 390 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 391 NullValue = "nil"; 392 else if (getLangOpts().CPlusPlus11) 393 NullValue = "nullptr"; 394 else if (PP.isMacroDefined("NULL")) 395 NullValue = "NULL"; 396 else 397 NullValue = "(void*) 0"; 398 399 if (MissingNilLoc.isInvalid()) 400 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 401 else 402 Diag(MissingNilLoc, diag::warn_missing_sentinel) 403 << int(calleeType) 404 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 405 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 406 } 407 408 SourceRange Sema::getExprRange(Expr *E) const { 409 return E ? E->getSourceRange() : SourceRange(); 410 } 411 412 //===----------------------------------------------------------------------===// 413 // Standard Promotions and Conversions 414 //===----------------------------------------------------------------------===// 415 416 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 417 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 418 // Handle any placeholder expressions which made it here. 419 if (E->getType()->isPlaceholderType()) { 420 ExprResult result = CheckPlaceholderExpr(E); 421 if (result.isInvalid()) return ExprError(); 422 E = result.get(); 423 } 424 425 QualType Ty = E->getType(); 426 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 427 428 if (Ty->isFunctionType()) { 429 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 430 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 431 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 432 return ExprError(); 433 434 E = ImpCastExprToType(E, Context.getPointerType(Ty), 435 CK_FunctionToPointerDecay).get(); 436 } else if (Ty->isArrayType()) { 437 // In C90 mode, arrays only promote to pointers if the array expression is 438 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 439 // type 'array of type' is converted to an expression that has type 'pointer 440 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 441 // that has type 'array of type' ...". The relevant change is "an lvalue" 442 // (C90) to "an expression" (C99). 443 // 444 // C++ 4.2p1: 445 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 446 // T" can be converted to an rvalue of type "pointer to T". 447 // 448 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 449 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 450 CK_ArrayToPointerDecay).get(); 451 } 452 return E; 453 } 454 455 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 456 // Check to see if we are dereferencing a null pointer. If so, 457 // and if not volatile-qualified, this is undefined behavior that the 458 // optimizer will delete, so warn about it. People sometimes try to use this 459 // to get a deterministic trap and are surprised by clang's behavior. This 460 // only handles the pattern "*null", which is a very syntactic check. 461 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 462 if (UO->getOpcode() == UO_Deref && 463 UO->getSubExpr()->IgnoreParenCasts()-> 464 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 465 !UO->getType().isVolatileQualified()) { 466 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 467 S.PDiag(diag::warn_indirection_through_null) 468 << UO->getSubExpr()->getSourceRange()); 469 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 470 S.PDiag(diag::note_indirection_through_null)); 471 } 472 } 473 474 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 475 SourceLocation AssignLoc, 476 const Expr* RHS) { 477 const ObjCIvarDecl *IV = OIRE->getDecl(); 478 if (!IV) 479 return; 480 481 DeclarationName MemberName = IV->getDeclName(); 482 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 483 if (!Member || !Member->isStr("isa")) 484 return; 485 486 const Expr *Base = OIRE->getBase(); 487 QualType BaseType = Base->getType(); 488 if (OIRE->isArrow()) 489 BaseType = BaseType->getPointeeType(); 490 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 491 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 492 ObjCInterfaceDecl *ClassDeclared = nullptr; 493 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 494 if (!ClassDeclared->getSuperClass() 495 && (*ClassDeclared->ivar_begin()) == IV) { 496 if (RHS) { 497 NamedDecl *ObjectSetClass = 498 S.LookupSingleName(S.TUScope, 499 &S.Context.Idents.get("object_setClass"), 500 SourceLocation(), S.LookupOrdinaryName); 501 if (ObjectSetClass) { 502 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 503 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 504 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 505 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 506 AssignLoc), ",") << 507 FixItHint::CreateInsertion(RHSLocEnd, ")"); 508 } 509 else 510 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 511 } else { 512 NamedDecl *ObjectGetClass = 513 S.LookupSingleName(S.TUScope, 514 &S.Context.Idents.get("object_getClass"), 515 SourceLocation(), S.LookupOrdinaryName); 516 if (ObjectGetClass) 517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 518 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 519 FixItHint::CreateReplacement( 520 SourceRange(OIRE->getOpLoc(), 521 OIRE->getLocEnd()), ")"); 522 else 523 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 524 } 525 S.Diag(IV->getLocation(), diag::note_ivar_decl); 526 } 527 } 528 } 529 530 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 531 // Handle any placeholder expressions which made it here. 532 if (E->getType()->isPlaceholderType()) { 533 ExprResult result = CheckPlaceholderExpr(E); 534 if (result.isInvalid()) return ExprError(); 535 E = result.get(); 536 } 537 538 // C++ [conv.lval]p1: 539 // A glvalue of a non-function, non-array type T can be 540 // converted to a prvalue. 541 if (!E->isGLValue()) return E; 542 543 QualType T = E->getType(); 544 assert(!T.isNull() && "r-value conversion on typeless expression?"); 545 546 // We don't want to throw lvalue-to-rvalue casts on top of 547 // expressions of certain types in C++. 548 if (getLangOpts().CPlusPlus && 549 (E->getType() == Context.OverloadTy || 550 T->isDependentType() || 551 T->isRecordType())) 552 return E; 553 554 // The C standard is actually really unclear on this point, and 555 // DR106 tells us what the result should be but not why. It's 556 // generally best to say that void types just doesn't undergo 557 // lvalue-to-rvalue at all. Note that expressions of unqualified 558 // 'void' type are never l-values, but qualified void can be. 559 if (T->isVoidType()) 560 return E; 561 562 // OpenCL usually rejects direct accesses to values of 'half' type. 563 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 564 T->isHalfType()) { 565 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 566 << 0 << T; 567 return ExprError(); 568 } 569 570 CheckForNullPointerDereference(*this, E); 571 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 572 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 573 &Context.Idents.get("object_getClass"), 574 SourceLocation(), LookupOrdinaryName); 575 if (ObjectGetClass) 576 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 577 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 578 FixItHint::CreateReplacement( 579 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 580 else 581 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 582 } 583 else if (const ObjCIvarRefExpr *OIRE = 584 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 585 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 586 587 // C++ [conv.lval]p1: 588 // [...] If T is a non-class type, the type of the prvalue is the 589 // cv-unqualified version of T. Otherwise, the type of the 590 // rvalue is T. 591 // 592 // C99 6.3.2.1p2: 593 // If the lvalue has qualified type, the value has the unqualified 594 // version of the type of the lvalue; otherwise, the value has the 595 // type of the lvalue. 596 if (T.hasQualifiers()) 597 T = T.getUnqualifiedType(); 598 599 // Under the MS ABI, lock down the inheritance model now. 600 if (T->isMemberPointerType() && 601 Context.getTargetInfo().getCXXABI().isMicrosoft()) 602 (void)isCompleteType(E->getExprLoc(), T); 603 604 UpdateMarkingForLValueToRValue(E); 605 606 // Loading a __weak object implicitly retains the value, so we need a cleanup to 607 // balance that. 608 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 609 Cleanup.setExprNeedsCleanups(true); 610 611 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 612 nullptr, VK_RValue); 613 614 // C11 6.3.2.1p2: 615 // ... if the lvalue has atomic type, the value has the non-atomic version 616 // of the type of the lvalue ... 617 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 618 T = Atomic->getValueType().getUnqualifiedType(); 619 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 620 nullptr, VK_RValue); 621 } 622 623 return Res; 624 } 625 626 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 627 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 628 if (Res.isInvalid()) 629 return ExprError(); 630 Res = DefaultLvalueConversion(Res.get()); 631 if (Res.isInvalid()) 632 return ExprError(); 633 return Res; 634 } 635 636 /// CallExprUnaryConversions - a special case of an unary conversion 637 /// performed on a function designator of a call expression. 638 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 639 QualType Ty = E->getType(); 640 ExprResult Res = E; 641 // Only do implicit cast for a function type, but not for a pointer 642 // to function type. 643 if (Ty->isFunctionType()) { 644 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 645 CK_FunctionToPointerDecay).get(); 646 if (Res.isInvalid()) 647 return ExprError(); 648 } 649 Res = DefaultLvalueConversion(Res.get()); 650 if (Res.isInvalid()) 651 return ExprError(); 652 return Res.get(); 653 } 654 655 /// UsualUnaryConversions - Performs various conversions that are common to most 656 /// operators (C99 6.3). The conversions of array and function types are 657 /// sometimes suppressed. For example, the array->pointer conversion doesn't 658 /// apply if the array is an argument to the sizeof or address (&) operators. 659 /// In these instances, this routine should *not* be called. 660 ExprResult Sema::UsualUnaryConversions(Expr *E) { 661 // First, convert to an r-value. 662 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 663 if (Res.isInvalid()) 664 return ExprError(); 665 E = Res.get(); 666 667 QualType Ty = E->getType(); 668 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 669 670 // Half FP have to be promoted to float unless it is natively supported 671 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 672 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 673 674 // Try to perform integral promotions if the object has a theoretically 675 // promotable type. 676 if (Ty->isIntegralOrUnscopedEnumerationType()) { 677 // C99 6.3.1.1p2: 678 // 679 // The following may be used in an expression wherever an int or 680 // unsigned int may be used: 681 // - an object or expression with an integer type whose integer 682 // conversion rank is less than or equal to the rank of int 683 // and unsigned int. 684 // - A bit-field of type _Bool, int, signed int, or unsigned int. 685 // 686 // If an int can represent all values of the original type, the 687 // value is converted to an int; otherwise, it is converted to an 688 // unsigned int. These are called the integer promotions. All 689 // other types are unchanged by the integer promotions. 690 691 QualType PTy = Context.isPromotableBitField(E); 692 if (!PTy.isNull()) { 693 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 694 return E; 695 } 696 if (Ty->isPromotableIntegerType()) { 697 QualType PT = Context.getPromotedIntegerType(Ty); 698 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 699 return E; 700 } 701 } 702 return E; 703 } 704 705 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 706 /// do not have a prototype. Arguments that have type float or __fp16 707 /// are promoted to double. All other argument types are converted by 708 /// UsualUnaryConversions(). 709 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 710 QualType Ty = E->getType(); 711 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 712 713 ExprResult Res = UsualUnaryConversions(E); 714 if (Res.isInvalid()) 715 return ExprError(); 716 E = Res.get(); 717 718 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 719 // promote to double. 720 // Note that default argument promotion applies only to float (and 721 // half/fp16); it does not apply to _Float16. 722 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 723 if (BTy && (BTy->getKind() == BuiltinType::Half || 724 BTy->getKind() == BuiltinType::Float)) { 725 if (getLangOpts().OpenCL && 726 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 727 if (BTy->getKind() == BuiltinType::Half) { 728 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 729 } 730 } else { 731 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 732 } 733 } 734 735 // C++ performs lvalue-to-rvalue conversion as a default argument 736 // promotion, even on class types, but note: 737 // C++11 [conv.lval]p2: 738 // When an lvalue-to-rvalue conversion occurs in an unevaluated 739 // operand or a subexpression thereof the value contained in the 740 // referenced object is not accessed. Otherwise, if the glvalue 741 // has a class type, the conversion copy-initializes a temporary 742 // of type T from the glvalue and the result of the conversion 743 // is a prvalue for the temporary. 744 // FIXME: add some way to gate this entire thing for correctness in 745 // potentially potentially evaluated contexts. 746 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 747 ExprResult Temp = PerformCopyInitialization( 748 InitializedEntity::InitializeTemporary(E->getType()), 749 E->getExprLoc(), E); 750 if (Temp.isInvalid()) 751 return ExprError(); 752 E = Temp.get(); 753 } 754 755 return E; 756 } 757 758 /// Determine the degree of POD-ness for an expression. 759 /// Incomplete types are considered POD, since this check can be performed 760 /// when we're in an unevaluated context. 761 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 762 if (Ty->isIncompleteType()) { 763 // C++11 [expr.call]p7: 764 // After these conversions, if the argument does not have arithmetic, 765 // enumeration, pointer, pointer to member, or class type, the program 766 // is ill-formed. 767 // 768 // Since we've already performed array-to-pointer and function-to-pointer 769 // decay, the only such type in C++ is cv void. This also handles 770 // initializer lists as variadic arguments. 771 if (Ty->isVoidType()) 772 return VAK_Invalid; 773 774 if (Ty->isObjCObjectType()) 775 return VAK_Invalid; 776 return VAK_Valid; 777 } 778 779 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 780 return VAK_Invalid; 781 782 if (Ty.isCXX98PODType(Context)) 783 return VAK_Valid; 784 785 // C++11 [expr.call]p7: 786 // Passing a potentially-evaluated argument of class type (Clause 9) 787 // having a non-trivial copy constructor, a non-trivial move constructor, 788 // or a non-trivial destructor, with no corresponding parameter, 789 // is conditionally-supported with implementation-defined semantics. 790 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 791 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 792 if (!Record->hasNonTrivialCopyConstructor() && 793 !Record->hasNonTrivialMoveConstructor() && 794 !Record->hasNonTrivialDestructor()) 795 return VAK_ValidInCXX11; 796 797 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 798 return VAK_Valid; 799 800 if (Ty->isObjCObjectType()) 801 return VAK_Invalid; 802 803 if (getLangOpts().MSVCCompat) 804 return VAK_MSVCUndefined; 805 806 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 807 // permitted to reject them. We should consider doing so. 808 return VAK_Undefined; 809 } 810 811 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 812 // Don't allow one to pass an Objective-C interface to a vararg. 813 const QualType &Ty = E->getType(); 814 VarArgKind VAK = isValidVarArgType(Ty); 815 816 // Complain about passing non-POD types through varargs. 817 switch (VAK) { 818 case VAK_ValidInCXX11: 819 DiagRuntimeBehavior( 820 E->getLocStart(), nullptr, 821 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 822 << Ty << CT); 823 LLVM_FALLTHROUGH; 824 case VAK_Valid: 825 if (Ty->isRecordType()) { 826 // This is unlikely to be what the user intended. If the class has a 827 // 'c_str' member function, the user probably meant to call that. 828 DiagRuntimeBehavior(E->getLocStart(), nullptr, 829 PDiag(diag::warn_pass_class_arg_to_vararg) 830 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 831 } 832 break; 833 834 case VAK_Undefined: 835 case VAK_MSVCUndefined: 836 DiagRuntimeBehavior( 837 E->getLocStart(), nullptr, 838 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 839 << getLangOpts().CPlusPlus11 << Ty << CT); 840 break; 841 842 case VAK_Invalid: 843 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 844 Diag(E->getLocStart(), 845 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT; 846 else if (Ty->isObjCObjectType()) 847 DiagRuntimeBehavior( 848 E->getLocStart(), nullptr, 849 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 850 << Ty << CT); 851 else 852 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 853 << isa<InitListExpr>(E) << Ty << CT; 854 break; 855 } 856 } 857 858 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 859 /// will create a trap if the resulting type is not a POD type. 860 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 861 FunctionDecl *FDecl) { 862 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 863 // Strip the unbridged-cast placeholder expression off, if applicable. 864 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 865 (CT == VariadicMethod || 866 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 867 E = stripARCUnbridgedCast(E); 868 869 // Otherwise, do normal placeholder checking. 870 } else { 871 ExprResult ExprRes = CheckPlaceholderExpr(E); 872 if (ExprRes.isInvalid()) 873 return ExprError(); 874 E = ExprRes.get(); 875 } 876 } 877 878 ExprResult ExprRes = DefaultArgumentPromotion(E); 879 if (ExprRes.isInvalid()) 880 return ExprError(); 881 E = ExprRes.get(); 882 883 // Diagnostics regarding non-POD argument types are 884 // emitted along with format string checking in Sema::CheckFunctionCall(). 885 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 886 // Turn this into a trap. 887 CXXScopeSpec SS; 888 SourceLocation TemplateKWLoc; 889 UnqualifiedId Name; 890 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 891 E->getLocStart()); 892 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 893 Name, true, false); 894 if (TrapFn.isInvalid()) 895 return ExprError(); 896 897 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 898 E->getLocStart(), None, 899 E->getLocEnd()); 900 if (Call.isInvalid()) 901 return ExprError(); 902 903 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 904 Call.get(), E); 905 if (Comma.isInvalid()) 906 return ExprError(); 907 return Comma.get(); 908 } 909 910 if (!getLangOpts().CPlusPlus && 911 RequireCompleteType(E->getExprLoc(), E->getType(), 912 diag::err_call_incomplete_argument)) 913 return ExprError(); 914 915 return E; 916 } 917 918 /// \brief Converts an integer to complex float type. Helper function of 919 /// UsualArithmeticConversions() 920 /// 921 /// \return false if the integer expression is an integer type and is 922 /// successfully converted to the complex type. 923 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 924 ExprResult &ComplexExpr, 925 QualType IntTy, 926 QualType ComplexTy, 927 bool SkipCast) { 928 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 929 if (SkipCast) return false; 930 if (IntTy->isIntegerType()) { 931 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 932 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 933 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 934 CK_FloatingRealToComplex); 935 } else { 936 assert(IntTy->isComplexIntegerType()); 937 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 938 CK_IntegralComplexToFloatingComplex); 939 } 940 return false; 941 } 942 943 /// \brief Handle arithmetic conversion with complex types. Helper function of 944 /// UsualArithmeticConversions() 945 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 946 ExprResult &RHS, QualType LHSType, 947 QualType RHSType, 948 bool IsCompAssign) { 949 // if we have an integer operand, the result is the complex type. 950 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 951 /*skipCast*/false)) 952 return LHSType; 953 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 954 /*skipCast*/IsCompAssign)) 955 return RHSType; 956 957 // This handles complex/complex, complex/float, or float/complex. 958 // When both operands are complex, the shorter operand is converted to the 959 // type of the longer, and that is the type of the result. This corresponds 960 // to what is done when combining two real floating-point operands. 961 // The fun begins when size promotion occur across type domains. 962 // From H&S 6.3.4: When one operand is complex and the other is a real 963 // floating-point type, the less precise type is converted, within it's 964 // real or complex domain, to the precision of the other type. For example, 965 // when combining a "long double" with a "double _Complex", the 966 // "double _Complex" is promoted to "long double _Complex". 967 968 // Compute the rank of the two types, regardless of whether they are complex. 969 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 970 971 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 972 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 973 QualType LHSElementType = 974 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 975 QualType RHSElementType = 976 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 977 978 QualType ResultType = S.Context.getComplexType(LHSElementType); 979 if (Order < 0) { 980 // Promote the precision of the LHS if not an assignment. 981 ResultType = S.Context.getComplexType(RHSElementType); 982 if (!IsCompAssign) { 983 if (LHSComplexType) 984 LHS = 985 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 986 else 987 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 988 } 989 } else if (Order > 0) { 990 // Promote the precision of the RHS. 991 if (RHSComplexType) 992 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 993 else 994 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 995 } 996 return ResultType; 997 } 998 999 /// \brief Handle arithmetic conversion from integer to float. Helper function 1000 /// of UsualArithmeticConversions() 1001 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1002 ExprResult &IntExpr, 1003 QualType FloatTy, QualType IntTy, 1004 bool ConvertFloat, bool ConvertInt) { 1005 if (IntTy->isIntegerType()) { 1006 if (ConvertInt) 1007 // Convert intExpr to the lhs floating point type. 1008 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1009 CK_IntegralToFloating); 1010 return FloatTy; 1011 } 1012 1013 // Convert both sides to the appropriate complex float. 1014 assert(IntTy->isComplexIntegerType()); 1015 QualType result = S.Context.getComplexType(FloatTy); 1016 1017 // _Complex int -> _Complex float 1018 if (ConvertInt) 1019 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1020 CK_IntegralComplexToFloatingComplex); 1021 1022 // float -> _Complex float 1023 if (ConvertFloat) 1024 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1025 CK_FloatingRealToComplex); 1026 1027 return result; 1028 } 1029 1030 /// \brief Handle arithmethic conversion with floating point types. Helper 1031 /// function of UsualArithmeticConversions() 1032 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1033 ExprResult &RHS, QualType LHSType, 1034 QualType RHSType, bool IsCompAssign) { 1035 bool LHSFloat = LHSType->isRealFloatingType(); 1036 bool RHSFloat = RHSType->isRealFloatingType(); 1037 1038 // If we have two real floating types, convert the smaller operand 1039 // to the bigger result. 1040 if (LHSFloat && RHSFloat) { 1041 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1042 if (order > 0) { 1043 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1044 return LHSType; 1045 } 1046 1047 assert(order < 0 && "illegal float comparison"); 1048 if (!IsCompAssign) 1049 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1050 return RHSType; 1051 } 1052 1053 if (LHSFloat) { 1054 // Half FP has to be promoted to float unless it is natively supported 1055 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1056 LHSType = S.Context.FloatTy; 1057 1058 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1059 /*convertFloat=*/!IsCompAssign, 1060 /*convertInt=*/ true); 1061 } 1062 assert(RHSFloat); 1063 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1064 /*convertInt=*/ true, 1065 /*convertFloat=*/!IsCompAssign); 1066 } 1067 1068 /// \brief Diagnose attempts to convert between __float128 and long double if 1069 /// there is no support for such conversion. Helper function of 1070 /// UsualArithmeticConversions(). 1071 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1072 QualType RHSType) { 1073 /* No issue converting if at least one of the types is not a floating point 1074 type or the two types have the same rank. 1075 */ 1076 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1077 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1078 return false; 1079 1080 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1081 "The remaining types must be floating point types."); 1082 1083 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1084 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1085 1086 QualType LHSElemType = LHSComplex ? 1087 LHSComplex->getElementType() : LHSType; 1088 QualType RHSElemType = RHSComplex ? 1089 RHSComplex->getElementType() : RHSType; 1090 1091 // No issue if the two types have the same representation 1092 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1093 &S.Context.getFloatTypeSemantics(RHSElemType)) 1094 return false; 1095 1096 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1097 RHSElemType == S.Context.LongDoubleTy); 1098 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1099 RHSElemType == S.Context.Float128Ty); 1100 1101 // We've handled the situation where __float128 and long double have the same 1102 // representation. We allow all conversions for all possible long double types 1103 // except PPC's double double. 1104 return Float128AndLongDouble && 1105 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1106 &llvm::APFloat::PPCDoubleDouble()); 1107 } 1108 1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1110 1111 namespace { 1112 /// These helper callbacks are placed in an anonymous namespace to 1113 /// permit their use as function template parameters. 1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1115 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1116 } 1117 1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1119 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1120 CK_IntegralComplexCast); 1121 } 1122 } 1123 1124 /// \brief Handle integer arithmetic conversions. Helper function of 1125 /// UsualArithmeticConversions() 1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1128 ExprResult &RHS, QualType LHSType, 1129 QualType RHSType, bool IsCompAssign) { 1130 // The rules for this case are in C99 6.3.1.8 1131 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1132 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1133 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1134 if (LHSSigned == RHSSigned) { 1135 // Same signedness; use the higher-ranked type 1136 if (order >= 0) { 1137 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1138 return LHSType; 1139 } else if (!IsCompAssign) 1140 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1141 return RHSType; 1142 } else if (order != (LHSSigned ? 1 : -1)) { 1143 // The unsigned type has greater than or equal rank to the 1144 // signed type, so use the unsigned type 1145 if (RHSSigned) { 1146 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1147 return LHSType; 1148 } else if (!IsCompAssign) 1149 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1150 return RHSType; 1151 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1152 // The two types are different widths; if we are here, that 1153 // means the signed type is larger than the unsigned type, so 1154 // use the signed type. 1155 if (LHSSigned) { 1156 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1157 return LHSType; 1158 } else if (!IsCompAssign) 1159 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1160 return RHSType; 1161 } else { 1162 // The signed type is higher-ranked than the unsigned type, 1163 // but isn't actually any bigger (like unsigned int and long 1164 // on most 32-bit systems). Use the unsigned type corresponding 1165 // to the signed type. 1166 QualType result = 1167 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1168 RHS = (*doRHSCast)(S, RHS.get(), result); 1169 if (!IsCompAssign) 1170 LHS = (*doLHSCast)(S, LHS.get(), result); 1171 return result; 1172 } 1173 } 1174 1175 /// \brief Handle conversions with GCC complex int extension. Helper function 1176 /// of UsualArithmeticConversions() 1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1178 ExprResult &RHS, QualType LHSType, 1179 QualType RHSType, 1180 bool IsCompAssign) { 1181 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1182 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1183 1184 if (LHSComplexInt && RHSComplexInt) { 1185 QualType LHSEltType = LHSComplexInt->getElementType(); 1186 QualType RHSEltType = RHSComplexInt->getElementType(); 1187 QualType ScalarType = 1188 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1189 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1190 1191 return S.Context.getComplexType(ScalarType); 1192 } 1193 1194 if (LHSComplexInt) { 1195 QualType LHSEltType = LHSComplexInt->getElementType(); 1196 QualType ScalarType = 1197 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1198 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1199 QualType ComplexType = S.Context.getComplexType(ScalarType); 1200 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1201 CK_IntegralRealToComplex); 1202 1203 return ComplexType; 1204 } 1205 1206 assert(RHSComplexInt); 1207 1208 QualType RHSEltType = RHSComplexInt->getElementType(); 1209 QualType ScalarType = 1210 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1211 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1212 QualType ComplexType = S.Context.getComplexType(ScalarType); 1213 1214 if (!IsCompAssign) 1215 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1216 CK_IntegralRealToComplex); 1217 return ComplexType; 1218 } 1219 1220 /// UsualArithmeticConversions - Performs various conversions that are common to 1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1222 /// routine returns the first non-arithmetic type found. The client is 1223 /// responsible for emitting appropriate error diagnostics. 1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1225 bool IsCompAssign) { 1226 if (!IsCompAssign) { 1227 LHS = UsualUnaryConversions(LHS.get()); 1228 if (LHS.isInvalid()) 1229 return QualType(); 1230 } 1231 1232 RHS = UsualUnaryConversions(RHS.get()); 1233 if (RHS.isInvalid()) 1234 return QualType(); 1235 1236 // For conversion purposes, we ignore any qualifiers. 1237 // For example, "const float" and "float" are equivalent. 1238 QualType LHSType = 1239 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1240 QualType RHSType = 1241 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1242 1243 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1244 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1245 LHSType = AtomicLHS->getValueType(); 1246 1247 // If both types are identical, no conversion is needed. 1248 if (LHSType == RHSType) 1249 return LHSType; 1250 1251 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1252 // The caller can deal with this (e.g. pointer + int). 1253 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1254 return QualType(); 1255 1256 // Apply unary and bitfield promotions to the LHS's type. 1257 QualType LHSUnpromotedType = LHSType; 1258 if (LHSType->isPromotableIntegerType()) 1259 LHSType = Context.getPromotedIntegerType(LHSType); 1260 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1261 if (!LHSBitfieldPromoteTy.isNull()) 1262 LHSType = LHSBitfieldPromoteTy; 1263 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1264 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1265 1266 // If both types are identical, no conversion is needed. 1267 if (LHSType == RHSType) 1268 return LHSType; 1269 1270 // At this point, we have two different arithmetic types. 1271 1272 // Diagnose attempts to convert between __float128 and long double where 1273 // such conversions currently can't be handled. 1274 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1275 return QualType(); 1276 1277 // Handle complex types first (C99 6.3.1.8p1). 1278 if (LHSType->isComplexType() || RHSType->isComplexType()) 1279 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1280 IsCompAssign); 1281 1282 // Now handle "real" floating types (i.e. float, double, long double). 1283 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1284 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1285 IsCompAssign); 1286 1287 // Handle GCC complex int extension. 1288 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1289 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1290 IsCompAssign); 1291 1292 // Finally, we have two differing integer types. 1293 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1294 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1295 } 1296 1297 1298 //===----------------------------------------------------------------------===// 1299 // Semantic Analysis for various Expression Types 1300 //===----------------------------------------------------------------------===// 1301 1302 1303 ExprResult 1304 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1305 SourceLocation DefaultLoc, 1306 SourceLocation RParenLoc, 1307 Expr *ControllingExpr, 1308 ArrayRef<ParsedType> ArgTypes, 1309 ArrayRef<Expr *> ArgExprs) { 1310 unsigned NumAssocs = ArgTypes.size(); 1311 assert(NumAssocs == ArgExprs.size()); 1312 1313 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1314 for (unsigned i = 0; i < NumAssocs; ++i) { 1315 if (ArgTypes[i]) 1316 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1317 else 1318 Types[i] = nullptr; 1319 } 1320 1321 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1322 ControllingExpr, 1323 llvm::makeArrayRef(Types, NumAssocs), 1324 ArgExprs); 1325 delete [] Types; 1326 return ER; 1327 } 1328 1329 ExprResult 1330 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1331 SourceLocation DefaultLoc, 1332 SourceLocation RParenLoc, 1333 Expr *ControllingExpr, 1334 ArrayRef<TypeSourceInfo *> Types, 1335 ArrayRef<Expr *> Exprs) { 1336 unsigned NumAssocs = Types.size(); 1337 assert(NumAssocs == Exprs.size()); 1338 1339 // Decay and strip qualifiers for the controlling expression type, and handle 1340 // placeholder type replacement. See committee discussion from WG14 DR423. 1341 { 1342 EnterExpressionEvaluationContext Unevaluated( 1343 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1344 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1345 if (R.isInvalid()) 1346 return ExprError(); 1347 ControllingExpr = R.get(); 1348 } 1349 1350 // The controlling expression is an unevaluated operand, so side effects are 1351 // likely unintended. 1352 if (!inTemplateInstantiation() && 1353 ControllingExpr->HasSideEffects(Context, false)) 1354 Diag(ControllingExpr->getExprLoc(), 1355 diag::warn_side_effects_unevaluated_context); 1356 1357 bool TypeErrorFound = false, 1358 IsResultDependent = ControllingExpr->isTypeDependent(), 1359 ContainsUnexpandedParameterPack 1360 = ControllingExpr->containsUnexpandedParameterPack(); 1361 1362 for (unsigned i = 0; i < NumAssocs; ++i) { 1363 if (Exprs[i]->containsUnexpandedParameterPack()) 1364 ContainsUnexpandedParameterPack = true; 1365 1366 if (Types[i]) { 1367 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1368 ContainsUnexpandedParameterPack = true; 1369 1370 if (Types[i]->getType()->isDependentType()) { 1371 IsResultDependent = true; 1372 } else { 1373 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1374 // complete object type other than a variably modified type." 1375 unsigned D = 0; 1376 if (Types[i]->getType()->isIncompleteType()) 1377 D = diag::err_assoc_type_incomplete; 1378 else if (!Types[i]->getType()->isObjectType()) 1379 D = diag::err_assoc_type_nonobject; 1380 else if (Types[i]->getType()->isVariablyModifiedType()) 1381 D = diag::err_assoc_type_variably_modified; 1382 1383 if (D != 0) { 1384 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1385 << Types[i]->getTypeLoc().getSourceRange() 1386 << Types[i]->getType(); 1387 TypeErrorFound = true; 1388 } 1389 1390 // C11 6.5.1.1p2 "No two generic associations in the same generic 1391 // selection shall specify compatible types." 1392 for (unsigned j = i+1; j < NumAssocs; ++j) 1393 if (Types[j] && !Types[j]->getType()->isDependentType() && 1394 Context.typesAreCompatible(Types[i]->getType(), 1395 Types[j]->getType())) { 1396 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1397 diag::err_assoc_compatible_types) 1398 << Types[j]->getTypeLoc().getSourceRange() 1399 << Types[j]->getType() 1400 << Types[i]->getType(); 1401 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1402 diag::note_compat_assoc) 1403 << Types[i]->getTypeLoc().getSourceRange() 1404 << Types[i]->getType(); 1405 TypeErrorFound = true; 1406 } 1407 } 1408 } 1409 } 1410 if (TypeErrorFound) 1411 return ExprError(); 1412 1413 // If we determined that the generic selection is result-dependent, don't 1414 // try to compute the result expression. 1415 if (IsResultDependent) 1416 return new (Context) GenericSelectionExpr( 1417 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1418 ContainsUnexpandedParameterPack); 1419 1420 SmallVector<unsigned, 1> CompatIndices; 1421 unsigned DefaultIndex = -1U; 1422 for (unsigned i = 0; i < NumAssocs; ++i) { 1423 if (!Types[i]) 1424 DefaultIndex = i; 1425 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1426 Types[i]->getType())) 1427 CompatIndices.push_back(i); 1428 } 1429 1430 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1431 // type compatible with at most one of the types named in its generic 1432 // association list." 1433 if (CompatIndices.size() > 1) { 1434 // We strip parens here because the controlling expression is typically 1435 // parenthesized in macro definitions. 1436 ControllingExpr = ControllingExpr->IgnoreParens(); 1437 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1438 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1439 << (unsigned) CompatIndices.size(); 1440 for (unsigned I : CompatIndices) { 1441 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1442 diag::note_compat_assoc) 1443 << Types[I]->getTypeLoc().getSourceRange() 1444 << Types[I]->getType(); 1445 } 1446 return ExprError(); 1447 } 1448 1449 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1450 // its controlling expression shall have type compatible with exactly one of 1451 // the types named in its generic association list." 1452 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1453 // We strip parens here because the controlling expression is typically 1454 // parenthesized in macro definitions. 1455 ControllingExpr = ControllingExpr->IgnoreParens(); 1456 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1457 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1458 return ExprError(); 1459 } 1460 1461 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1462 // type name that is compatible with the type of the controlling expression, 1463 // then the result expression of the generic selection is the expression 1464 // in that generic association. Otherwise, the result expression of the 1465 // generic selection is the expression in the default generic association." 1466 unsigned ResultIndex = 1467 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1468 1469 return new (Context) GenericSelectionExpr( 1470 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1471 ContainsUnexpandedParameterPack, ResultIndex); 1472 } 1473 1474 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1475 /// location of the token and the offset of the ud-suffix within it. 1476 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1477 unsigned Offset) { 1478 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1479 S.getLangOpts()); 1480 } 1481 1482 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1483 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1484 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1485 IdentifierInfo *UDSuffix, 1486 SourceLocation UDSuffixLoc, 1487 ArrayRef<Expr*> Args, 1488 SourceLocation LitEndLoc) { 1489 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1490 1491 QualType ArgTy[2]; 1492 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1493 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1494 if (ArgTy[ArgIdx]->isArrayType()) 1495 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1496 } 1497 1498 DeclarationName OpName = 1499 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1500 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1501 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1502 1503 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1504 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1505 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1506 /*AllowStringTemplate*/ false, 1507 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1508 return ExprError(); 1509 1510 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1511 } 1512 1513 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1514 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1515 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1516 /// multiple tokens. However, the common case is that StringToks points to one 1517 /// string. 1518 /// 1519 ExprResult 1520 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1521 assert(!StringToks.empty() && "Must have at least one string!"); 1522 1523 StringLiteralParser Literal(StringToks, PP); 1524 if (Literal.hadError) 1525 return ExprError(); 1526 1527 SmallVector<SourceLocation, 4> StringTokLocs; 1528 for (const Token &Tok : StringToks) 1529 StringTokLocs.push_back(Tok.getLocation()); 1530 1531 QualType CharTy = Context.CharTy; 1532 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1533 if (Literal.isWide()) { 1534 CharTy = Context.getWideCharType(); 1535 Kind = StringLiteral::Wide; 1536 } else if (Literal.isUTF8()) { 1537 Kind = StringLiteral::UTF8; 1538 } else if (Literal.isUTF16()) { 1539 CharTy = Context.Char16Ty; 1540 Kind = StringLiteral::UTF16; 1541 } else if (Literal.isUTF32()) { 1542 CharTy = Context.Char32Ty; 1543 Kind = StringLiteral::UTF32; 1544 } else if (Literal.isPascal()) { 1545 CharTy = Context.UnsignedCharTy; 1546 } 1547 1548 QualType CharTyConst = CharTy; 1549 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1550 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1551 CharTyConst.addConst(); 1552 1553 // Get an array type for the string, according to C99 6.4.5. This includes 1554 // the nul terminator character as well as the string length for pascal 1555 // strings. 1556 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1557 llvm::APInt(32, Literal.GetNumStringChars()+1), 1558 ArrayType::Normal, 0); 1559 1560 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1561 if (getLangOpts().OpenCL) { 1562 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1563 } 1564 1565 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1566 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1567 Kind, Literal.Pascal, StrTy, 1568 &StringTokLocs[0], 1569 StringTokLocs.size()); 1570 if (Literal.getUDSuffix().empty()) 1571 return Lit; 1572 1573 // We're building a user-defined literal. 1574 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1575 SourceLocation UDSuffixLoc = 1576 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1577 Literal.getUDSuffixOffset()); 1578 1579 // Make sure we're allowed user-defined literals here. 1580 if (!UDLScope) 1581 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1582 1583 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1584 // operator "" X (str, len) 1585 QualType SizeType = Context.getSizeType(); 1586 1587 DeclarationName OpName = 1588 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1589 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1590 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1591 1592 QualType ArgTy[] = { 1593 Context.getArrayDecayedType(StrTy), SizeType 1594 }; 1595 1596 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1597 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1598 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1599 /*AllowStringTemplate*/ true, 1600 /*DiagnoseMissing*/ true)) { 1601 1602 case LOLR_Cooked: { 1603 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1604 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1605 StringTokLocs[0]); 1606 Expr *Args[] = { Lit, LenArg }; 1607 1608 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1609 } 1610 1611 case LOLR_StringTemplate: { 1612 TemplateArgumentListInfo ExplicitArgs; 1613 1614 unsigned CharBits = Context.getIntWidth(CharTy); 1615 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1616 llvm::APSInt Value(CharBits, CharIsUnsigned); 1617 1618 TemplateArgument TypeArg(CharTy); 1619 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1620 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1621 1622 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1623 Value = Lit->getCodeUnit(I); 1624 TemplateArgument Arg(Context, Value, CharTy); 1625 TemplateArgumentLocInfo ArgInfo; 1626 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1627 } 1628 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1629 &ExplicitArgs); 1630 } 1631 case LOLR_Raw: 1632 case LOLR_Template: 1633 case LOLR_ErrorNoDiagnostic: 1634 llvm_unreachable("unexpected literal operator lookup result"); 1635 case LOLR_Error: 1636 return ExprError(); 1637 } 1638 llvm_unreachable("unexpected literal operator lookup result"); 1639 } 1640 1641 ExprResult 1642 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1643 SourceLocation Loc, 1644 const CXXScopeSpec *SS) { 1645 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1646 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1647 } 1648 1649 /// BuildDeclRefExpr - Build an expression that references a 1650 /// declaration that does not require a closure capture. 1651 ExprResult 1652 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1653 const DeclarationNameInfo &NameInfo, 1654 const CXXScopeSpec *SS, NamedDecl *FoundD, 1655 const TemplateArgumentListInfo *TemplateArgs) { 1656 bool RefersToCapturedVariable = 1657 isa<VarDecl>(D) && 1658 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1659 1660 DeclRefExpr *E; 1661 if (isa<VarTemplateSpecializationDecl>(D)) { 1662 VarTemplateSpecializationDecl *VarSpec = 1663 cast<VarTemplateSpecializationDecl>(D); 1664 1665 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1666 : NestedNameSpecifierLoc(), 1667 VarSpec->getTemplateKeywordLoc(), D, 1668 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1669 FoundD, TemplateArgs); 1670 } else { 1671 assert(!TemplateArgs && "No template arguments for non-variable" 1672 " template specialization references"); 1673 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1674 : NestedNameSpecifierLoc(), 1675 SourceLocation(), D, RefersToCapturedVariable, 1676 NameInfo, Ty, VK, FoundD); 1677 } 1678 1679 MarkDeclRefReferenced(E); 1680 1681 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1682 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1683 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1684 getCurFunction()->recordUseOfWeak(E); 1685 1686 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1687 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1688 FD = IFD->getAnonField(); 1689 if (FD) { 1690 UnusedPrivateFields.remove(FD); 1691 // Just in case we're building an illegal pointer-to-member. 1692 if (FD->isBitField()) 1693 E->setObjectKind(OK_BitField); 1694 } 1695 1696 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1697 // designates a bit-field. 1698 if (auto *BD = dyn_cast<BindingDecl>(D)) 1699 if (auto *BE = BD->getBinding()) 1700 E->setObjectKind(BE->getObjectKind()); 1701 1702 return E; 1703 } 1704 1705 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1706 /// possibly a list of template arguments. 1707 /// 1708 /// If this produces template arguments, it is permitted to call 1709 /// DecomposeTemplateName. 1710 /// 1711 /// This actually loses a lot of source location information for 1712 /// non-standard name kinds; we should consider preserving that in 1713 /// some way. 1714 void 1715 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1716 TemplateArgumentListInfo &Buffer, 1717 DeclarationNameInfo &NameInfo, 1718 const TemplateArgumentListInfo *&TemplateArgs) { 1719 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1720 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1721 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1722 1723 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1724 Id.TemplateId->NumArgs); 1725 translateTemplateArguments(TemplateArgsPtr, Buffer); 1726 1727 TemplateName TName = Id.TemplateId->Template.get(); 1728 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1729 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1730 TemplateArgs = &Buffer; 1731 } else { 1732 NameInfo = GetNameFromUnqualifiedId(Id); 1733 TemplateArgs = nullptr; 1734 } 1735 } 1736 1737 static void emitEmptyLookupTypoDiagnostic( 1738 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1739 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1740 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1741 DeclContext *Ctx = 1742 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1743 if (!TC) { 1744 // Emit a special diagnostic for failed member lookups. 1745 // FIXME: computing the declaration context might fail here (?) 1746 if (Ctx) 1747 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1748 << SS.getRange(); 1749 else 1750 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1751 return; 1752 } 1753 1754 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1755 bool DroppedSpecifier = 1756 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1757 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1758 ? diag::note_implicit_param_decl 1759 : diag::note_previous_decl; 1760 if (!Ctx) 1761 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1762 SemaRef.PDiag(NoteID)); 1763 else 1764 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1765 << Typo << Ctx << DroppedSpecifier 1766 << SS.getRange(), 1767 SemaRef.PDiag(NoteID)); 1768 } 1769 1770 /// Diagnose an empty lookup. 1771 /// 1772 /// \return false if new lookup candidates were found 1773 bool 1774 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1775 std::unique_ptr<CorrectionCandidateCallback> CCC, 1776 TemplateArgumentListInfo *ExplicitTemplateArgs, 1777 ArrayRef<Expr *> Args, TypoExpr **Out) { 1778 DeclarationName Name = R.getLookupName(); 1779 1780 unsigned diagnostic = diag::err_undeclared_var_use; 1781 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1782 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1783 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1784 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1785 diagnostic = diag::err_undeclared_use; 1786 diagnostic_suggest = diag::err_undeclared_use_suggest; 1787 } 1788 1789 // If the original lookup was an unqualified lookup, fake an 1790 // unqualified lookup. This is useful when (for example) the 1791 // original lookup would not have found something because it was a 1792 // dependent name. 1793 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1794 while (DC) { 1795 if (isa<CXXRecordDecl>(DC)) { 1796 LookupQualifiedName(R, DC); 1797 1798 if (!R.empty()) { 1799 // Don't give errors about ambiguities in this lookup. 1800 R.suppressDiagnostics(); 1801 1802 // During a default argument instantiation the CurContext points 1803 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1804 // function parameter list, hence add an explicit check. 1805 bool isDefaultArgument = 1806 !CodeSynthesisContexts.empty() && 1807 CodeSynthesisContexts.back().Kind == 1808 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1809 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1810 bool isInstance = CurMethod && 1811 CurMethod->isInstance() && 1812 DC == CurMethod->getParent() && !isDefaultArgument; 1813 1814 // Give a code modification hint to insert 'this->'. 1815 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1816 // Actually quite difficult! 1817 if (getLangOpts().MSVCCompat) 1818 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1819 if (isInstance) { 1820 Diag(R.getNameLoc(), diagnostic) << Name 1821 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1822 CheckCXXThisCapture(R.getNameLoc()); 1823 } else { 1824 Diag(R.getNameLoc(), diagnostic) << Name; 1825 } 1826 1827 // Do we really want to note all of these? 1828 for (NamedDecl *D : R) 1829 Diag(D->getLocation(), diag::note_dependent_var_use); 1830 1831 // Return true if we are inside a default argument instantiation 1832 // and the found name refers to an instance member function, otherwise 1833 // the function calling DiagnoseEmptyLookup will try to create an 1834 // implicit member call and this is wrong for default argument. 1835 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1836 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1837 return true; 1838 } 1839 1840 // Tell the callee to try to recover. 1841 return false; 1842 } 1843 1844 R.clear(); 1845 } 1846 1847 // In Microsoft mode, if we are performing lookup from within a friend 1848 // function definition declared at class scope then we must set 1849 // DC to the lexical parent to be able to search into the parent 1850 // class. 1851 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1852 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1853 DC->getLexicalParent()->isRecord()) 1854 DC = DC->getLexicalParent(); 1855 else 1856 DC = DC->getParent(); 1857 } 1858 1859 // We didn't find anything, so try to correct for a typo. 1860 TypoCorrection Corrected; 1861 if (S && Out) { 1862 SourceLocation TypoLoc = R.getNameLoc(); 1863 assert(!ExplicitTemplateArgs && 1864 "Diagnosing an empty lookup with explicit template args!"); 1865 *Out = CorrectTypoDelayed( 1866 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1867 [=](const TypoCorrection &TC) { 1868 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1869 diagnostic, diagnostic_suggest); 1870 }, 1871 nullptr, CTK_ErrorRecovery); 1872 if (*Out) 1873 return true; 1874 } else if (S && (Corrected = 1875 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1876 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1877 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1878 bool DroppedSpecifier = 1879 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1880 R.setLookupName(Corrected.getCorrection()); 1881 1882 bool AcceptableWithRecovery = false; 1883 bool AcceptableWithoutRecovery = false; 1884 NamedDecl *ND = Corrected.getFoundDecl(); 1885 if (ND) { 1886 if (Corrected.isOverloaded()) { 1887 OverloadCandidateSet OCS(R.getNameLoc(), 1888 OverloadCandidateSet::CSK_Normal); 1889 OverloadCandidateSet::iterator Best; 1890 for (NamedDecl *CD : Corrected) { 1891 if (FunctionTemplateDecl *FTD = 1892 dyn_cast<FunctionTemplateDecl>(CD)) 1893 AddTemplateOverloadCandidate( 1894 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1895 Args, OCS); 1896 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1897 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1898 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1899 Args, OCS); 1900 } 1901 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1902 case OR_Success: 1903 ND = Best->FoundDecl; 1904 Corrected.setCorrectionDecl(ND); 1905 break; 1906 default: 1907 // FIXME: Arbitrarily pick the first declaration for the note. 1908 Corrected.setCorrectionDecl(ND); 1909 break; 1910 } 1911 } 1912 R.addDecl(ND); 1913 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1914 CXXRecordDecl *Record = nullptr; 1915 if (Corrected.getCorrectionSpecifier()) { 1916 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1917 Record = Ty->getAsCXXRecordDecl(); 1918 } 1919 if (!Record) 1920 Record = cast<CXXRecordDecl>( 1921 ND->getDeclContext()->getRedeclContext()); 1922 R.setNamingClass(Record); 1923 } 1924 1925 auto *UnderlyingND = ND->getUnderlyingDecl(); 1926 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1927 isa<FunctionTemplateDecl>(UnderlyingND); 1928 // FIXME: If we ended up with a typo for a type name or 1929 // Objective-C class name, we're in trouble because the parser 1930 // is in the wrong place to recover. Suggest the typo 1931 // correction, but don't make it a fix-it since we're not going 1932 // to recover well anyway. 1933 AcceptableWithoutRecovery = 1934 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1935 } else { 1936 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1937 // because we aren't able to recover. 1938 AcceptableWithoutRecovery = true; 1939 } 1940 1941 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1942 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1943 ? diag::note_implicit_param_decl 1944 : diag::note_previous_decl; 1945 if (SS.isEmpty()) 1946 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1947 PDiag(NoteID), AcceptableWithRecovery); 1948 else 1949 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1950 << Name << computeDeclContext(SS, false) 1951 << DroppedSpecifier << SS.getRange(), 1952 PDiag(NoteID), AcceptableWithRecovery); 1953 1954 // Tell the callee whether to try to recover. 1955 return !AcceptableWithRecovery; 1956 } 1957 } 1958 R.clear(); 1959 1960 // Emit a special diagnostic for failed member lookups. 1961 // FIXME: computing the declaration context might fail here (?) 1962 if (!SS.isEmpty()) { 1963 Diag(R.getNameLoc(), diag::err_no_member) 1964 << Name << computeDeclContext(SS, false) 1965 << SS.getRange(); 1966 return true; 1967 } 1968 1969 // Give up, we can't recover. 1970 Diag(R.getNameLoc(), diagnostic) << Name; 1971 return true; 1972 } 1973 1974 /// In Microsoft mode, if we are inside a template class whose parent class has 1975 /// dependent base classes, and we can't resolve an unqualified identifier, then 1976 /// assume the identifier is a member of a dependent base class. We can only 1977 /// recover successfully in static methods, instance methods, and other contexts 1978 /// where 'this' is available. This doesn't precisely match MSVC's 1979 /// instantiation model, but it's close enough. 1980 static Expr * 1981 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1982 DeclarationNameInfo &NameInfo, 1983 SourceLocation TemplateKWLoc, 1984 const TemplateArgumentListInfo *TemplateArgs) { 1985 // Only try to recover from lookup into dependent bases in static methods or 1986 // contexts where 'this' is available. 1987 QualType ThisType = S.getCurrentThisType(); 1988 const CXXRecordDecl *RD = nullptr; 1989 if (!ThisType.isNull()) 1990 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1991 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1992 RD = MD->getParent(); 1993 if (!RD || !RD->hasAnyDependentBases()) 1994 return nullptr; 1995 1996 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1997 // is available, suggest inserting 'this->' as a fixit. 1998 SourceLocation Loc = NameInfo.getLoc(); 1999 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2000 DB << NameInfo.getName() << RD; 2001 2002 if (!ThisType.isNull()) { 2003 DB << FixItHint::CreateInsertion(Loc, "this->"); 2004 return CXXDependentScopeMemberExpr::Create( 2005 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2006 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2007 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2008 } 2009 2010 // Synthesize a fake NNS that points to the derived class. This will 2011 // perform name lookup during template instantiation. 2012 CXXScopeSpec SS; 2013 auto *NNS = 2014 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2015 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2016 return DependentScopeDeclRefExpr::Create( 2017 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2018 TemplateArgs); 2019 } 2020 2021 ExprResult 2022 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2023 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2024 bool HasTrailingLParen, bool IsAddressOfOperand, 2025 std::unique_ptr<CorrectionCandidateCallback> CCC, 2026 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2027 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2028 "cannot be direct & operand and have a trailing lparen"); 2029 if (SS.isInvalid()) 2030 return ExprError(); 2031 2032 TemplateArgumentListInfo TemplateArgsBuffer; 2033 2034 // Decompose the UnqualifiedId into the following data. 2035 DeclarationNameInfo NameInfo; 2036 const TemplateArgumentListInfo *TemplateArgs; 2037 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2038 2039 DeclarationName Name = NameInfo.getName(); 2040 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2041 SourceLocation NameLoc = NameInfo.getLoc(); 2042 2043 if (II && II->isEditorPlaceholder()) { 2044 // FIXME: When typed placeholders are supported we can create a typed 2045 // placeholder expression node. 2046 return ExprError(); 2047 } 2048 2049 // C++ [temp.dep.expr]p3: 2050 // An id-expression is type-dependent if it contains: 2051 // -- an identifier that was declared with a dependent type, 2052 // (note: handled after lookup) 2053 // -- a template-id that is dependent, 2054 // (note: handled in BuildTemplateIdExpr) 2055 // -- a conversion-function-id that specifies a dependent type, 2056 // -- a nested-name-specifier that contains a class-name that 2057 // names a dependent type. 2058 // Determine whether this is a member of an unknown specialization; 2059 // we need to handle these differently. 2060 bool DependentID = false; 2061 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2062 Name.getCXXNameType()->isDependentType()) { 2063 DependentID = true; 2064 } else if (SS.isSet()) { 2065 if (DeclContext *DC = computeDeclContext(SS, false)) { 2066 if (RequireCompleteDeclContext(SS, DC)) 2067 return ExprError(); 2068 } else { 2069 DependentID = true; 2070 } 2071 } 2072 2073 if (DependentID) 2074 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2075 IsAddressOfOperand, TemplateArgs); 2076 2077 // Perform the required lookup. 2078 LookupResult R(*this, NameInfo, 2079 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2080 ? LookupObjCImplicitSelfParam 2081 : LookupOrdinaryName); 2082 if (TemplateArgs) { 2083 // Lookup the template name again to correctly establish the context in 2084 // which it was found. This is really unfortunate as we already did the 2085 // lookup to determine that it was a template name in the first place. If 2086 // this becomes a performance hit, we can work harder to preserve those 2087 // results until we get here but it's likely not worth it. 2088 bool MemberOfUnknownSpecialization; 2089 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2090 MemberOfUnknownSpecialization); 2091 2092 if (MemberOfUnknownSpecialization || 2093 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2094 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2095 IsAddressOfOperand, TemplateArgs); 2096 } else { 2097 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2098 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2099 2100 // If the result might be in a dependent base class, this is a dependent 2101 // id-expression. 2102 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2103 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2104 IsAddressOfOperand, TemplateArgs); 2105 2106 // If this reference is in an Objective-C method, then we need to do 2107 // some special Objective-C lookup, too. 2108 if (IvarLookupFollowUp) { 2109 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2110 if (E.isInvalid()) 2111 return ExprError(); 2112 2113 if (Expr *Ex = E.getAs<Expr>()) 2114 return Ex; 2115 } 2116 } 2117 2118 if (R.isAmbiguous()) 2119 return ExprError(); 2120 2121 // This could be an implicitly declared function reference (legal in C90, 2122 // extension in C99, forbidden in C++). 2123 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2124 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2125 if (D) R.addDecl(D); 2126 } 2127 2128 // Determine whether this name might be a candidate for 2129 // argument-dependent lookup. 2130 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2131 2132 if (R.empty() && !ADL) { 2133 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2134 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2135 TemplateKWLoc, TemplateArgs)) 2136 return E; 2137 } 2138 2139 // Don't diagnose an empty lookup for inline assembly. 2140 if (IsInlineAsmIdentifier) 2141 return ExprError(); 2142 2143 // If this name wasn't predeclared and if this is not a function 2144 // call, diagnose the problem. 2145 TypoExpr *TE = nullptr; 2146 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2147 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2148 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2149 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2150 "Typo correction callback misconfigured"); 2151 if (CCC) { 2152 // Make sure the callback knows what the typo being diagnosed is. 2153 CCC->setTypoName(II); 2154 if (SS.isValid()) 2155 CCC->setTypoNNS(SS.getScopeRep()); 2156 } 2157 if (DiagnoseEmptyLookup(S, SS, R, 2158 CCC ? std::move(CCC) : std::move(DefaultValidator), 2159 nullptr, None, &TE)) { 2160 if (TE && KeywordReplacement) { 2161 auto &State = getTypoExprState(TE); 2162 auto BestTC = State.Consumer->getNextCorrection(); 2163 if (BestTC.isKeyword()) { 2164 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2165 if (State.DiagHandler) 2166 State.DiagHandler(BestTC); 2167 KeywordReplacement->startToken(); 2168 KeywordReplacement->setKind(II->getTokenID()); 2169 KeywordReplacement->setIdentifierInfo(II); 2170 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2171 // Clean up the state associated with the TypoExpr, since it has 2172 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2173 clearDelayedTypo(TE); 2174 // Signal that a correction to a keyword was performed by returning a 2175 // valid-but-null ExprResult. 2176 return (Expr*)nullptr; 2177 } 2178 State.Consumer->resetCorrectionStream(); 2179 } 2180 return TE ? TE : ExprError(); 2181 } 2182 2183 assert(!R.empty() && 2184 "DiagnoseEmptyLookup returned false but added no results"); 2185 2186 // If we found an Objective-C instance variable, let 2187 // LookupInObjCMethod build the appropriate expression to 2188 // reference the ivar. 2189 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2190 R.clear(); 2191 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2192 // In a hopelessly buggy code, Objective-C instance variable 2193 // lookup fails and no expression will be built to reference it. 2194 if (!E.isInvalid() && !E.get()) 2195 return ExprError(); 2196 return E; 2197 } 2198 } 2199 2200 // This is guaranteed from this point on. 2201 assert(!R.empty() || ADL); 2202 2203 // Check whether this might be a C++ implicit instance member access. 2204 // C++ [class.mfct.non-static]p3: 2205 // When an id-expression that is not part of a class member access 2206 // syntax and not used to form a pointer to member is used in the 2207 // body of a non-static member function of class X, if name lookup 2208 // resolves the name in the id-expression to a non-static non-type 2209 // member of some class C, the id-expression is transformed into a 2210 // class member access expression using (*this) as the 2211 // postfix-expression to the left of the . operator. 2212 // 2213 // But we don't actually need to do this for '&' operands if R 2214 // resolved to a function or overloaded function set, because the 2215 // expression is ill-formed if it actually works out to be a 2216 // non-static member function: 2217 // 2218 // C++ [expr.ref]p4: 2219 // Otherwise, if E1.E2 refers to a non-static member function. . . 2220 // [t]he expression can be used only as the left-hand operand of a 2221 // member function call. 2222 // 2223 // There are other safeguards against such uses, but it's important 2224 // to get this right here so that we don't end up making a 2225 // spuriously dependent expression if we're inside a dependent 2226 // instance method. 2227 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2228 bool MightBeImplicitMember; 2229 if (!IsAddressOfOperand) 2230 MightBeImplicitMember = true; 2231 else if (!SS.isEmpty()) 2232 MightBeImplicitMember = false; 2233 else if (R.isOverloadedResult()) 2234 MightBeImplicitMember = false; 2235 else if (R.isUnresolvableResult()) 2236 MightBeImplicitMember = true; 2237 else 2238 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2239 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2240 isa<MSPropertyDecl>(R.getFoundDecl()); 2241 2242 if (MightBeImplicitMember) 2243 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2244 R, TemplateArgs, S); 2245 } 2246 2247 if (TemplateArgs || TemplateKWLoc.isValid()) { 2248 2249 // In C++1y, if this is a variable template id, then check it 2250 // in BuildTemplateIdExpr(). 2251 // The single lookup result must be a variable template declaration. 2252 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2253 Id.TemplateId->Kind == TNK_Var_template) { 2254 assert(R.getAsSingle<VarTemplateDecl>() && 2255 "There should only be one declaration found."); 2256 } 2257 2258 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2259 } 2260 2261 return BuildDeclarationNameExpr(SS, R, ADL); 2262 } 2263 2264 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2265 /// declaration name, generally during template instantiation. 2266 /// There's a large number of things which don't need to be done along 2267 /// this path. 2268 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2269 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2270 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2271 DeclContext *DC = computeDeclContext(SS, false); 2272 if (!DC) 2273 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2274 NameInfo, /*TemplateArgs=*/nullptr); 2275 2276 if (RequireCompleteDeclContext(SS, DC)) 2277 return ExprError(); 2278 2279 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2280 LookupQualifiedName(R, DC); 2281 2282 if (R.isAmbiguous()) 2283 return ExprError(); 2284 2285 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2286 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2287 NameInfo, /*TemplateArgs=*/nullptr); 2288 2289 if (R.empty()) { 2290 Diag(NameInfo.getLoc(), diag::err_no_member) 2291 << NameInfo.getName() << DC << SS.getRange(); 2292 return ExprError(); 2293 } 2294 2295 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2296 // Diagnose a missing typename if this resolved unambiguously to a type in 2297 // a dependent context. If we can recover with a type, downgrade this to 2298 // a warning in Microsoft compatibility mode. 2299 unsigned DiagID = diag::err_typename_missing; 2300 if (RecoveryTSI && getLangOpts().MSVCCompat) 2301 DiagID = diag::ext_typename_missing; 2302 SourceLocation Loc = SS.getBeginLoc(); 2303 auto D = Diag(Loc, DiagID); 2304 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2305 << SourceRange(Loc, NameInfo.getEndLoc()); 2306 2307 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2308 // context. 2309 if (!RecoveryTSI) 2310 return ExprError(); 2311 2312 // Only issue the fixit if we're prepared to recover. 2313 D << FixItHint::CreateInsertion(Loc, "typename "); 2314 2315 // Recover by pretending this was an elaborated type. 2316 QualType Ty = Context.getTypeDeclType(TD); 2317 TypeLocBuilder TLB; 2318 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2319 2320 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2321 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2322 QTL.setElaboratedKeywordLoc(SourceLocation()); 2323 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2324 2325 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2326 2327 return ExprEmpty(); 2328 } 2329 2330 // Defend against this resolving to an implicit member access. We usually 2331 // won't get here if this might be a legitimate a class member (we end up in 2332 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2333 // a pointer-to-member or in an unevaluated context in C++11. 2334 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2335 return BuildPossibleImplicitMemberExpr(SS, 2336 /*TemplateKWLoc=*/SourceLocation(), 2337 R, /*TemplateArgs=*/nullptr, S); 2338 2339 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2340 } 2341 2342 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2343 /// detected that we're currently inside an ObjC method. Perform some 2344 /// additional lookup. 2345 /// 2346 /// Ideally, most of this would be done by lookup, but there's 2347 /// actually quite a lot of extra work involved. 2348 /// 2349 /// Returns a null sentinel to indicate trivial success. 2350 ExprResult 2351 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2352 IdentifierInfo *II, bool AllowBuiltinCreation) { 2353 SourceLocation Loc = Lookup.getNameLoc(); 2354 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2355 2356 // Check for error condition which is already reported. 2357 if (!CurMethod) 2358 return ExprError(); 2359 2360 // There are two cases to handle here. 1) scoped lookup could have failed, 2361 // in which case we should look for an ivar. 2) scoped lookup could have 2362 // found a decl, but that decl is outside the current instance method (i.e. 2363 // a global variable). In these two cases, we do a lookup for an ivar with 2364 // this name, if the lookup sucedes, we replace it our current decl. 2365 2366 // If we're in a class method, we don't normally want to look for 2367 // ivars. But if we don't find anything else, and there's an 2368 // ivar, that's an error. 2369 bool IsClassMethod = CurMethod->isClassMethod(); 2370 2371 bool LookForIvars; 2372 if (Lookup.empty()) 2373 LookForIvars = true; 2374 else if (IsClassMethod) 2375 LookForIvars = false; 2376 else 2377 LookForIvars = (Lookup.isSingleResult() && 2378 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2379 ObjCInterfaceDecl *IFace = nullptr; 2380 if (LookForIvars) { 2381 IFace = CurMethod->getClassInterface(); 2382 ObjCInterfaceDecl *ClassDeclared; 2383 ObjCIvarDecl *IV = nullptr; 2384 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2385 // Diagnose using an ivar in a class method. 2386 if (IsClassMethod) 2387 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2388 << IV->getDeclName()); 2389 2390 // If we're referencing an invalid decl, just return this as a silent 2391 // error node. The error diagnostic was already emitted on the decl. 2392 if (IV->isInvalidDecl()) 2393 return ExprError(); 2394 2395 // Check if referencing a field with __attribute__((deprecated)). 2396 if (DiagnoseUseOfDecl(IV, Loc)) 2397 return ExprError(); 2398 2399 // Diagnose the use of an ivar outside of the declaring class. 2400 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2401 !declaresSameEntity(ClassDeclared, IFace) && 2402 !getLangOpts().DebuggerSupport) 2403 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2404 2405 // FIXME: This should use a new expr for a direct reference, don't 2406 // turn this into Self->ivar, just return a BareIVarExpr or something. 2407 IdentifierInfo &II = Context.Idents.get("self"); 2408 UnqualifiedId SelfName; 2409 SelfName.setIdentifier(&II, SourceLocation()); 2410 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2411 CXXScopeSpec SelfScopeSpec; 2412 SourceLocation TemplateKWLoc; 2413 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2414 SelfName, false, false); 2415 if (SelfExpr.isInvalid()) 2416 return ExprError(); 2417 2418 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2419 if (SelfExpr.isInvalid()) 2420 return ExprError(); 2421 2422 MarkAnyDeclReferenced(Loc, IV, true); 2423 2424 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2425 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2426 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2427 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2428 2429 ObjCIvarRefExpr *Result = new (Context) 2430 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2431 IV->getLocation(), SelfExpr.get(), true, true); 2432 2433 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2434 if (!isUnevaluatedContext() && 2435 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2436 getCurFunction()->recordUseOfWeak(Result); 2437 } 2438 if (getLangOpts().ObjCAutoRefCount) { 2439 if (CurContext->isClosure()) 2440 Diag(Loc, diag::warn_implicitly_retains_self) 2441 << FixItHint::CreateInsertion(Loc, "self->"); 2442 } 2443 2444 return Result; 2445 } 2446 } else if (CurMethod->isInstanceMethod()) { 2447 // We should warn if a local variable hides an ivar. 2448 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2449 ObjCInterfaceDecl *ClassDeclared; 2450 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2451 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2452 declaresSameEntity(IFace, ClassDeclared)) 2453 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2454 } 2455 } 2456 } else if (Lookup.isSingleResult() && 2457 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2458 // If accessing a stand-alone ivar in a class method, this is an error. 2459 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2460 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2461 << IV->getDeclName()); 2462 } 2463 2464 if (Lookup.empty() && II && AllowBuiltinCreation) { 2465 // FIXME. Consolidate this with similar code in LookupName. 2466 if (unsigned BuiltinID = II->getBuiltinID()) { 2467 if (!(getLangOpts().CPlusPlus && 2468 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2469 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2470 S, Lookup.isForRedeclaration(), 2471 Lookup.getNameLoc()); 2472 if (D) Lookup.addDecl(D); 2473 } 2474 } 2475 } 2476 // Sentinel value saying that we didn't do anything special. 2477 return ExprResult((Expr *)nullptr); 2478 } 2479 2480 /// \brief Cast a base object to a member's actual type. 2481 /// 2482 /// Logically this happens in three phases: 2483 /// 2484 /// * First we cast from the base type to the naming class. 2485 /// The naming class is the class into which we were looking 2486 /// when we found the member; it's the qualifier type if a 2487 /// qualifier was provided, and otherwise it's the base type. 2488 /// 2489 /// * Next we cast from the naming class to the declaring class. 2490 /// If the member we found was brought into a class's scope by 2491 /// a using declaration, this is that class; otherwise it's 2492 /// the class declaring the member. 2493 /// 2494 /// * Finally we cast from the declaring class to the "true" 2495 /// declaring class of the member. This conversion does not 2496 /// obey access control. 2497 ExprResult 2498 Sema::PerformObjectMemberConversion(Expr *From, 2499 NestedNameSpecifier *Qualifier, 2500 NamedDecl *FoundDecl, 2501 NamedDecl *Member) { 2502 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2503 if (!RD) 2504 return From; 2505 2506 QualType DestRecordType; 2507 QualType DestType; 2508 QualType FromRecordType; 2509 QualType FromType = From->getType(); 2510 bool PointerConversions = false; 2511 if (isa<FieldDecl>(Member)) { 2512 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2513 2514 if (FromType->getAs<PointerType>()) { 2515 DestType = Context.getPointerType(DestRecordType); 2516 FromRecordType = FromType->getPointeeType(); 2517 PointerConversions = true; 2518 } else { 2519 DestType = DestRecordType; 2520 FromRecordType = FromType; 2521 } 2522 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2523 if (Method->isStatic()) 2524 return From; 2525 2526 DestType = Method->getThisType(Context); 2527 DestRecordType = DestType->getPointeeType(); 2528 2529 if (FromType->getAs<PointerType>()) { 2530 FromRecordType = FromType->getPointeeType(); 2531 PointerConversions = true; 2532 } else { 2533 FromRecordType = FromType; 2534 DestType = DestRecordType; 2535 } 2536 } else { 2537 // No conversion necessary. 2538 return From; 2539 } 2540 2541 if (DestType->isDependentType() || FromType->isDependentType()) 2542 return From; 2543 2544 // If the unqualified types are the same, no conversion is necessary. 2545 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2546 return From; 2547 2548 SourceRange FromRange = From->getSourceRange(); 2549 SourceLocation FromLoc = FromRange.getBegin(); 2550 2551 ExprValueKind VK = From->getValueKind(); 2552 2553 // C++ [class.member.lookup]p8: 2554 // [...] Ambiguities can often be resolved by qualifying a name with its 2555 // class name. 2556 // 2557 // If the member was a qualified name and the qualified referred to a 2558 // specific base subobject type, we'll cast to that intermediate type 2559 // first and then to the object in which the member is declared. That allows 2560 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2561 // 2562 // class Base { public: int x; }; 2563 // class Derived1 : public Base { }; 2564 // class Derived2 : public Base { }; 2565 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2566 // 2567 // void VeryDerived::f() { 2568 // x = 17; // error: ambiguous base subobjects 2569 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2570 // } 2571 if (Qualifier && Qualifier->getAsType()) { 2572 QualType QType = QualType(Qualifier->getAsType(), 0); 2573 assert(QType->isRecordType() && "lookup done with non-record type"); 2574 2575 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2576 2577 // In C++98, the qualifier type doesn't actually have to be a base 2578 // type of the object type, in which case we just ignore it. 2579 // Otherwise build the appropriate casts. 2580 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2581 CXXCastPath BasePath; 2582 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2583 FromLoc, FromRange, &BasePath)) 2584 return ExprError(); 2585 2586 if (PointerConversions) 2587 QType = Context.getPointerType(QType); 2588 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2589 VK, &BasePath).get(); 2590 2591 FromType = QType; 2592 FromRecordType = QRecordType; 2593 2594 // If the qualifier type was the same as the destination type, 2595 // we're done. 2596 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2597 return From; 2598 } 2599 } 2600 2601 bool IgnoreAccess = false; 2602 2603 // If we actually found the member through a using declaration, cast 2604 // down to the using declaration's type. 2605 // 2606 // Pointer equality is fine here because only one declaration of a 2607 // class ever has member declarations. 2608 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2609 assert(isa<UsingShadowDecl>(FoundDecl)); 2610 QualType URecordType = Context.getTypeDeclType( 2611 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2612 2613 // We only need to do this if the naming-class to declaring-class 2614 // conversion is non-trivial. 2615 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2616 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2617 CXXCastPath BasePath; 2618 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2619 FromLoc, FromRange, &BasePath)) 2620 return ExprError(); 2621 2622 QualType UType = URecordType; 2623 if (PointerConversions) 2624 UType = Context.getPointerType(UType); 2625 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2626 VK, &BasePath).get(); 2627 FromType = UType; 2628 FromRecordType = URecordType; 2629 } 2630 2631 // We don't do access control for the conversion from the 2632 // declaring class to the true declaring class. 2633 IgnoreAccess = true; 2634 } 2635 2636 CXXCastPath BasePath; 2637 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2638 FromLoc, FromRange, &BasePath, 2639 IgnoreAccess)) 2640 return ExprError(); 2641 2642 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2643 VK, &BasePath); 2644 } 2645 2646 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2647 const LookupResult &R, 2648 bool HasTrailingLParen) { 2649 // Only when used directly as the postfix-expression of a call. 2650 if (!HasTrailingLParen) 2651 return false; 2652 2653 // Never if a scope specifier was provided. 2654 if (SS.isSet()) 2655 return false; 2656 2657 // Only in C++ or ObjC++. 2658 if (!getLangOpts().CPlusPlus) 2659 return false; 2660 2661 // Turn off ADL when we find certain kinds of declarations during 2662 // normal lookup: 2663 for (NamedDecl *D : R) { 2664 // C++0x [basic.lookup.argdep]p3: 2665 // -- a declaration of a class member 2666 // Since using decls preserve this property, we check this on the 2667 // original decl. 2668 if (D->isCXXClassMember()) 2669 return false; 2670 2671 // C++0x [basic.lookup.argdep]p3: 2672 // -- a block-scope function declaration that is not a 2673 // using-declaration 2674 // NOTE: we also trigger this for function templates (in fact, we 2675 // don't check the decl type at all, since all other decl types 2676 // turn off ADL anyway). 2677 if (isa<UsingShadowDecl>(D)) 2678 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2679 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2680 return false; 2681 2682 // C++0x [basic.lookup.argdep]p3: 2683 // -- a declaration that is neither a function or a function 2684 // template 2685 // And also for builtin functions. 2686 if (isa<FunctionDecl>(D)) { 2687 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2688 2689 // But also builtin functions. 2690 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2691 return false; 2692 } else if (!isa<FunctionTemplateDecl>(D)) 2693 return false; 2694 } 2695 2696 return true; 2697 } 2698 2699 2700 /// Diagnoses obvious problems with the use of the given declaration 2701 /// as an expression. This is only actually called for lookups that 2702 /// were not overloaded, and it doesn't promise that the declaration 2703 /// will in fact be used. 2704 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2705 if (D->isInvalidDecl()) 2706 return true; 2707 2708 if (isa<TypedefNameDecl>(D)) { 2709 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2710 return true; 2711 } 2712 2713 if (isa<ObjCInterfaceDecl>(D)) { 2714 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2715 return true; 2716 } 2717 2718 if (isa<NamespaceDecl>(D)) { 2719 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2720 return true; 2721 } 2722 2723 return false; 2724 } 2725 2726 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2727 LookupResult &R, bool NeedsADL, 2728 bool AcceptInvalidDecl) { 2729 // If this is a single, fully-resolved result and we don't need ADL, 2730 // just build an ordinary singleton decl ref. 2731 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2732 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2733 R.getRepresentativeDecl(), nullptr, 2734 AcceptInvalidDecl); 2735 2736 // We only need to check the declaration if there's exactly one 2737 // result, because in the overloaded case the results can only be 2738 // functions and function templates. 2739 if (R.isSingleResult() && 2740 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2741 return ExprError(); 2742 2743 // Otherwise, just build an unresolved lookup expression. Suppress 2744 // any lookup-related diagnostics; we'll hash these out later, when 2745 // we've picked a target. 2746 R.suppressDiagnostics(); 2747 2748 UnresolvedLookupExpr *ULE 2749 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2750 SS.getWithLocInContext(Context), 2751 R.getLookupNameInfo(), 2752 NeedsADL, R.isOverloadedResult(), 2753 R.begin(), R.end()); 2754 2755 return ULE; 2756 } 2757 2758 static void 2759 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2760 ValueDecl *var, DeclContext *DC); 2761 2762 /// \brief Complete semantic analysis for a reference to the given declaration. 2763 ExprResult Sema::BuildDeclarationNameExpr( 2764 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2765 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2766 bool AcceptInvalidDecl) { 2767 assert(D && "Cannot refer to a NULL declaration"); 2768 assert(!isa<FunctionTemplateDecl>(D) && 2769 "Cannot refer unambiguously to a function template"); 2770 2771 SourceLocation Loc = NameInfo.getLoc(); 2772 if (CheckDeclInExpr(*this, Loc, D)) 2773 return ExprError(); 2774 2775 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2776 // Specifically diagnose references to class templates that are missing 2777 // a template argument list. 2778 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2779 << Template << SS.getRange(); 2780 Diag(Template->getLocation(), diag::note_template_decl_here); 2781 return ExprError(); 2782 } 2783 2784 // Make sure that we're referring to a value. 2785 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2786 if (!VD) { 2787 Diag(Loc, diag::err_ref_non_value) 2788 << D << SS.getRange(); 2789 Diag(D->getLocation(), diag::note_declared_at); 2790 return ExprError(); 2791 } 2792 2793 // Check whether this declaration can be used. Note that we suppress 2794 // this check when we're going to perform argument-dependent lookup 2795 // on this function name, because this might not be the function 2796 // that overload resolution actually selects. 2797 if (DiagnoseUseOfDecl(VD, Loc)) 2798 return ExprError(); 2799 2800 // Only create DeclRefExpr's for valid Decl's. 2801 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2802 return ExprError(); 2803 2804 // Handle members of anonymous structs and unions. If we got here, 2805 // and the reference is to a class member indirect field, then this 2806 // must be the subject of a pointer-to-member expression. 2807 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2808 if (!indirectField->isCXXClassMember()) 2809 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2810 indirectField); 2811 2812 { 2813 QualType type = VD->getType(); 2814 if (type.isNull()) 2815 return ExprError(); 2816 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2817 // C++ [except.spec]p17: 2818 // An exception-specification is considered to be needed when: 2819 // - in an expression, the function is the unique lookup result or 2820 // the selected member of a set of overloaded functions. 2821 ResolveExceptionSpec(Loc, FPT); 2822 type = VD->getType(); 2823 } 2824 ExprValueKind valueKind = VK_RValue; 2825 2826 switch (D->getKind()) { 2827 // Ignore all the non-ValueDecl kinds. 2828 #define ABSTRACT_DECL(kind) 2829 #define VALUE(type, base) 2830 #define DECL(type, base) \ 2831 case Decl::type: 2832 #include "clang/AST/DeclNodes.inc" 2833 llvm_unreachable("invalid value decl kind"); 2834 2835 // These shouldn't make it here. 2836 case Decl::ObjCAtDefsField: 2837 case Decl::ObjCIvar: 2838 llvm_unreachable("forming non-member reference to ivar?"); 2839 2840 // Enum constants are always r-values and never references. 2841 // Unresolved using declarations are dependent. 2842 case Decl::EnumConstant: 2843 case Decl::UnresolvedUsingValue: 2844 case Decl::OMPDeclareReduction: 2845 valueKind = VK_RValue; 2846 break; 2847 2848 // Fields and indirect fields that got here must be for 2849 // pointer-to-member expressions; we just call them l-values for 2850 // internal consistency, because this subexpression doesn't really 2851 // exist in the high-level semantics. 2852 case Decl::Field: 2853 case Decl::IndirectField: 2854 assert(getLangOpts().CPlusPlus && 2855 "building reference to field in C?"); 2856 2857 // These can't have reference type in well-formed programs, but 2858 // for internal consistency we do this anyway. 2859 type = type.getNonReferenceType(); 2860 valueKind = VK_LValue; 2861 break; 2862 2863 // Non-type template parameters are either l-values or r-values 2864 // depending on the type. 2865 case Decl::NonTypeTemplateParm: { 2866 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2867 type = reftype->getPointeeType(); 2868 valueKind = VK_LValue; // even if the parameter is an r-value reference 2869 break; 2870 } 2871 2872 // For non-references, we need to strip qualifiers just in case 2873 // the template parameter was declared as 'const int' or whatever. 2874 valueKind = VK_RValue; 2875 type = type.getUnqualifiedType(); 2876 break; 2877 } 2878 2879 case Decl::Var: 2880 case Decl::VarTemplateSpecialization: 2881 case Decl::VarTemplatePartialSpecialization: 2882 case Decl::Decomposition: 2883 case Decl::OMPCapturedExpr: 2884 // In C, "extern void blah;" is valid and is an r-value. 2885 if (!getLangOpts().CPlusPlus && 2886 !type.hasQualifiers() && 2887 type->isVoidType()) { 2888 valueKind = VK_RValue; 2889 break; 2890 } 2891 LLVM_FALLTHROUGH; 2892 2893 case Decl::ImplicitParam: 2894 case Decl::ParmVar: { 2895 // These are always l-values. 2896 valueKind = VK_LValue; 2897 type = type.getNonReferenceType(); 2898 2899 // FIXME: Does the addition of const really only apply in 2900 // potentially-evaluated contexts? Since the variable isn't actually 2901 // captured in an unevaluated context, it seems that the answer is no. 2902 if (!isUnevaluatedContext()) { 2903 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2904 if (!CapturedType.isNull()) 2905 type = CapturedType; 2906 } 2907 2908 break; 2909 } 2910 2911 case Decl::Binding: { 2912 // These are always lvalues. 2913 valueKind = VK_LValue; 2914 type = type.getNonReferenceType(); 2915 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2916 // decides how that's supposed to work. 2917 auto *BD = cast<BindingDecl>(VD); 2918 if (BD->getDeclContext()->isFunctionOrMethod() && 2919 BD->getDeclContext() != CurContext) 2920 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2921 break; 2922 } 2923 2924 case Decl::Function: { 2925 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2926 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2927 type = Context.BuiltinFnTy; 2928 valueKind = VK_RValue; 2929 break; 2930 } 2931 } 2932 2933 const FunctionType *fty = type->castAs<FunctionType>(); 2934 2935 // If we're referring to a function with an __unknown_anytype 2936 // result type, make the entire expression __unknown_anytype. 2937 if (fty->getReturnType() == Context.UnknownAnyTy) { 2938 type = Context.UnknownAnyTy; 2939 valueKind = VK_RValue; 2940 break; 2941 } 2942 2943 // Functions are l-values in C++. 2944 if (getLangOpts().CPlusPlus) { 2945 valueKind = VK_LValue; 2946 break; 2947 } 2948 2949 // C99 DR 316 says that, if a function type comes from a 2950 // function definition (without a prototype), that type is only 2951 // used for checking compatibility. Therefore, when referencing 2952 // the function, we pretend that we don't have the full function 2953 // type. 2954 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2955 isa<FunctionProtoType>(fty)) 2956 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2957 fty->getExtInfo()); 2958 2959 // Functions are r-values in C. 2960 valueKind = VK_RValue; 2961 break; 2962 } 2963 2964 case Decl::CXXDeductionGuide: 2965 llvm_unreachable("building reference to deduction guide"); 2966 2967 case Decl::MSProperty: 2968 valueKind = VK_LValue; 2969 break; 2970 2971 case Decl::CXXMethod: 2972 // If we're referring to a method with an __unknown_anytype 2973 // result type, make the entire expression __unknown_anytype. 2974 // This should only be possible with a type written directly. 2975 if (const FunctionProtoType *proto 2976 = dyn_cast<FunctionProtoType>(VD->getType())) 2977 if (proto->getReturnType() == Context.UnknownAnyTy) { 2978 type = Context.UnknownAnyTy; 2979 valueKind = VK_RValue; 2980 break; 2981 } 2982 2983 // C++ methods are l-values if static, r-values if non-static. 2984 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2985 valueKind = VK_LValue; 2986 break; 2987 } 2988 LLVM_FALLTHROUGH; 2989 2990 case Decl::CXXConversion: 2991 case Decl::CXXDestructor: 2992 case Decl::CXXConstructor: 2993 valueKind = VK_RValue; 2994 break; 2995 } 2996 2997 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2998 TemplateArgs); 2999 } 3000 } 3001 3002 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3003 SmallString<32> &Target) { 3004 Target.resize(CharByteWidth * (Source.size() + 1)); 3005 char *ResultPtr = &Target[0]; 3006 const llvm::UTF8 *ErrorPtr; 3007 bool success = 3008 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3009 (void)success; 3010 assert(success); 3011 Target.resize(ResultPtr - &Target[0]); 3012 } 3013 3014 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3015 PredefinedExpr::IdentType IT) { 3016 // Pick the current block, lambda, captured statement or function. 3017 Decl *currentDecl = nullptr; 3018 if (const BlockScopeInfo *BSI = getCurBlock()) 3019 currentDecl = BSI->TheDecl; 3020 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3021 currentDecl = LSI->CallOperator; 3022 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3023 currentDecl = CSI->TheCapturedDecl; 3024 else 3025 currentDecl = getCurFunctionOrMethodDecl(); 3026 3027 if (!currentDecl) { 3028 Diag(Loc, diag::ext_predef_outside_function); 3029 currentDecl = Context.getTranslationUnitDecl(); 3030 } 3031 3032 QualType ResTy; 3033 StringLiteral *SL = nullptr; 3034 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3035 ResTy = Context.DependentTy; 3036 else { 3037 // Pre-defined identifiers are of type char[x], where x is the length of 3038 // the string. 3039 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3040 unsigned Length = Str.length(); 3041 3042 llvm::APInt LengthI(32, Length + 1); 3043 if (IT == PredefinedExpr::LFunction) { 3044 ResTy = Context.WideCharTy.withConst(); 3045 SmallString<32> RawChars; 3046 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3047 Str, RawChars); 3048 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3049 /*IndexTypeQuals*/ 0); 3050 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3051 /*Pascal*/ false, ResTy, Loc); 3052 } else { 3053 ResTy = Context.CharTy.withConst(); 3054 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3055 /*IndexTypeQuals*/ 0); 3056 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3057 /*Pascal*/ false, ResTy, Loc); 3058 } 3059 } 3060 3061 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3062 } 3063 3064 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3065 PredefinedExpr::IdentType IT; 3066 3067 switch (Kind) { 3068 default: llvm_unreachable("Unknown simple primary expr!"); 3069 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3070 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3071 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3072 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3073 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3074 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3075 } 3076 3077 return BuildPredefinedExpr(Loc, IT); 3078 } 3079 3080 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3081 SmallString<16> CharBuffer; 3082 bool Invalid = false; 3083 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3084 if (Invalid) 3085 return ExprError(); 3086 3087 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3088 PP, Tok.getKind()); 3089 if (Literal.hadError()) 3090 return ExprError(); 3091 3092 QualType Ty; 3093 if (Literal.isWide()) 3094 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3095 else if (Literal.isUTF16()) 3096 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3097 else if (Literal.isUTF32()) 3098 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3099 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3100 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3101 else 3102 Ty = Context.CharTy; // 'x' -> char in C++ 3103 3104 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3105 if (Literal.isWide()) 3106 Kind = CharacterLiteral::Wide; 3107 else if (Literal.isUTF16()) 3108 Kind = CharacterLiteral::UTF16; 3109 else if (Literal.isUTF32()) 3110 Kind = CharacterLiteral::UTF32; 3111 else if (Literal.isUTF8()) 3112 Kind = CharacterLiteral::UTF8; 3113 3114 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3115 Tok.getLocation()); 3116 3117 if (Literal.getUDSuffix().empty()) 3118 return Lit; 3119 3120 // We're building a user-defined literal. 3121 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3122 SourceLocation UDSuffixLoc = 3123 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3124 3125 // Make sure we're allowed user-defined literals here. 3126 if (!UDLScope) 3127 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3128 3129 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3130 // operator "" X (ch) 3131 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3132 Lit, Tok.getLocation()); 3133 } 3134 3135 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3136 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3137 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3138 Context.IntTy, Loc); 3139 } 3140 3141 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3142 QualType Ty, SourceLocation Loc) { 3143 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3144 3145 using llvm::APFloat; 3146 APFloat Val(Format); 3147 3148 APFloat::opStatus result = Literal.GetFloatValue(Val); 3149 3150 // Overflow is always an error, but underflow is only an error if 3151 // we underflowed to zero (APFloat reports denormals as underflow). 3152 if ((result & APFloat::opOverflow) || 3153 ((result & APFloat::opUnderflow) && Val.isZero())) { 3154 unsigned diagnostic; 3155 SmallString<20> buffer; 3156 if (result & APFloat::opOverflow) { 3157 diagnostic = diag::warn_float_overflow; 3158 APFloat::getLargest(Format).toString(buffer); 3159 } else { 3160 diagnostic = diag::warn_float_underflow; 3161 APFloat::getSmallest(Format).toString(buffer); 3162 } 3163 3164 S.Diag(Loc, diagnostic) 3165 << Ty 3166 << StringRef(buffer.data(), buffer.size()); 3167 } 3168 3169 bool isExact = (result == APFloat::opOK); 3170 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3171 } 3172 3173 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3174 assert(E && "Invalid expression"); 3175 3176 if (E->isValueDependent()) 3177 return false; 3178 3179 QualType QT = E->getType(); 3180 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3181 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3182 return true; 3183 } 3184 3185 llvm::APSInt ValueAPS; 3186 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3187 3188 if (R.isInvalid()) 3189 return true; 3190 3191 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3192 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3193 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3194 << ValueAPS.toString(10) << ValueIsPositive; 3195 return true; 3196 } 3197 3198 return false; 3199 } 3200 3201 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3202 // Fast path for a single digit (which is quite common). A single digit 3203 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3204 if (Tok.getLength() == 1) { 3205 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3206 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3207 } 3208 3209 SmallString<128> SpellingBuffer; 3210 // NumericLiteralParser wants to overread by one character. Add padding to 3211 // the buffer in case the token is copied to the buffer. If getSpelling() 3212 // returns a StringRef to the memory buffer, it should have a null char at 3213 // the EOF, so it is also safe. 3214 SpellingBuffer.resize(Tok.getLength() + 1); 3215 3216 // Get the spelling of the token, which eliminates trigraphs, etc. 3217 bool Invalid = false; 3218 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3219 if (Invalid) 3220 return ExprError(); 3221 3222 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3223 if (Literal.hadError) 3224 return ExprError(); 3225 3226 if (Literal.hasUDSuffix()) { 3227 // We're building a user-defined literal. 3228 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3229 SourceLocation UDSuffixLoc = 3230 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3231 3232 // Make sure we're allowed user-defined literals here. 3233 if (!UDLScope) 3234 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3235 3236 QualType CookedTy; 3237 if (Literal.isFloatingLiteral()) { 3238 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3239 // long double, the literal is treated as a call of the form 3240 // operator "" X (f L) 3241 CookedTy = Context.LongDoubleTy; 3242 } else { 3243 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3244 // unsigned long long, the literal is treated as a call of the form 3245 // operator "" X (n ULL) 3246 CookedTy = Context.UnsignedLongLongTy; 3247 } 3248 3249 DeclarationName OpName = 3250 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3251 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3252 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3253 3254 SourceLocation TokLoc = Tok.getLocation(); 3255 3256 // Perform literal operator lookup to determine if we're building a raw 3257 // literal or a cooked one. 3258 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3259 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3260 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3261 /*AllowStringTemplate*/ false, 3262 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3263 case LOLR_ErrorNoDiagnostic: 3264 // Lookup failure for imaginary constants isn't fatal, there's still the 3265 // GNU extension producing _Complex types. 3266 break; 3267 case LOLR_Error: 3268 return ExprError(); 3269 case LOLR_Cooked: { 3270 Expr *Lit; 3271 if (Literal.isFloatingLiteral()) { 3272 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3273 } else { 3274 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3275 if (Literal.GetIntegerValue(ResultVal)) 3276 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3277 << /* Unsigned */ 1; 3278 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3279 Tok.getLocation()); 3280 } 3281 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3282 } 3283 3284 case LOLR_Raw: { 3285 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3286 // literal is treated as a call of the form 3287 // operator "" X ("n") 3288 unsigned Length = Literal.getUDSuffixOffset(); 3289 QualType StrTy = Context.getConstantArrayType( 3290 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3291 ArrayType::Normal, 0); 3292 Expr *Lit = StringLiteral::Create( 3293 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3294 /*Pascal*/false, StrTy, &TokLoc, 1); 3295 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3296 } 3297 3298 case LOLR_Template: { 3299 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3300 // template), L is treated as a call fo the form 3301 // operator "" X <'c1', 'c2', ... 'ck'>() 3302 // where n is the source character sequence c1 c2 ... ck. 3303 TemplateArgumentListInfo ExplicitArgs; 3304 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3305 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3306 llvm::APSInt Value(CharBits, CharIsUnsigned); 3307 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3308 Value = TokSpelling[I]; 3309 TemplateArgument Arg(Context, Value, Context.CharTy); 3310 TemplateArgumentLocInfo ArgInfo; 3311 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3312 } 3313 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3314 &ExplicitArgs); 3315 } 3316 case LOLR_StringTemplate: 3317 llvm_unreachable("unexpected literal operator lookup result"); 3318 } 3319 } 3320 3321 Expr *Res; 3322 3323 if (Literal.isFloatingLiteral()) { 3324 QualType Ty; 3325 if (Literal.isHalf){ 3326 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3327 Ty = Context.HalfTy; 3328 else { 3329 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3330 return ExprError(); 3331 } 3332 } else if (Literal.isFloat) 3333 Ty = Context.FloatTy; 3334 else if (Literal.isLong) 3335 Ty = Context.LongDoubleTy; 3336 else if (Literal.isFloat16) 3337 Ty = Context.Float16Ty; 3338 else if (Literal.isFloat128) 3339 Ty = Context.Float128Ty; 3340 else 3341 Ty = Context.DoubleTy; 3342 3343 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3344 3345 if (Ty == Context.DoubleTy) { 3346 if (getLangOpts().SinglePrecisionConstants) { 3347 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3348 if (BTy->getKind() != BuiltinType::Float) { 3349 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3350 } 3351 } else if (getLangOpts().OpenCL && 3352 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3353 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3354 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3355 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3356 } 3357 } 3358 } else if (!Literal.isIntegerLiteral()) { 3359 return ExprError(); 3360 } else { 3361 QualType Ty; 3362 3363 // 'long long' is a C99 or C++11 feature. 3364 if (!getLangOpts().C99 && Literal.isLongLong) { 3365 if (getLangOpts().CPlusPlus) 3366 Diag(Tok.getLocation(), 3367 getLangOpts().CPlusPlus11 ? 3368 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3369 else 3370 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3371 } 3372 3373 // Get the value in the widest-possible width. 3374 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3375 llvm::APInt ResultVal(MaxWidth, 0); 3376 3377 if (Literal.GetIntegerValue(ResultVal)) { 3378 // If this value didn't fit into uintmax_t, error and force to ull. 3379 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3380 << /* Unsigned */ 1; 3381 Ty = Context.UnsignedLongLongTy; 3382 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3383 "long long is not intmax_t?"); 3384 } else { 3385 // If this value fits into a ULL, try to figure out what else it fits into 3386 // according to the rules of C99 6.4.4.1p5. 3387 3388 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3389 // be an unsigned int. 3390 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3391 3392 // Check from smallest to largest, picking the smallest type we can. 3393 unsigned Width = 0; 3394 3395 // Microsoft specific integer suffixes are explicitly sized. 3396 if (Literal.MicrosoftInteger) { 3397 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3398 Width = 8; 3399 Ty = Context.CharTy; 3400 } else { 3401 Width = Literal.MicrosoftInteger; 3402 Ty = Context.getIntTypeForBitwidth(Width, 3403 /*Signed=*/!Literal.isUnsigned); 3404 } 3405 } 3406 3407 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3408 // Are int/unsigned possibilities? 3409 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3410 3411 // Does it fit in a unsigned int? 3412 if (ResultVal.isIntN(IntSize)) { 3413 // Does it fit in a signed int? 3414 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3415 Ty = Context.IntTy; 3416 else if (AllowUnsigned) 3417 Ty = Context.UnsignedIntTy; 3418 Width = IntSize; 3419 } 3420 } 3421 3422 // Are long/unsigned long possibilities? 3423 if (Ty.isNull() && !Literal.isLongLong) { 3424 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3425 3426 // Does it fit in a unsigned long? 3427 if (ResultVal.isIntN(LongSize)) { 3428 // Does it fit in a signed long? 3429 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3430 Ty = Context.LongTy; 3431 else if (AllowUnsigned) 3432 Ty = Context.UnsignedLongTy; 3433 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3434 // is compatible. 3435 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3436 const unsigned LongLongSize = 3437 Context.getTargetInfo().getLongLongWidth(); 3438 Diag(Tok.getLocation(), 3439 getLangOpts().CPlusPlus 3440 ? Literal.isLong 3441 ? diag::warn_old_implicitly_unsigned_long_cxx 3442 : /*C++98 UB*/ diag:: 3443 ext_old_implicitly_unsigned_long_cxx 3444 : diag::warn_old_implicitly_unsigned_long) 3445 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3446 : /*will be ill-formed*/ 1); 3447 Ty = Context.UnsignedLongTy; 3448 } 3449 Width = LongSize; 3450 } 3451 } 3452 3453 // Check long long if needed. 3454 if (Ty.isNull()) { 3455 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3456 3457 // Does it fit in a unsigned long long? 3458 if (ResultVal.isIntN(LongLongSize)) { 3459 // Does it fit in a signed long long? 3460 // To be compatible with MSVC, hex integer literals ending with the 3461 // LL or i64 suffix are always signed in Microsoft mode. 3462 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3463 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3464 Ty = Context.LongLongTy; 3465 else if (AllowUnsigned) 3466 Ty = Context.UnsignedLongLongTy; 3467 Width = LongLongSize; 3468 } 3469 } 3470 3471 // If we still couldn't decide a type, we probably have something that 3472 // does not fit in a signed long long, but has no U suffix. 3473 if (Ty.isNull()) { 3474 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3475 Ty = Context.UnsignedLongLongTy; 3476 Width = Context.getTargetInfo().getLongLongWidth(); 3477 } 3478 3479 if (ResultVal.getBitWidth() != Width) 3480 ResultVal = ResultVal.trunc(Width); 3481 } 3482 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3483 } 3484 3485 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3486 if (Literal.isImaginary) { 3487 Res = new (Context) ImaginaryLiteral(Res, 3488 Context.getComplexType(Res->getType())); 3489 3490 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3491 } 3492 return Res; 3493 } 3494 3495 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3496 assert(E && "ActOnParenExpr() missing expr"); 3497 return new (Context) ParenExpr(L, R, E); 3498 } 3499 3500 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3501 SourceLocation Loc, 3502 SourceRange ArgRange) { 3503 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3504 // scalar or vector data type argument..." 3505 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3506 // type (C99 6.2.5p18) or void. 3507 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3508 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3509 << T << ArgRange; 3510 return true; 3511 } 3512 3513 assert((T->isVoidType() || !T->isIncompleteType()) && 3514 "Scalar types should always be complete"); 3515 return false; 3516 } 3517 3518 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3519 SourceLocation Loc, 3520 SourceRange ArgRange, 3521 UnaryExprOrTypeTrait TraitKind) { 3522 // Invalid types must be hard errors for SFINAE in C++. 3523 if (S.LangOpts.CPlusPlus) 3524 return true; 3525 3526 // C99 6.5.3.4p1: 3527 if (T->isFunctionType() && 3528 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3529 // sizeof(function)/alignof(function) is allowed as an extension. 3530 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3531 << TraitKind << ArgRange; 3532 return false; 3533 } 3534 3535 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3536 // this is an error (OpenCL v1.1 s6.3.k) 3537 if (T->isVoidType()) { 3538 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3539 : diag::ext_sizeof_alignof_void_type; 3540 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3541 return false; 3542 } 3543 3544 return true; 3545 } 3546 3547 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3548 SourceLocation Loc, 3549 SourceRange ArgRange, 3550 UnaryExprOrTypeTrait TraitKind) { 3551 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3552 // runtime doesn't allow it. 3553 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3554 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3555 << T << (TraitKind == UETT_SizeOf) 3556 << ArgRange; 3557 return true; 3558 } 3559 3560 return false; 3561 } 3562 3563 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3564 /// pointer type is equal to T) and emit a warning if it is. 3565 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3566 Expr *E) { 3567 // Don't warn if the operation changed the type. 3568 if (T != E->getType()) 3569 return; 3570 3571 // Now look for array decays. 3572 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3573 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3574 return; 3575 3576 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3577 << ICE->getType() 3578 << ICE->getSubExpr()->getType(); 3579 } 3580 3581 /// \brief Check the constraints on expression operands to unary type expression 3582 /// and type traits. 3583 /// 3584 /// Completes any types necessary and validates the constraints on the operand 3585 /// expression. The logic mostly mirrors the type-based overload, but may modify 3586 /// the expression as it completes the type for that expression through template 3587 /// instantiation, etc. 3588 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3589 UnaryExprOrTypeTrait ExprKind) { 3590 QualType ExprTy = E->getType(); 3591 assert(!ExprTy->isReferenceType()); 3592 3593 if (ExprKind == UETT_VecStep) 3594 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3595 E->getSourceRange()); 3596 3597 // Whitelist some types as extensions 3598 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3599 E->getSourceRange(), ExprKind)) 3600 return false; 3601 3602 // 'alignof' applied to an expression only requires the base element type of 3603 // the expression to be complete. 'sizeof' requires the expression's type to 3604 // be complete (and will attempt to complete it if it's an array of unknown 3605 // bound). 3606 if (ExprKind == UETT_AlignOf) { 3607 if (RequireCompleteType(E->getExprLoc(), 3608 Context.getBaseElementType(E->getType()), 3609 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3610 E->getSourceRange())) 3611 return true; 3612 } else { 3613 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3614 ExprKind, E->getSourceRange())) 3615 return true; 3616 } 3617 3618 // Completing the expression's type may have changed it. 3619 ExprTy = E->getType(); 3620 assert(!ExprTy->isReferenceType()); 3621 3622 if (ExprTy->isFunctionType()) { 3623 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3624 << ExprKind << E->getSourceRange(); 3625 return true; 3626 } 3627 3628 // The operand for sizeof and alignof is in an unevaluated expression context, 3629 // so side effects could result in unintended consequences. 3630 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3631 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3632 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3633 3634 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3635 E->getSourceRange(), ExprKind)) 3636 return true; 3637 3638 if (ExprKind == UETT_SizeOf) { 3639 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3640 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3641 QualType OType = PVD->getOriginalType(); 3642 QualType Type = PVD->getType(); 3643 if (Type->isPointerType() && OType->isArrayType()) { 3644 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3645 << Type << OType; 3646 Diag(PVD->getLocation(), diag::note_declared_at); 3647 } 3648 } 3649 } 3650 3651 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3652 // decays into a pointer and returns an unintended result. This is most 3653 // likely a typo for "sizeof(array) op x". 3654 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3655 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3656 BO->getLHS()); 3657 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3658 BO->getRHS()); 3659 } 3660 } 3661 3662 return false; 3663 } 3664 3665 /// \brief Check the constraints on operands to unary expression and type 3666 /// traits. 3667 /// 3668 /// This will complete any types necessary, and validate the various constraints 3669 /// on those operands. 3670 /// 3671 /// The UsualUnaryConversions() function is *not* called by this routine. 3672 /// C99 6.3.2.1p[2-4] all state: 3673 /// Except when it is the operand of the sizeof operator ... 3674 /// 3675 /// C++ [expr.sizeof]p4 3676 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3677 /// standard conversions are not applied to the operand of sizeof. 3678 /// 3679 /// This policy is followed for all of the unary trait expressions. 3680 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3681 SourceLocation OpLoc, 3682 SourceRange ExprRange, 3683 UnaryExprOrTypeTrait ExprKind) { 3684 if (ExprType->isDependentType()) 3685 return false; 3686 3687 // C++ [expr.sizeof]p2: 3688 // When applied to a reference or a reference type, the result 3689 // is the size of the referenced type. 3690 // C++11 [expr.alignof]p3: 3691 // When alignof is applied to a reference type, the result 3692 // shall be the alignment of the referenced type. 3693 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3694 ExprType = Ref->getPointeeType(); 3695 3696 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3697 // When alignof or _Alignof is applied to an array type, the result 3698 // is the alignment of the element type. 3699 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3700 ExprType = Context.getBaseElementType(ExprType); 3701 3702 if (ExprKind == UETT_VecStep) 3703 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3704 3705 // Whitelist some types as extensions 3706 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3707 ExprKind)) 3708 return false; 3709 3710 if (RequireCompleteType(OpLoc, ExprType, 3711 diag::err_sizeof_alignof_incomplete_type, 3712 ExprKind, ExprRange)) 3713 return true; 3714 3715 if (ExprType->isFunctionType()) { 3716 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3717 << ExprKind << ExprRange; 3718 return true; 3719 } 3720 3721 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3722 ExprKind)) 3723 return true; 3724 3725 return false; 3726 } 3727 3728 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3729 E = E->IgnoreParens(); 3730 3731 // Cannot know anything else if the expression is dependent. 3732 if (E->isTypeDependent()) 3733 return false; 3734 3735 if (E->getObjectKind() == OK_BitField) { 3736 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3737 << 1 << E->getSourceRange(); 3738 return true; 3739 } 3740 3741 ValueDecl *D = nullptr; 3742 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3743 D = DRE->getDecl(); 3744 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3745 D = ME->getMemberDecl(); 3746 } 3747 3748 // If it's a field, require the containing struct to have a 3749 // complete definition so that we can compute the layout. 3750 // 3751 // This can happen in C++11 onwards, either by naming the member 3752 // in a way that is not transformed into a member access expression 3753 // (in an unevaluated operand, for instance), or by naming the member 3754 // in a trailing-return-type. 3755 // 3756 // For the record, since __alignof__ on expressions is a GCC 3757 // extension, GCC seems to permit this but always gives the 3758 // nonsensical answer 0. 3759 // 3760 // We don't really need the layout here --- we could instead just 3761 // directly check for all the appropriate alignment-lowing 3762 // attributes --- but that would require duplicating a lot of 3763 // logic that just isn't worth duplicating for such a marginal 3764 // use-case. 3765 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3766 // Fast path this check, since we at least know the record has a 3767 // definition if we can find a member of it. 3768 if (!FD->getParent()->isCompleteDefinition()) { 3769 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3770 << E->getSourceRange(); 3771 return true; 3772 } 3773 3774 // Otherwise, if it's a field, and the field doesn't have 3775 // reference type, then it must have a complete type (or be a 3776 // flexible array member, which we explicitly want to 3777 // white-list anyway), which makes the following checks trivial. 3778 if (!FD->getType()->isReferenceType()) 3779 return false; 3780 } 3781 3782 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3783 } 3784 3785 bool Sema::CheckVecStepExpr(Expr *E) { 3786 E = E->IgnoreParens(); 3787 3788 // Cannot know anything else if the expression is dependent. 3789 if (E->isTypeDependent()) 3790 return false; 3791 3792 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3793 } 3794 3795 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3796 CapturingScopeInfo *CSI) { 3797 assert(T->isVariablyModifiedType()); 3798 assert(CSI != nullptr); 3799 3800 // We're going to walk down into the type and look for VLA expressions. 3801 do { 3802 const Type *Ty = T.getTypePtr(); 3803 switch (Ty->getTypeClass()) { 3804 #define TYPE(Class, Base) 3805 #define ABSTRACT_TYPE(Class, Base) 3806 #define NON_CANONICAL_TYPE(Class, Base) 3807 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3808 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3809 #include "clang/AST/TypeNodes.def" 3810 T = QualType(); 3811 break; 3812 // These types are never variably-modified. 3813 case Type::Builtin: 3814 case Type::Complex: 3815 case Type::Vector: 3816 case Type::ExtVector: 3817 case Type::Record: 3818 case Type::Enum: 3819 case Type::Elaborated: 3820 case Type::TemplateSpecialization: 3821 case Type::ObjCObject: 3822 case Type::ObjCInterface: 3823 case Type::ObjCObjectPointer: 3824 case Type::ObjCTypeParam: 3825 case Type::Pipe: 3826 llvm_unreachable("type class is never variably-modified!"); 3827 case Type::Adjusted: 3828 T = cast<AdjustedType>(Ty)->getOriginalType(); 3829 break; 3830 case Type::Decayed: 3831 T = cast<DecayedType>(Ty)->getPointeeType(); 3832 break; 3833 case Type::Pointer: 3834 T = cast<PointerType>(Ty)->getPointeeType(); 3835 break; 3836 case Type::BlockPointer: 3837 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3838 break; 3839 case Type::LValueReference: 3840 case Type::RValueReference: 3841 T = cast<ReferenceType>(Ty)->getPointeeType(); 3842 break; 3843 case Type::MemberPointer: 3844 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3845 break; 3846 case Type::ConstantArray: 3847 case Type::IncompleteArray: 3848 // Losing element qualification here is fine. 3849 T = cast<ArrayType>(Ty)->getElementType(); 3850 break; 3851 case Type::VariableArray: { 3852 // Losing element qualification here is fine. 3853 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3854 3855 // Unknown size indication requires no size computation. 3856 // Otherwise, evaluate and record it. 3857 if (auto Size = VAT->getSizeExpr()) { 3858 if (!CSI->isVLATypeCaptured(VAT)) { 3859 RecordDecl *CapRecord = nullptr; 3860 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3861 CapRecord = LSI->Lambda; 3862 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3863 CapRecord = CRSI->TheRecordDecl; 3864 } 3865 if (CapRecord) { 3866 auto ExprLoc = Size->getExprLoc(); 3867 auto SizeType = Context.getSizeType(); 3868 // Build the non-static data member. 3869 auto Field = 3870 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3871 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3872 /*BW*/ nullptr, /*Mutable*/ false, 3873 /*InitStyle*/ ICIS_NoInit); 3874 Field->setImplicit(true); 3875 Field->setAccess(AS_private); 3876 Field->setCapturedVLAType(VAT); 3877 CapRecord->addDecl(Field); 3878 3879 CSI->addVLATypeCapture(ExprLoc, SizeType); 3880 } 3881 } 3882 } 3883 T = VAT->getElementType(); 3884 break; 3885 } 3886 case Type::FunctionProto: 3887 case Type::FunctionNoProto: 3888 T = cast<FunctionType>(Ty)->getReturnType(); 3889 break; 3890 case Type::Paren: 3891 case Type::TypeOf: 3892 case Type::UnaryTransform: 3893 case Type::Attributed: 3894 case Type::SubstTemplateTypeParm: 3895 case Type::PackExpansion: 3896 // Keep walking after single level desugaring. 3897 T = T.getSingleStepDesugaredType(Context); 3898 break; 3899 case Type::Typedef: 3900 T = cast<TypedefType>(Ty)->desugar(); 3901 break; 3902 case Type::Decltype: 3903 T = cast<DecltypeType>(Ty)->desugar(); 3904 break; 3905 case Type::Auto: 3906 case Type::DeducedTemplateSpecialization: 3907 T = cast<DeducedType>(Ty)->getDeducedType(); 3908 break; 3909 case Type::TypeOfExpr: 3910 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3911 break; 3912 case Type::Atomic: 3913 T = cast<AtomicType>(Ty)->getValueType(); 3914 break; 3915 } 3916 } while (!T.isNull() && T->isVariablyModifiedType()); 3917 } 3918 3919 /// \brief Build a sizeof or alignof expression given a type operand. 3920 ExprResult 3921 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3922 SourceLocation OpLoc, 3923 UnaryExprOrTypeTrait ExprKind, 3924 SourceRange R) { 3925 if (!TInfo) 3926 return ExprError(); 3927 3928 QualType T = TInfo->getType(); 3929 3930 if (!T->isDependentType() && 3931 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3932 return ExprError(); 3933 3934 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3935 if (auto *TT = T->getAs<TypedefType>()) { 3936 for (auto I = FunctionScopes.rbegin(), 3937 E = std::prev(FunctionScopes.rend()); 3938 I != E; ++I) { 3939 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3940 if (CSI == nullptr) 3941 break; 3942 DeclContext *DC = nullptr; 3943 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3944 DC = LSI->CallOperator; 3945 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3946 DC = CRSI->TheCapturedDecl; 3947 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3948 DC = BSI->TheDecl; 3949 if (DC) { 3950 if (DC->containsDecl(TT->getDecl())) 3951 break; 3952 captureVariablyModifiedType(Context, T, CSI); 3953 } 3954 } 3955 } 3956 } 3957 3958 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3959 return new (Context) UnaryExprOrTypeTraitExpr( 3960 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3961 } 3962 3963 /// \brief Build a sizeof or alignof expression given an expression 3964 /// operand. 3965 ExprResult 3966 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3967 UnaryExprOrTypeTrait ExprKind) { 3968 ExprResult PE = CheckPlaceholderExpr(E); 3969 if (PE.isInvalid()) 3970 return ExprError(); 3971 3972 E = PE.get(); 3973 3974 // Verify that the operand is valid. 3975 bool isInvalid = false; 3976 if (E->isTypeDependent()) { 3977 // Delay type-checking for type-dependent expressions. 3978 } else if (ExprKind == UETT_AlignOf) { 3979 isInvalid = CheckAlignOfExpr(*this, E); 3980 } else if (ExprKind == UETT_VecStep) { 3981 isInvalid = CheckVecStepExpr(E); 3982 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3983 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3984 isInvalid = true; 3985 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3986 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3987 isInvalid = true; 3988 } else { 3989 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3990 } 3991 3992 if (isInvalid) 3993 return ExprError(); 3994 3995 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3996 PE = TransformToPotentiallyEvaluated(E); 3997 if (PE.isInvalid()) return ExprError(); 3998 E = PE.get(); 3999 } 4000 4001 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4002 return new (Context) UnaryExprOrTypeTraitExpr( 4003 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4004 } 4005 4006 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4007 /// expr and the same for @c alignof and @c __alignof 4008 /// Note that the ArgRange is invalid if isType is false. 4009 ExprResult 4010 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4011 UnaryExprOrTypeTrait ExprKind, bool IsType, 4012 void *TyOrEx, SourceRange ArgRange) { 4013 // If error parsing type, ignore. 4014 if (!TyOrEx) return ExprError(); 4015 4016 if (IsType) { 4017 TypeSourceInfo *TInfo; 4018 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4019 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4020 } 4021 4022 Expr *ArgEx = (Expr *)TyOrEx; 4023 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4024 return Result; 4025 } 4026 4027 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4028 bool IsReal) { 4029 if (V.get()->isTypeDependent()) 4030 return S.Context.DependentTy; 4031 4032 // _Real and _Imag are only l-values for normal l-values. 4033 if (V.get()->getObjectKind() != OK_Ordinary) { 4034 V = S.DefaultLvalueConversion(V.get()); 4035 if (V.isInvalid()) 4036 return QualType(); 4037 } 4038 4039 // These operators return the element type of a complex type. 4040 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4041 return CT->getElementType(); 4042 4043 // Otherwise they pass through real integer and floating point types here. 4044 if (V.get()->getType()->isArithmeticType()) 4045 return V.get()->getType(); 4046 4047 // Test for placeholders. 4048 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4049 if (PR.isInvalid()) return QualType(); 4050 if (PR.get() != V.get()) { 4051 V = PR; 4052 return CheckRealImagOperand(S, V, Loc, IsReal); 4053 } 4054 4055 // Reject anything else. 4056 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4057 << (IsReal ? "__real" : "__imag"); 4058 return QualType(); 4059 } 4060 4061 4062 4063 ExprResult 4064 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4065 tok::TokenKind Kind, Expr *Input) { 4066 UnaryOperatorKind Opc; 4067 switch (Kind) { 4068 default: llvm_unreachable("Unknown unary op!"); 4069 case tok::plusplus: Opc = UO_PostInc; break; 4070 case tok::minusminus: Opc = UO_PostDec; break; 4071 } 4072 4073 // Since this might is a postfix expression, get rid of ParenListExprs. 4074 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4075 if (Result.isInvalid()) return ExprError(); 4076 Input = Result.get(); 4077 4078 return BuildUnaryOp(S, OpLoc, Opc, Input); 4079 } 4080 4081 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4082 /// 4083 /// \return true on error 4084 static bool checkArithmeticOnObjCPointer(Sema &S, 4085 SourceLocation opLoc, 4086 Expr *op) { 4087 assert(op->getType()->isObjCObjectPointerType()); 4088 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4089 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4090 return false; 4091 4092 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4093 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4094 << op->getSourceRange(); 4095 return true; 4096 } 4097 4098 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4099 auto *BaseNoParens = Base->IgnoreParens(); 4100 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4101 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4102 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4103 } 4104 4105 ExprResult 4106 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4107 Expr *idx, SourceLocation rbLoc) { 4108 if (base && !base->getType().isNull() && 4109 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4110 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4111 /*Length=*/nullptr, rbLoc); 4112 4113 // Since this might be a postfix expression, get rid of ParenListExprs. 4114 if (isa<ParenListExpr>(base)) { 4115 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4116 if (result.isInvalid()) return ExprError(); 4117 base = result.get(); 4118 } 4119 4120 // Handle any non-overload placeholder types in the base and index 4121 // expressions. We can't handle overloads here because the other 4122 // operand might be an overloadable type, in which case the overload 4123 // resolution for the operator overload should get the first crack 4124 // at the overload. 4125 bool IsMSPropertySubscript = false; 4126 if (base->getType()->isNonOverloadPlaceholderType()) { 4127 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4128 if (!IsMSPropertySubscript) { 4129 ExprResult result = CheckPlaceholderExpr(base); 4130 if (result.isInvalid()) 4131 return ExprError(); 4132 base = result.get(); 4133 } 4134 } 4135 if (idx->getType()->isNonOverloadPlaceholderType()) { 4136 ExprResult result = CheckPlaceholderExpr(idx); 4137 if (result.isInvalid()) return ExprError(); 4138 idx = result.get(); 4139 } 4140 4141 // Build an unanalyzed expression if either operand is type-dependent. 4142 if (getLangOpts().CPlusPlus && 4143 (base->isTypeDependent() || idx->isTypeDependent())) { 4144 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4145 VK_LValue, OK_Ordinary, rbLoc); 4146 } 4147 4148 // MSDN, property (C++) 4149 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4150 // This attribute can also be used in the declaration of an empty array in a 4151 // class or structure definition. For example: 4152 // __declspec(property(get=GetX, put=PutX)) int x[]; 4153 // The above statement indicates that x[] can be used with one or more array 4154 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4155 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4156 if (IsMSPropertySubscript) { 4157 // Build MS property subscript expression if base is MS property reference 4158 // or MS property subscript. 4159 return new (Context) MSPropertySubscriptExpr( 4160 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4161 } 4162 4163 // Use C++ overloaded-operator rules if either operand has record 4164 // type. The spec says to do this if either type is *overloadable*, 4165 // but enum types can't declare subscript operators or conversion 4166 // operators, so there's nothing interesting for overload resolution 4167 // to do if there aren't any record types involved. 4168 // 4169 // ObjC pointers have their own subscripting logic that is not tied 4170 // to overload resolution and so should not take this path. 4171 if (getLangOpts().CPlusPlus && 4172 (base->getType()->isRecordType() || 4173 (!base->getType()->isObjCObjectPointerType() && 4174 idx->getType()->isRecordType()))) { 4175 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4176 } 4177 4178 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4179 } 4180 4181 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4182 Expr *LowerBound, 4183 SourceLocation ColonLoc, Expr *Length, 4184 SourceLocation RBLoc) { 4185 if (Base->getType()->isPlaceholderType() && 4186 !Base->getType()->isSpecificPlaceholderType( 4187 BuiltinType::OMPArraySection)) { 4188 ExprResult Result = CheckPlaceholderExpr(Base); 4189 if (Result.isInvalid()) 4190 return ExprError(); 4191 Base = Result.get(); 4192 } 4193 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4194 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4195 if (Result.isInvalid()) 4196 return ExprError(); 4197 Result = DefaultLvalueConversion(Result.get()); 4198 if (Result.isInvalid()) 4199 return ExprError(); 4200 LowerBound = Result.get(); 4201 } 4202 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4203 ExprResult Result = CheckPlaceholderExpr(Length); 4204 if (Result.isInvalid()) 4205 return ExprError(); 4206 Result = DefaultLvalueConversion(Result.get()); 4207 if (Result.isInvalid()) 4208 return ExprError(); 4209 Length = Result.get(); 4210 } 4211 4212 // Build an unanalyzed expression if either operand is type-dependent. 4213 if (Base->isTypeDependent() || 4214 (LowerBound && 4215 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4216 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4217 return new (Context) 4218 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4219 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4220 } 4221 4222 // Perform default conversions. 4223 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4224 QualType ResultTy; 4225 if (OriginalTy->isAnyPointerType()) { 4226 ResultTy = OriginalTy->getPointeeType(); 4227 } else if (OriginalTy->isArrayType()) { 4228 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4229 } else { 4230 return ExprError( 4231 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4232 << Base->getSourceRange()); 4233 } 4234 // C99 6.5.2.1p1 4235 if (LowerBound) { 4236 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4237 LowerBound); 4238 if (Res.isInvalid()) 4239 return ExprError(Diag(LowerBound->getExprLoc(), 4240 diag::err_omp_typecheck_section_not_integer) 4241 << 0 << LowerBound->getSourceRange()); 4242 LowerBound = Res.get(); 4243 4244 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4245 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4246 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4247 << 0 << LowerBound->getSourceRange(); 4248 } 4249 if (Length) { 4250 auto Res = 4251 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4252 if (Res.isInvalid()) 4253 return ExprError(Diag(Length->getExprLoc(), 4254 diag::err_omp_typecheck_section_not_integer) 4255 << 1 << Length->getSourceRange()); 4256 Length = Res.get(); 4257 4258 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4259 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4260 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4261 << 1 << Length->getSourceRange(); 4262 } 4263 4264 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4265 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4266 // type. Note that functions are not objects, and that (in C99 parlance) 4267 // incomplete types are not object types. 4268 if (ResultTy->isFunctionType()) { 4269 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4270 << ResultTy << Base->getSourceRange(); 4271 return ExprError(); 4272 } 4273 4274 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4275 diag::err_omp_section_incomplete_type, Base)) 4276 return ExprError(); 4277 4278 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4279 llvm::APSInt LowerBoundValue; 4280 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4281 // OpenMP 4.5, [2.4 Array Sections] 4282 // The array section must be a subset of the original array. 4283 if (LowerBoundValue.isNegative()) { 4284 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4285 << LowerBound->getSourceRange(); 4286 return ExprError(); 4287 } 4288 } 4289 } 4290 4291 if (Length) { 4292 llvm::APSInt LengthValue; 4293 if (Length->EvaluateAsInt(LengthValue, Context)) { 4294 // OpenMP 4.5, [2.4 Array Sections] 4295 // The length must evaluate to non-negative integers. 4296 if (LengthValue.isNegative()) { 4297 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4298 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4299 << Length->getSourceRange(); 4300 return ExprError(); 4301 } 4302 } 4303 } else if (ColonLoc.isValid() && 4304 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4305 !OriginalTy->isVariableArrayType()))) { 4306 // OpenMP 4.5, [2.4 Array Sections] 4307 // When the size of the array dimension is not known, the length must be 4308 // specified explicitly. 4309 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4310 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4311 return ExprError(); 4312 } 4313 4314 if (!Base->getType()->isSpecificPlaceholderType( 4315 BuiltinType::OMPArraySection)) { 4316 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4317 if (Result.isInvalid()) 4318 return ExprError(); 4319 Base = Result.get(); 4320 } 4321 return new (Context) 4322 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4323 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4324 } 4325 4326 ExprResult 4327 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4328 Expr *Idx, SourceLocation RLoc) { 4329 Expr *LHSExp = Base; 4330 Expr *RHSExp = Idx; 4331 4332 ExprValueKind VK = VK_LValue; 4333 ExprObjectKind OK = OK_Ordinary; 4334 4335 // Per C++ core issue 1213, the result is an xvalue if either operand is 4336 // a non-lvalue array, and an lvalue otherwise. 4337 if (getLangOpts().CPlusPlus11 && 4338 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4339 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4340 VK = VK_XValue; 4341 4342 // Perform default conversions. 4343 if (!LHSExp->getType()->getAs<VectorType>()) { 4344 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4345 if (Result.isInvalid()) 4346 return ExprError(); 4347 LHSExp = Result.get(); 4348 } 4349 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4350 if (Result.isInvalid()) 4351 return ExprError(); 4352 RHSExp = Result.get(); 4353 4354 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4355 4356 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4357 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4358 // in the subscript position. As a result, we need to derive the array base 4359 // and index from the expression types. 4360 Expr *BaseExpr, *IndexExpr; 4361 QualType ResultType; 4362 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4363 BaseExpr = LHSExp; 4364 IndexExpr = RHSExp; 4365 ResultType = Context.DependentTy; 4366 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4367 BaseExpr = LHSExp; 4368 IndexExpr = RHSExp; 4369 ResultType = PTy->getPointeeType(); 4370 } else if (const ObjCObjectPointerType *PTy = 4371 LHSTy->getAs<ObjCObjectPointerType>()) { 4372 BaseExpr = LHSExp; 4373 IndexExpr = RHSExp; 4374 4375 // Use custom logic if this should be the pseudo-object subscript 4376 // expression. 4377 if (!LangOpts.isSubscriptPointerArithmetic()) 4378 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4379 nullptr); 4380 4381 ResultType = PTy->getPointeeType(); 4382 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4383 // Handle the uncommon case of "123[Ptr]". 4384 BaseExpr = RHSExp; 4385 IndexExpr = LHSExp; 4386 ResultType = PTy->getPointeeType(); 4387 } else if (const ObjCObjectPointerType *PTy = 4388 RHSTy->getAs<ObjCObjectPointerType>()) { 4389 // Handle the uncommon case of "123[Ptr]". 4390 BaseExpr = RHSExp; 4391 IndexExpr = LHSExp; 4392 ResultType = PTy->getPointeeType(); 4393 if (!LangOpts.isSubscriptPointerArithmetic()) { 4394 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4395 << ResultType << BaseExpr->getSourceRange(); 4396 return ExprError(); 4397 } 4398 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4399 BaseExpr = LHSExp; // vectors: V[123] 4400 IndexExpr = RHSExp; 4401 VK = LHSExp->getValueKind(); 4402 if (VK != VK_RValue) 4403 OK = OK_VectorComponent; 4404 4405 ResultType = VTy->getElementType(); 4406 QualType BaseType = BaseExpr->getType(); 4407 Qualifiers BaseQuals = BaseType.getQualifiers(); 4408 Qualifiers MemberQuals = ResultType.getQualifiers(); 4409 Qualifiers Combined = BaseQuals + MemberQuals; 4410 if (Combined != MemberQuals) 4411 ResultType = Context.getQualifiedType(ResultType, Combined); 4412 } else if (LHSTy->isArrayType()) { 4413 // If we see an array that wasn't promoted by 4414 // DefaultFunctionArrayLvalueConversion, it must be an array that 4415 // wasn't promoted because of the C90 rule that doesn't 4416 // allow promoting non-lvalue arrays. Warn, then 4417 // force the promotion here. 4418 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4419 LHSExp->getSourceRange(); 4420 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4421 CK_ArrayToPointerDecay).get(); 4422 LHSTy = LHSExp->getType(); 4423 4424 BaseExpr = LHSExp; 4425 IndexExpr = RHSExp; 4426 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4427 } else if (RHSTy->isArrayType()) { 4428 // Same as previous, except for 123[f().a] case 4429 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4430 RHSExp->getSourceRange(); 4431 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4432 CK_ArrayToPointerDecay).get(); 4433 RHSTy = RHSExp->getType(); 4434 4435 BaseExpr = RHSExp; 4436 IndexExpr = LHSExp; 4437 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4438 } else { 4439 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4440 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4441 } 4442 // C99 6.5.2.1p1 4443 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4444 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4445 << IndexExpr->getSourceRange()); 4446 4447 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4448 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4449 && !IndexExpr->isTypeDependent()) 4450 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4451 4452 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4453 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4454 // type. Note that Functions are not objects, and that (in C99 parlance) 4455 // incomplete types are not object types. 4456 if (ResultType->isFunctionType()) { 4457 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4458 << ResultType << BaseExpr->getSourceRange(); 4459 return ExprError(); 4460 } 4461 4462 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4463 // GNU extension: subscripting on pointer to void 4464 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4465 << BaseExpr->getSourceRange(); 4466 4467 // C forbids expressions of unqualified void type from being l-values. 4468 // See IsCForbiddenLValueType. 4469 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4470 } else if (!ResultType->isDependentType() && 4471 RequireCompleteType(LLoc, ResultType, 4472 diag::err_subscript_incomplete_type, BaseExpr)) 4473 return ExprError(); 4474 4475 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4476 !ResultType.isCForbiddenLValueType()); 4477 4478 return new (Context) 4479 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4480 } 4481 4482 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4483 ParmVarDecl *Param) { 4484 if (Param->hasUnparsedDefaultArg()) { 4485 Diag(CallLoc, 4486 diag::err_use_of_default_argument_to_function_declared_later) << 4487 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4488 Diag(UnparsedDefaultArgLocs[Param], 4489 diag::note_default_argument_declared_here); 4490 return true; 4491 } 4492 4493 if (Param->hasUninstantiatedDefaultArg()) { 4494 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4495 4496 EnterExpressionEvaluationContext EvalContext( 4497 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4498 4499 // Instantiate the expression. 4500 // 4501 // FIXME: Pass in a correct Pattern argument, otherwise 4502 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4503 // 4504 // template<typename T> 4505 // struct A { 4506 // static int FooImpl(); 4507 // 4508 // template<typename Tp> 4509 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4510 // // template argument list [[T], [Tp]], should be [[Tp]]. 4511 // friend A<Tp> Foo(int a); 4512 // }; 4513 // 4514 // template<typename T> 4515 // A<T> Foo(int a = A<T>::FooImpl()); 4516 MultiLevelTemplateArgumentList MutiLevelArgList 4517 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4518 4519 InstantiatingTemplate Inst(*this, CallLoc, Param, 4520 MutiLevelArgList.getInnermost()); 4521 if (Inst.isInvalid()) 4522 return true; 4523 if (Inst.isAlreadyInstantiating()) { 4524 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4525 Param->setInvalidDecl(); 4526 return true; 4527 } 4528 4529 ExprResult Result; 4530 { 4531 // C++ [dcl.fct.default]p5: 4532 // The names in the [default argument] expression are bound, and 4533 // the semantic constraints are checked, at the point where the 4534 // default argument expression appears. 4535 ContextRAII SavedContext(*this, FD); 4536 LocalInstantiationScope Local(*this); 4537 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4538 /*DirectInit*/false); 4539 } 4540 if (Result.isInvalid()) 4541 return true; 4542 4543 // Check the expression as an initializer for the parameter. 4544 InitializedEntity Entity 4545 = InitializedEntity::InitializeParameter(Context, Param); 4546 InitializationKind Kind 4547 = InitializationKind::CreateCopy(Param->getLocation(), 4548 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4549 Expr *ResultE = Result.getAs<Expr>(); 4550 4551 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4552 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4553 if (Result.isInvalid()) 4554 return true; 4555 4556 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4557 Param->getOuterLocStart()); 4558 if (Result.isInvalid()) 4559 return true; 4560 4561 // Remember the instantiated default argument. 4562 Param->setDefaultArg(Result.getAs<Expr>()); 4563 if (ASTMutationListener *L = getASTMutationListener()) { 4564 L->DefaultArgumentInstantiated(Param); 4565 } 4566 } 4567 4568 // If the default argument expression is not set yet, we are building it now. 4569 if (!Param->hasInit()) { 4570 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4571 Param->setInvalidDecl(); 4572 return true; 4573 } 4574 4575 // If the default expression creates temporaries, we need to 4576 // push them to the current stack of expression temporaries so they'll 4577 // be properly destroyed. 4578 // FIXME: We should really be rebuilding the default argument with new 4579 // bound temporaries; see the comment in PR5810. 4580 // We don't need to do that with block decls, though, because 4581 // blocks in default argument expression can never capture anything. 4582 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4583 // Set the "needs cleanups" bit regardless of whether there are 4584 // any explicit objects. 4585 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4586 4587 // Append all the objects to the cleanup list. Right now, this 4588 // should always be a no-op, because blocks in default argument 4589 // expressions should never be able to capture anything. 4590 assert(!Init->getNumObjects() && 4591 "default argument expression has capturing blocks?"); 4592 } 4593 4594 // We already type-checked the argument, so we know it works. 4595 // Just mark all of the declarations in this potentially-evaluated expression 4596 // as being "referenced". 4597 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4598 /*SkipLocalVariables=*/true); 4599 return false; 4600 } 4601 4602 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4603 FunctionDecl *FD, ParmVarDecl *Param) { 4604 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4605 return ExprError(); 4606 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4607 } 4608 4609 Sema::VariadicCallType 4610 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4611 Expr *Fn) { 4612 if (Proto && Proto->isVariadic()) { 4613 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4614 return VariadicConstructor; 4615 else if (Fn && Fn->getType()->isBlockPointerType()) 4616 return VariadicBlock; 4617 else if (FDecl) { 4618 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4619 if (Method->isInstance()) 4620 return VariadicMethod; 4621 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4622 return VariadicMethod; 4623 return VariadicFunction; 4624 } 4625 return VariadicDoesNotApply; 4626 } 4627 4628 namespace { 4629 class FunctionCallCCC : public FunctionCallFilterCCC { 4630 public: 4631 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4632 unsigned NumArgs, MemberExpr *ME) 4633 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4634 FunctionName(FuncName) {} 4635 4636 bool ValidateCandidate(const TypoCorrection &candidate) override { 4637 if (!candidate.getCorrectionSpecifier() || 4638 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4639 return false; 4640 } 4641 4642 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4643 } 4644 4645 private: 4646 const IdentifierInfo *const FunctionName; 4647 }; 4648 } 4649 4650 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4651 FunctionDecl *FDecl, 4652 ArrayRef<Expr *> Args) { 4653 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4654 DeclarationName FuncName = FDecl->getDeclName(); 4655 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4656 4657 if (TypoCorrection Corrected = S.CorrectTypo( 4658 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4659 S.getScopeForContext(S.CurContext), nullptr, 4660 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4661 Args.size(), ME), 4662 Sema::CTK_ErrorRecovery)) { 4663 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4664 if (Corrected.isOverloaded()) { 4665 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4666 OverloadCandidateSet::iterator Best; 4667 for (NamedDecl *CD : Corrected) { 4668 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4669 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4670 OCS); 4671 } 4672 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4673 case OR_Success: 4674 ND = Best->FoundDecl; 4675 Corrected.setCorrectionDecl(ND); 4676 break; 4677 default: 4678 break; 4679 } 4680 } 4681 ND = ND->getUnderlyingDecl(); 4682 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4683 return Corrected; 4684 } 4685 } 4686 return TypoCorrection(); 4687 } 4688 4689 /// ConvertArgumentsForCall - Converts the arguments specified in 4690 /// Args/NumArgs to the parameter types of the function FDecl with 4691 /// function prototype Proto. Call is the call expression itself, and 4692 /// Fn is the function expression. For a C++ member function, this 4693 /// routine does not attempt to convert the object argument. Returns 4694 /// true if the call is ill-formed. 4695 bool 4696 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4697 FunctionDecl *FDecl, 4698 const FunctionProtoType *Proto, 4699 ArrayRef<Expr *> Args, 4700 SourceLocation RParenLoc, 4701 bool IsExecConfig) { 4702 // Bail out early if calling a builtin with custom typechecking. 4703 if (FDecl) 4704 if (unsigned ID = FDecl->getBuiltinID()) 4705 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4706 return false; 4707 4708 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4709 // assignment, to the types of the corresponding parameter, ... 4710 unsigned NumParams = Proto->getNumParams(); 4711 bool Invalid = false; 4712 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4713 unsigned FnKind = Fn->getType()->isBlockPointerType() 4714 ? 1 /* block */ 4715 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4716 : 0 /* function */); 4717 4718 // If too few arguments are available (and we don't have default 4719 // arguments for the remaining parameters), don't make the call. 4720 if (Args.size() < NumParams) { 4721 if (Args.size() < MinArgs) { 4722 TypoCorrection TC; 4723 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4724 unsigned diag_id = 4725 MinArgs == NumParams && !Proto->isVariadic() 4726 ? diag::err_typecheck_call_too_few_args_suggest 4727 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4728 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4729 << static_cast<unsigned>(Args.size()) 4730 << TC.getCorrectionRange()); 4731 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4732 Diag(RParenLoc, 4733 MinArgs == NumParams && !Proto->isVariadic() 4734 ? diag::err_typecheck_call_too_few_args_one 4735 : diag::err_typecheck_call_too_few_args_at_least_one) 4736 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4737 else 4738 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4739 ? diag::err_typecheck_call_too_few_args 4740 : diag::err_typecheck_call_too_few_args_at_least) 4741 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4742 << Fn->getSourceRange(); 4743 4744 // Emit the location of the prototype. 4745 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4746 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4747 << FDecl; 4748 4749 return true; 4750 } 4751 Call->setNumArgs(Context, NumParams); 4752 } 4753 4754 // If too many are passed and not variadic, error on the extras and drop 4755 // them. 4756 if (Args.size() > NumParams) { 4757 if (!Proto->isVariadic()) { 4758 TypoCorrection TC; 4759 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4760 unsigned diag_id = 4761 MinArgs == NumParams && !Proto->isVariadic() 4762 ? diag::err_typecheck_call_too_many_args_suggest 4763 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4764 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4765 << static_cast<unsigned>(Args.size()) 4766 << TC.getCorrectionRange()); 4767 } else if (NumParams == 1 && FDecl && 4768 FDecl->getParamDecl(0)->getDeclName()) 4769 Diag(Args[NumParams]->getLocStart(), 4770 MinArgs == NumParams 4771 ? diag::err_typecheck_call_too_many_args_one 4772 : diag::err_typecheck_call_too_many_args_at_most_one) 4773 << FnKind << FDecl->getParamDecl(0) 4774 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4775 << SourceRange(Args[NumParams]->getLocStart(), 4776 Args.back()->getLocEnd()); 4777 else 4778 Diag(Args[NumParams]->getLocStart(), 4779 MinArgs == NumParams 4780 ? diag::err_typecheck_call_too_many_args 4781 : diag::err_typecheck_call_too_many_args_at_most) 4782 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4783 << Fn->getSourceRange() 4784 << SourceRange(Args[NumParams]->getLocStart(), 4785 Args.back()->getLocEnd()); 4786 4787 // Emit the location of the prototype. 4788 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4789 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4790 << FDecl; 4791 4792 // This deletes the extra arguments. 4793 Call->setNumArgs(Context, NumParams); 4794 return true; 4795 } 4796 } 4797 SmallVector<Expr *, 8> AllArgs; 4798 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4799 4800 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4801 Proto, 0, Args, AllArgs, CallType); 4802 if (Invalid) 4803 return true; 4804 unsigned TotalNumArgs = AllArgs.size(); 4805 for (unsigned i = 0; i < TotalNumArgs; ++i) 4806 Call->setArg(i, AllArgs[i]); 4807 4808 return false; 4809 } 4810 4811 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4812 const FunctionProtoType *Proto, 4813 unsigned FirstParam, ArrayRef<Expr *> Args, 4814 SmallVectorImpl<Expr *> &AllArgs, 4815 VariadicCallType CallType, bool AllowExplicit, 4816 bool IsListInitialization) { 4817 unsigned NumParams = Proto->getNumParams(); 4818 bool Invalid = false; 4819 size_t ArgIx = 0; 4820 // Continue to check argument types (even if we have too few/many args). 4821 for (unsigned i = FirstParam; i < NumParams; i++) { 4822 QualType ProtoArgType = Proto->getParamType(i); 4823 4824 Expr *Arg; 4825 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4826 if (ArgIx < Args.size()) { 4827 Arg = Args[ArgIx++]; 4828 4829 if (RequireCompleteType(Arg->getLocStart(), 4830 ProtoArgType, 4831 diag::err_call_incomplete_argument, Arg)) 4832 return true; 4833 4834 // Strip the unbridged-cast placeholder expression off, if applicable. 4835 bool CFAudited = false; 4836 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4837 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4838 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4839 Arg = stripARCUnbridgedCast(Arg); 4840 else if (getLangOpts().ObjCAutoRefCount && 4841 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4842 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4843 CFAudited = true; 4844 4845 if (Proto->getExtParameterInfo(i).isNoEscape()) 4846 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4847 BE->getBlockDecl()->setDoesNotEscape(); 4848 4849 InitializedEntity Entity = 4850 Param ? InitializedEntity::InitializeParameter(Context, Param, 4851 ProtoArgType) 4852 : InitializedEntity::InitializeParameter( 4853 Context, ProtoArgType, Proto->isParamConsumed(i)); 4854 4855 // Remember that parameter belongs to a CF audited API. 4856 if (CFAudited) 4857 Entity.setParameterCFAudited(); 4858 4859 ExprResult ArgE = PerformCopyInitialization( 4860 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4861 if (ArgE.isInvalid()) 4862 return true; 4863 4864 Arg = ArgE.getAs<Expr>(); 4865 } else { 4866 assert(Param && "can't use default arguments without a known callee"); 4867 4868 ExprResult ArgExpr = 4869 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4870 if (ArgExpr.isInvalid()) 4871 return true; 4872 4873 Arg = ArgExpr.getAs<Expr>(); 4874 } 4875 4876 // Check for array bounds violations for each argument to the call. This 4877 // check only triggers warnings when the argument isn't a more complex Expr 4878 // with its own checking, such as a BinaryOperator. 4879 CheckArrayAccess(Arg); 4880 4881 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4882 CheckStaticArrayArgument(CallLoc, Param, Arg); 4883 4884 AllArgs.push_back(Arg); 4885 } 4886 4887 // If this is a variadic call, handle args passed through "...". 4888 if (CallType != VariadicDoesNotApply) { 4889 // Assume that extern "C" functions with variadic arguments that 4890 // return __unknown_anytype aren't *really* variadic. 4891 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4892 FDecl->isExternC()) { 4893 for (Expr *A : Args.slice(ArgIx)) { 4894 QualType paramType; // ignored 4895 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4896 Invalid |= arg.isInvalid(); 4897 AllArgs.push_back(arg.get()); 4898 } 4899 4900 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4901 } else { 4902 for (Expr *A : Args.slice(ArgIx)) { 4903 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4904 Invalid |= Arg.isInvalid(); 4905 AllArgs.push_back(Arg.get()); 4906 } 4907 } 4908 4909 // Check for array bounds violations. 4910 for (Expr *A : Args.slice(ArgIx)) 4911 CheckArrayAccess(A); 4912 } 4913 return Invalid; 4914 } 4915 4916 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4917 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4918 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4919 TL = DTL.getOriginalLoc(); 4920 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4921 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4922 << ATL.getLocalSourceRange(); 4923 } 4924 4925 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4926 /// array parameter, check that it is non-null, and that if it is formed by 4927 /// array-to-pointer decay, the underlying array is sufficiently large. 4928 /// 4929 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4930 /// array type derivation, then for each call to the function, the value of the 4931 /// corresponding actual argument shall provide access to the first element of 4932 /// an array with at least as many elements as specified by the size expression. 4933 void 4934 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4935 ParmVarDecl *Param, 4936 const Expr *ArgExpr) { 4937 // Static array parameters are not supported in C++. 4938 if (!Param || getLangOpts().CPlusPlus) 4939 return; 4940 4941 QualType OrigTy = Param->getOriginalType(); 4942 4943 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4944 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4945 return; 4946 4947 if (ArgExpr->isNullPointerConstant(Context, 4948 Expr::NPC_NeverValueDependent)) { 4949 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4950 DiagnoseCalleeStaticArrayParam(*this, Param); 4951 return; 4952 } 4953 4954 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4955 if (!CAT) 4956 return; 4957 4958 const ConstantArrayType *ArgCAT = 4959 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4960 if (!ArgCAT) 4961 return; 4962 4963 if (ArgCAT->getSize().ult(CAT->getSize())) { 4964 Diag(CallLoc, diag::warn_static_array_too_small) 4965 << ArgExpr->getSourceRange() 4966 << (unsigned) ArgCAT->getSize().getZExtValue() 4967 << (unsigned) CAT->getSize().getZExtValue(); 4968 DiagnoseCalleeStaticArrayParam(*this, Param); 4969 } 4970 } 4971 4972 /// Given a function expression of unknown-any type, try to rebuild it 4973 /// to have a function type. 4974 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4975 4976 /// Is the given type a placeholder that we need to lower out 4977 /// immediately during argument processing? 4978 static bool isPlaceholderToRemoveAsArg(QualType type) { 4979 // Placeholders are never sugared. 4980 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4981 if (!placeholder) return false; 4982 4983 switch (placeholder->getKind()) { 4984 // Ignore all the non-placeholder types. 4985 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4986 case BuiltinType::Id: 4987 #include "clang/Basic/OpenCLImageTypes.def" 4988 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4989 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4990 #include "clang/AST/BuiltinTypes.def" 4991 return false; 4992 4993 // We cannot lower out overload sets; they might validly be resolved 4994 // by the call machinery. 4995 case BuiltinType::Overload: 4996 return false; 4997 4998 // Unbridged casts in ARC can be handled in some call positions and 4999 // should be left in place. 5000 case BuiltinType::ARCUnbridgedCast: 5001 return false; 5002 5003 // Pseudo-objects should be converted as soon as possible. 5004 case BuiltinType::PseudoObject: 5005 return true; 5006 5007 // The debugger mode could theoretically but currently does not try 5008 // to resolve unknown-typed arguments based on known parameter types. 5009 case BuiltinType::UnknownAny: 5010 return true; 5011 5012 // These are always invalid as call arguments and should be reported. 5013 case BuiltinType::BoundMember: 5014 case BuiltinType::BuiltinFn: 5015 case BuiltinType::OMPArraySection: 5016 return true; 5017 5018 } 5019 llvm_unreachable("bad builtin type kind"); 5020 } 5021 5022 /// Check an argument list for placeholders that we won't try to 5023 /// handle later. 5024 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5025 // Apply this processing to all the arguments at once instead of 5026 // dying at the first failure. 5027 bool hasInvalid = false; 5028 for (size_t i = 0, e = args.size(); i != e; i++) { 5029 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5030 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5031 if (result.isInvalid()) hasInvalid = true; 5032 else args[i] = result.get(); 5033 } else if (hasInvalid) { 5034 (void)S.CorrectDelayedTyposInExpr(args[i]); 5035 } 5036 } 5037 return hasInvalid; 5038 } 5039 5040 /// If a builtin function has a pointer argument with no explicit address 5041 /// space, then it should be able to accept a pointer to any address 5042 /// space as input. In order to do this, we need to replace the 5043 /// standard builtin declaration with one that uses the same address space 5044 /// as the call. 5045 /// 5046 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5047 /// it does not contain any pointer arguments without 5048 /// an address space qualifer. Otherwise the rewritten 5049 /// FunctionDecl is returned. 5050 /// TODO: Handle pointer return types. 5051 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5052 const FunctionDecl *FDecl, 5053 MultiExprArg ArgExprs) { 5054 5055 QualType DeclType = FDecl->getType(); 5056 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5057 5058 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5059 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5060 return nullptr; 5061 5062 bool NeedsNewDecl = false; 5063 unsigned i = 0; 5064 SmallVector<QualType, 8> OverloadParams; 5065 5066 for (QualType ParamType : FT->param_types()) { 5067 5068 // Convert array arguments to pointer to simplify type lookup. 5069 ExprResult ArgRes = 5070 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5071 if (ArgRes.isInvalid()) 5072 return nullptr; 5073 Expr *Arg = ArgRes.get(); 5074 QualType ArgType = Arg->getType(); 5075 if (!ParamType->isPointerType() || 5076 ParamType.getQualifiers().hasAddressSpace() || 5077 !ArgType->isPointerType() || 5078 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5079 OverloadParams.push_back(ParamType); 5080 continue; 5081 } 5082 5083 NeedsNewDecl = true; 5084 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5085 5086 QualType PointeeType = ParamType->getPointeeType(); 5087 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5088 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5089 } 5090 5091 if (!NeedsNewDecl) 5092 return nullptr; 5093 5094 FunctionProtoType::ExtProtoInfo EPI; 5095 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5096 OverloadParams, EPI); 5097 DeclContext *Parent = Context.getTranslationUnitDecl(); 5098 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5099 FDecl->getLocation(), 5100 FDecl->getLocation(), 5101 FDecl->getIdentifier(), 5102 OverloadTy, 5103 /*TInfo=*/nullptr, 5104 SC_Extern, false, 5105 /*hasPrototype=*/true); 5106 SmallVector<ParmVarDecl*, 16> Params; 5107 FT = cast<FunctionProtoType>(OverloadTy); 5108 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5109 QualType ParamType = FT->getParamType(i); 5110 ParmVarDecl *Parm = 5111 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5112 SourceLocation(), nullptr, ParamType, 5113 /*TInfo=*/nullptr, SC_None, nullptr); 5114 Parm->setScopeInfo(0, i); 5115 Params.push_back(Parm); 5116 } 5117 OverloadDecl->setParams(Params); 5118 return OverloadDecl; 5119 } 5120 5121 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5122 FunctionDecl *Callee, 5123 MultiExprArg ArgExprs) { 5124 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5125 // similar attributes) really don't like it when functions are called with an 5126 // invalid number of args. 5127 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5128 /*PartialOverloading=*/false) && 5129 !Callee->isVariadic()) 5130 return; 5131 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5132 return; 5133 5134 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5135 S.Diag(Fn->getLocStart(), 5136 isa<CXXMethodDecl>(Callee) 5137 ? diag::err_ovl_no_viable_member_function_in_call 5138 : diag::err_ovl_no_viable_function_in_call) 5139 << Callee << Callee->getSourceRange(); 5140 S.Diag(Callee->getLocation(), 5141 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5142 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5143 return; 5144 } 5145 } 5146 5147 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5148 const UnresolvedMemberExpr *const UME, Sema &S) { 5149 5150 const auto GetFunctionLevelDCIfCXXClass = 5151 [](Sema &S) -> const CXXRecordDecl * { 5152 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5153 if (!DC || !DC->getParent()) 5154 return nullptr; 5155 5156 // If the call to some member function was made from within a member 5157 // function body 'M' return return 'M's parent. 5158 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5159 return MD->getParent()->getCanonicalDecl(); 5160 // else the call was made from within a default member initializer of a 5161 // class, so return the class. 5162 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5163 return RD->getCanonicalDecl(); 5164 return nullptr; 5165 }; 5166 // If our DeclContext is neither a member function nor a class (in the 5167 // case of a lambda in a default member initializer), we can't have an 5168 // enclosing 'this'. 5169 5170 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5171 if (!CurParentClass) 5172 return false; 5173 5174 // The naming class for implicit member functions call is the class in which 5175 // name lookup starts. 5176 const CXXRecordDecl *const NamingClass = 5177 UME->getNamingClass()->getCanonicalDecl(); 5178 assert(NamingClass && "Must have naming class even for implicit access"); 5179 5180 // If the unresolved member functions were found in a 'naming class' that is 5181 // related (either the same or derived from) to the class that contains the 5182 // member function that itself contained the implicit member access. 5183 5184 return CurParentClass == NamingClass || 5185 CurParentClass->isDerivedFrom(NamingClass); 5186 } 5187 5188 static void 5189 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5190 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5191 5192 if (!UME) 5193 return; 5194 5195 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5196 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5197 // already been captured, or if this is an implicit member function call (if 5198 // it isn't, an attempt to capture 'this' should already have been made). 5199 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5200 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5201 return; 5202 5203 // Check if the naming class in which the unresolved members were found is 5204 // related (same as or is a base of) to the enclosing class. 5205 5206 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5207 return; 5208 5209 5210 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5211 // If the enclosing function is not dependent, then this lambda is 5212 // capture ready, so if we can capture this, do so. 5213 if (!EnclosingFunctionCtx->isDependentContext()) { 5214 // If the current lambda and all enclosing lambdas can capture 'this' - 5215 // then go ahead and capture 'this' (since our unresolved overload set 5216 // contains at least one non-static member function). 5217 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5218 S.CheckCXXThisCapture(CallLoc); 5219 } else if (S.CurContext->isDependentContext()) { 5220 // ... since this is an implicit member reference, that might potentially 5221 // involve a 'this' capture, mark 'this' for potential capture in 5222 // enclosing lambdas. 5223 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5224 CurLSI->addPotentialThisCapture(CallLoc); 5225 } 5226 } 5227 5228 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5229 /// This provides the location of the left/right parens and a list of comma 5230 /// locations. 5231 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5232 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5233 Expr *ExecConfig, bool IsExecConfig) { 5234 // Since this might be a postfix expression, get rid of ParenListExprs. 5235 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5236 if (Result.isInvalid()) return ExprError(); 5237 Fn = Result.get(); 5238 5239 if (checkArgsForPlaceholders(*this, ArgExprs)) 5240 return ExprError(); 5241 5242 if (getLangOpts().CPlusPlus) { 5243 // If this is a pseudo-destructor expression, build the call immediately. 5244 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5245 if (!ArgExprs.empty()) { 5246 // Pseudo-destructor calls should not have any arguments. 5247 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5248 << FixItHint::CreateRemoval( 5249 SourceRange(ArgExprs.front()->getLocStart(), 5250 ArgExprs.back()->getLocEnd())); 5251 } 5252 5253 return new (Context) 5254 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5255 } 5256 if (Fn->getType() == Context.PseudoObjectTy) { 5257 ExprResult result = CheckPlaceholderExpr(Fn); 5258 if (result.isInvalid()) return ExprError(); 5259 Fn = result.get(); 5260 } 5261 5262 // Determine whether this is a dependent call inside a C++ template, 5263 // in which case we won't do any semantic analysis now. 5264 bool Dependent = false; 5265 if (Fn->isTypeDependent()) 5266 Dependent = true; 5267 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5268 Dependent = true; 5269 5270 if (Dependent) { 5271 if (ExecConfig) { 5272 return new (Context) CUDAKernelCallExpr( 5273 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5274 Context.DependentTy, VK_RValue, RParenLoc); 5275 } else { 5276 5277 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5278 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5279 Fn->getLocStart()); 5280 5281 return new (Context) CallExpr( 5282 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5283 } 5284 } 5285 5286 // Determine whether this is a call to an object (C++ [over.call.object]). 5287 if (Fn->getType()->isRecordType()) 5288 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5289 RParenLoc); 5290 5291 if (Fn->getType() == Context.UnknownAnyTy) { 5292 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5293 if (result.isInvalid()) return ExprError(); 5294 Fn = result.get(); 5295 } 5296 5297 if (Fn->getType() == Context.BoundMemberTy) { 5298 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5299 RParenLoc); 5300 } 5301 } 5302 5303 // Check for overloaded calls. This can happen even in C due to extensions. 5304 if (Fn->getType() == Context.OverloadTy) { 5305 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5306 5307 // We aren't supposed to apply this logic if there's an '&' involved. 5308 if (!find.HasFormOfMemberPointer) { 5309 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5310 return new (Context) CallExpr( 5311 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5312 OverloadExpr *ovl = find.Expression; 5313 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5314 return BuildOverloadedCallExpr( 5315 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5316 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5317 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5318 RParenLoc); 5319 } 5320 } 5321 5322 // If we're directly calling a function, get the appropriate declaration. 5323 if (Fn->getType() == Context.UnknownAnyTy) { 5324 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5325 if (result.isInvalid()) return ExprError(); 5326 Fn = result.get(); 5327 } 5328 5329 Expr *NakedFn = Fn->IgnoreParens(); 5330 5331 bool CallingNDeclIndirectly = false; 5332 NamedDecl *NDecl = nullptr; 5333 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5334 if (UnOp->getOpcode() == UO_AddrOf) { 5335 CallingNDeclIndirectly = true; 5336 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5337 } 5338 } 5339 5340 if (isa<DeclRefExpr>(NakedFn)) { 5341 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5342 5343 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5344 if (FDecl && FDecl->getBuiltinID()) { 5345 // Rewrite the function decl for this builtin by replacing parameters 5346 // with no explicit address space with the address space of the arguments 5347 // in ArgExprs. 5348 if ((FDecl = 5349 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5350 NDecl = FDecl; 5351 Fn = DeclRefExpr::Create( 5352 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5353 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5354 } 5355 } 5356 } else if (isa<MemberExpr>(NakedFn)) 5357 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5358 5359 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5360 if (CallingNDeclIndirectly && 5361 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5362 Fn->getLocStart())) 5363 return ExprError(); 5364 5365 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5366 return ExprError(); 5367 5368 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5369 } 5370 5371 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5372 ExecConfig, IsExecConfig); 5373 } 5374 5375 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5376 /// 5377 /// __builtin_astype( value, dst type ) 5378 /// 5379 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5380 SourceLocation BuiltinLoc, 5381 SourceLocation RParenLoc) { 5382 ExprValueKind VK = VK_RValue; 5383 ExprObjectKind OK = OK_Ordinary; 5384 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5385 QualType SrcTy = E->getType(); 5386 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5387 return ExprError(Diag(BuiltinLoc, 5388 diag::err_invalid_astype_of_different_size) 5389 << DstTy 5390 << SrcTy 5391 << E->getSourceRange()); 5392 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5393 } 5394 5395 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5396 /// provided arguments. 5397 /// 5398 /// __builtin_convertvector( value, dst type ) 5399 /// 5400 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5401 SourceLocation BuiltinLoc, 5402 SourceLocation RParenLoc) { 5403 TypeSourceInfo *TInfo; 5404 GetTypeFromParser(ParsedDestTy, &TInfo); 5405 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5406 } 5407 5408 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5409 /// i.e. an expression not of \p OverloadTy. The expression should 5410 /// unary-convert to an expression of function-pointer or 5411 /// block-pointer type. 5412 /// 5413 /// \param NDecl the declaration being called, if available 5414 ExprResult 5415 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5416 SourceLocation LParenLoc, 5417 ArrayRef<Expr *> Args, 5418 SourceLocation RParenLoc, 5419 Expr *Config, bool IsExecConfig) { 5420 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5421 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5422 5423 // Functions with 'interrupt' attribute cannot be called directly. 5424 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5425 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5426 return ExprError(); 5427 } 5428 5429 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5430 // so there's some risk when calling out to non-interrupt handler functions 5431 // that the callee might not preserve them. This is easy to diagnose here, 5432 // but can be very challenging to debug. 5433 if (auto *Caller = getCurFunctionDecl()) 5434 if (Caller->hasAttr<ARMInterruptAttr>()) { 5435 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5436 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5437 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5438 } 5439 5440 // Promote the function operand. 5441 // We special-case function promotion here because we only allow promoting 5442 // builtin functions to function pointers in the callee of a call. 5443 ExprResult Result; 5444 if (BuiltinID && 5445 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5446 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5447 CK_BuiltinFnToFnPtr).get(); 5448 } else { 5449 Result = CallExprUnaryConversions(Fn); 5450 } 5451 if (Result.isInvalid()) 5452 return ExprError(); 5453 Fn = Result.get(); 5454 5455 // Make the call expr early, before semantic checks. This guarantees cleanup 5456 // of arguments and function on error. 5457 CallExpr *TheCall; 5458 if (Config) 5459 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5460 cast<CallExpr>(Config), Args, 5461 Context.BoolTy, VK_RValue, 5462 RParenLoc); 5463 else 5464 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5465 VK_RValue, RParenLoc); 5466 5467 if (!getLangOpts().CPlusPlus) { 5468 // C cannot always handle TypoExpr nodes in builtin calls and direct 5469 // function calls as their argument checking don't necessarily handle 5470 // dependent types properly, so make sure any TypoExprs have been 5471 // dealt with. 5472 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5473 if (!Result.isUsable()) return ExprError(); 5474 TheCall = dyn_cast<CallExpr>(Result.get()); 5475 if (!TheCall) return Result; 5476 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5477 } 5478 5479 // Bail out early if calling a builtin with custom typechecking. 5480 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5481 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5482 5483 retry: 5484 const FunctionType *FuncT; 5485 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5486 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5487 // have type pointer to function". 5488 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5489 if (!FuncT) 5490 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5491 << Fn->getType() << Fn->getSourceRange()); 5492 } else if (const BlockPointerType *BPT = 5493 Fn->getType()->getAs<BlockPointerType>()) { 5494 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5495 } else { 5496 // Handle calls to expressions of unknown-any type. 5497 if (Fn->getType() == Context.UnknownAnyTy) { 5498 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5499 if (rewrite.isInvalid()) return ExprError(); 5500 Fn = rewrite.get(); 5501 TheCall->setCallee(Fn); 5502 goto retry; 5503 } 5504 5505 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5506 << Fn->getType() << Fn->getSourceRange()); 5507 } 5508 5509 if (getLangOpts().CUDA) { 5510 if (Config) { 5511 // CUDA: Kernel calls must be to global functions 5512 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5513 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5514 << FDecl->getName() << Fn->getSourceRange()); 5515 5516 // CUDA: Kernel function must have 'void' return type 5517 if (!FuncT->getReturnType()->isVoidType()) 5518 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5519 << Fn->getType() << Fn->getSourceRange()); 5520 } else { 5521 // CUDA: Calls to global functions must be configured 5522 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5523 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5524 << FDecl->getName() << Fn->getSourceRange()); 5525 } 5526 } 5527 5528 // Check for a valid return type 5529 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5530 FDecl)) 5531 return ExprError(); 5532 5533 // We know the result type of the call, set it. 5534 TheCall->setType(FuncT->getCallResultType(Context)); 5535 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5536 5537 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5538 if (Proto) { 5539 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5540 IsExecConfig)) 5541 return ExprError(); 5542 } else { 5543 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5544 5545 if (FDecl) { 5546 // Check if we have too few/too many template arguments, based 5547 // on our knowledge of the function definition. 5548 const FunctionDecl *Def = nullptr; 5549 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5550 Proto = Def->getType()->getAs<FunctionProtoType>(); 5551 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5552 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5553 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5554 } 5555 5556 // If the function we're calling isn't a function prototype, but we have 5557 // a function prototype from a prior declaratiom, use that prototype. 5558 if (!FDecl->hasPrototype()) 5559 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5560 } 5561 5562 // Promote the arguments (C99 6.5.2.2p6). 5563 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5564 Expr *Arg = Args[i]; 5565 5566 if (Proto && i < Proto->getNumParams()) { 5567 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5568 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5569 ExprResult ArgE = 5570 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5571 if (ArgE.isInvalid()) 5572 return true; 5573 5574 Arg = ArgE.getAs<Expr>(); 5575 5576 } else { 5577 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5578 5579 if (ArgE.isInvalid()) 5580 return true; 5581 5582 Arg = ArgE.getAs<Expr>(); 5583 } 5584 5585 if (RequireCompleteType(Arg->getLocStart(), 5586 Arg->getType(), 5587 diag::err_call_incomplete_argument, Arg)) 5588 return ExprError(); 5589 5590 TheCall->setArg(i, Arg); 5591 } 5592 } 5593 5594 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5595 if (!Method->isStatic()) 5596 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5597 << Fn->getSourceRange()); 5598 5599 // Check for sentinels 5600 if (NDecl) 5601 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5602 5603 // Do special checking on direct calls to functions. 5604 if (FDecl) { 5605 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5606 return ExprError(); 5607 5608 if (BuiltinID) 5609 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5610 } else if (NDecl) { 5611 if (CheckPointerCall(NDecl, TheCall, Proto)) 5612 return ExprError(); 5613 } else { 5614 if (CheckOtherCall(TheCall, Proto)) 5615 return ExprError(); 5616 } 5617 5618 return MaybeBindToTemporary(TheCall); 5619 } 5620 5621 ExprResult 5622 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5623 SourceLocation RParenLoc, Expr *InitExpr) { 5624 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5625 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5626 5627 TypeSourceInfo *TInfo; 5628 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5629 if (!TInfo) 5630 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5631 5632 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5633 } 5634 5635 ExprResult 5636 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5637 SourceLocation RParenLoc, Expr *LiteralExpr) { 5638 QualType literalType = TInfo->getType(); 5639 5640 if (literalType->isArrayType()) { 5641 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5642 diag::err_illegal_decl_array_incomplete_type, 5643 SourceRange(LParenLoc, 5644 LiteralExpr->getSourceRange().getEnd()))) 5645 return ExprError(); 5646 if (literalType->isVariableArrayType()) 5647 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5648 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5649 } else if (!literalType->isDependentType() && 5650 RequireCompleteType(LParenLoc, literalType, 5651 diag::err_typecheck_decl_incomplete_type, 5652 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5653 return ExprError(); 5654 5655 InitializedEntity Entity 5656 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5657 InitializationKind Kind 5658 = InitializationKind::CreateCStyleCast(LParenLoc, 5659 SourceRange(LParenLoc, RParenLoc), 5660 /*InitList=*/true); 5661 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5662 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5663 &literalType); 5664 if (Result.isInvalid()) 5665 return ExprError(); 5666 LiteralExpr = Result.get(); 5667 5668 bool isFileScope = !CurContext->isFunctionOrMethod(); 5669 if (isFileScope && 5670 !LiteralExpr->isTypeDependent() && 5671 !LiteralExpr->isValueDependent() && 5672 !literalType->isDependentType()) { // 6.5.2.5p3 5673 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5674 return ExprError(); 5675 } 5676 5677 // In C, compound literals are l-values for some reason. 5678 // For GCC compatibility, in C++, file-scope array compound literals with 5679 // constant initializers are also l-values, and compound literals are 5680 // otherwise prvalues. 5681 // 5682 // (GCC also treats C++ list-initialized file-scope array prvalues with 5683 // constant initializers as l-values, but that's non-conforming, so we don't 5684 // follow it there.) 5685 // 5686 // FIXME: It would be better to handle the lvalue cases as materializing and 5687 // lifetime-extending a temporary object, but our materialized temporaries 5688 // representation only supports lifetime extension from a variable, not "out 5689 // of thin air". 5690 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5691 // is bound to the result of applying array-to-pointer decay to the compound 5692 // literal. 5693 // FIXME: GCC supports compound literals of reference type, which should 5694 // obviously have a value kind derived from the kind of reference involved. 5695 ExprValueKind VK = 5696 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5697 ? VK_RValue 5698 : VK_LValue; 5699 5700 return MaybeBindToTemporary( 5701 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5702 VK, LiteralExpr, isFileScope)); 5703 } 5704 5705 ExprResult 5706 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5707 SourceLocation RBraceLoc) { 5708 // Immediately handle non-overload placeholders. Overloads can be 5709 // resolved contextually, but everything else here can't. 5710 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5711 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5712 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5713 5714 // Ignore failures; dropping the entire initializer list because 5715 // of one failure would be terrible for indexing/etc. 5716 if (result.isInvalid()) continue; 5717 5718 InitArgList[I] = result.get(); 5719 } 5720 } 5721 5722 // Semantic analysis for initializers is done by ActOnDeclarator() and 5723 // CheckInitializer() - it requires knowledge of the object being intialized. 5724 5725 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5726 RBraceLoc); 5727 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5728 return E; 5729 } 5730 5731 /// Do an explicit extend of the given block pointer if we're in ARC. 5732 void Sema::maybeExtendBlockObject(ExprResult &E) { 5733 assert(E.get()->getType()->isBlockPointerType()); 5734 assert(E.get()->isRValue()); 5735 5736 // Only do this in an r-value context. 5737 if (!getLangOpts().ObjCAutoRefCount) return; 5738 5739 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5740 CK_ARCExtendBlockObject, E.get(), 5741 /*base path*/ nullptr, VK_RValue); 5742 Cleanup.setExprNeedsCleanups(true); 5743 } 5744 5745 /// Prepare a conversion of the given expression to an ObjC object 5746 /// pointer type. 5747 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5748 QualType type = E.get()->getType(); 5749 if (type->isObjCObjectPointerType()) { 5750 return CK_BitCast; 5751 } else if (type->isBlockPointerType()) { 5752 maybeExtendBlockObject(E); 5753 return CK_BlockPointerToObjCPointerCast; 5754 } else { 5755 assert(type->isPointerType()); 5756 return CK_CPointerToObjCPointerCast; 5757 } 5758 } 5759 5760 /// Prepares for a scalar cast, performing all the necessary stages 5761 /// except the final cast and returning the kind required. 5762 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5763 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5764 // Also, callers should have filtered out the invalid cases with 5765 // pointers. Everything else should be possible. 5766 5767 QualType SrcTy = Src.get()->getType(); 5768 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5769 return CK_NoOp; 5770 5771 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5772 case Type::STK_MemberPointer: 5773 llvm_unreachable("member pointer type in C"); 5774 5775 case Type::STK_CPointer: 5776 case Type::STK_BlockPointer: 5777 case Type::STK_ObjCObjectPointer: 5778 switch (DestTy->getScalarTypeKind()) { 5779 case Type::STK_CPointer: { 5780 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5781 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5782 if (SrcAS != DestAS) 5783 return CK_AddressSpaceConversion; 5784 return CK_BitCast; 5785 } 5786 case Type::STK_BlockPointer: 5787 return (SrcKind == Type::STK_BlockPointer 5788 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5789 case Type::STK_ObjCObjectPointer: 5790 if (SrcKind == Type::STK_ObjCObjectPointer) 5791 return CK_BitCast; 5792 if (SrcKind == Type::STK_CPointer) 5793 return CK_CPointerToObjCPointerCast; 5794 maybeExtendBlockObject(Src); 5795 return CK_BlockPointerToObjCPointerCast; 5796 case Type::STK_Bool: 5797 return CK_PointerToBoolean; 5798 case Type::STK_Integral: 5799 return CK_PointerToIntegral; 5800 case Type::STK_Floating: 5801 case Type::STK_FloatingComplex: 5802 case Type::STK_IntegralComplex: 5803 case Type::STK_MemberPointer: 5804 llvm_unreachable("illegal cast from pointer"); 5805 } 5806 llvm_unreachable("Should have returned before this"); 5807 5808 case Type::STK_Bool: // casting from bool is like casting from an integer 5809 case Type::STK_Integral: 5810 switch (DestTy->getScalarTypeKind()) { 5811 case Type::STK_CPointer: 5812 case Type::STK_ObjCObjectPointer: 5813 case Type::STK_BlockPointer: 5814 if (Src.get()->isNullPointerConstant(Context, 5815 Expr::NPC_ValueDependentIsNull)) 5816 return CK_NullToPointer; 5817 return CK_IntegralToPointer; 5818 case Type::STK_Bool: 5819 return CK_IntegralToBoolean; 5820 case Type::STK_Integral: 5821 return CK_IntegralCast; 5822 case Type::STK_Floating: 5823 return CK_IntegralToFloating; 5824 case Type::STK_IntegralComplex: 5825 Src = ImpCastExprToType(Src.get(), 5826 DestTy->castAs<ComplexType>()->getElementType(), 5827 CK_IntegralCast); 5828 return CK_IntegralRealToComplex; 5829 case Type::STK_FloatingComplex: 5830 Src = ImpCastExprToType(Src.get(), 5831 DestTy->castAs<ComplexType>()->getElementType(), 5832 CK_IntegralToFloating); 5833 return CK_FloatingRealToComplex; 5834 case Type::STK_MemberPointer: 5835 llvm_unreachable("member pointer type in C"); 5836 } 5837 llvm_unreachable("Should have returned before this"); 5838 5839 case Type::STK_Floating: 5840 switch (DestTy->getScalarTypeKind()) { 5841 case Type::STK_Floating: 5842 return CK_FloatingCast; 5843 case Type::STK_Bool: 5844 return CK_FloatingToBoolean; 5845 case Type::STK_Integral: 5846 return CK_FloatingToIntegral; 5847 case Type::STK_FloatingComplex: 5848 Src = ImpCastExprToType(Src.get(), 5849 DestTy->castAs<ComplexType>()->getElementType(), 5850 CK_FloatingCast); 5851 return CK_FloatingRealToComplex; 5852 case Type::STK_IntegralComplex: 5853 Src = ImpCastExprToType(Src.get(), 5854 DestTy->castAs<ComplexType>()->getElementType(), 5855 CK_FloatingToIntegral); 5856 return CK_IntegralRealToComplex; 5857 case Type::STK_CPointer: 5858 case Type::STK_ObjCObjectPointer: 5859 case Type::STK_BlockPointer: 5860 llvm_unreachable("valid float->pointer cast?"); 5861 case Type::STK_MemberPointer: 5862 llvm_unreachable("member pointer type in C"); 5863 } 5864 llvm_unreachable("Should have returned before this"); 5865 5866 case Type::STK_FloatingComplex: 5867 switch (DestTy->getScalarTypeKind()) { 5868 case Type::STK_FloatingComplex: 5869 return CK_FloatingComplexCast; 5870 case Type::STK_IntegralComplex: 5871 return CK_FloatingComplexToIntegralComplex; 5872 case Type::STK_Floating: { 5873 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5874 if (Context.hasSameType(ET, DestTy)) 5875 return CK_FloatingComplexToReal; 5876 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5877 return CK_FloatingCast; 5878 } 5879 case Type::STK_Bool: 5880 return CK_FloatingComplexToBoolean; 5881 case Type::STK_Integral: 5882 Src = ImpCastExprToType(Src.get(), 5883 SrcTy->castAs<ComplexType>()->getElementType(), 5884 CK_FloatingComplexToReal); 5885 return CK_FloatingToIntegral; 5886 case Type::STK_CPointer: 5887 case Type::STK_ObjCObjectPointer: 5888 case Type::STK_BlockPointer: 5889 llvm_unreachable("valid complex float->pointer cast?"); 5890 case Type::STK_MemberPointer: 5891 llvm_unreachable("member pointer type in C"); 5892 } 5893 llvm_unreachable("Should have returned before this"); 5894 5895 case Type::STK_IntegralComplex: 5896 switch (DestTy->getScalarTypeKind()) { 5897 case Type::STK_FloatingComplex: 5898 return CK_IntegralComplexToFloatingComplex; 5899 case Type::STK_IntegralComplex: 5900 return CK_IntegralComplexCast; 5901 case Type::STK_Integral: { 5902 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5903 if (Context.hasSameType(ET, DestTy)) 5904 return CK_IntegralComplexToReal; 5905 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5906 return CK_IntegralCast; 5907 } 5908 case Type::STK_Bool: 5909 return CK_IntegralComplexToBoolean; 5910 case Type::STK_Floating: 5911 Src = ImpCastExprToType(Src.get(), 5912 SrcTy->castAs<ComplexType>()->getElementType(), 5913 CK_IntegralComplexToReal); 5914 return CK_IntegralToFloating; 5915 case Type::STK_CPointer: 5916 case Type::STK_ObjCObjectPointer: 5917 case Type::STK_BlockPointer: 5918 llvm_unreachable("valid complex int->pointer cast?"); 5919 case Type::STK_MemberPointer: 5920 llvm_unreachable("member pointer type in C"); 5921 } 5922 llvm_unreachable("Should have returned before this"); 5923 } 5924 5925 llvm_unreachable("Unhandled scalar cast"); 5926 } 5927 5928 static bool breakDownVectorType(QualType type, uint64_t &len, 5929 QualType &eltType) { 5930 // Vectors are simple. 5931 if (const VectorType *vecType = type->getAs<VectorType>()) { 5932 len = vecType->getNumElements(); 5933 eltType = vecType->getElementType(); 5934 assert(eltType->isScalarType()); 5935 return true; 5936 } 5937 5938 // We allow lax conversion to and from non-vector types, but only if 5939 // they're real types (i.e. non-complex, non-pointer scalar types). 5940 if (!type->isRealType()) return false; 5941 5942 len = 1; 5943 eltType = type; 5944 return true; 5945 } 5946 5947 /// Are the two types lax-compatible vector types? That is, given 5948 /// that one of them is a vector, do they have equal storage sizes, 5949 /// where the storage size is the number of elements times the element 5950 /// size? 5951 /// 5952 /// This will also return false if either of the types is neither a 5953 /// vector nor a real type. 5954 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5955 assert(destTy->isVectorType() || srcTy->isVectorType()); 5956 5957 // Disallow lax conversions between scalars and ExtVectors (these 5958 // conversions are allowed for other vector types because common headers 5959 // depend on them). Most scalar OP ExtVector cases are handled by the 5960 // splat path anyway, which does what we want (convert, not bitcast). 5961 // What this rules out for ExtVectors is crazy things like char4*float. 5962 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5963 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5964 5965 uint64_t srcLen, destLen; 5966 QualType srcEltTy, destEltTy; 5967 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5968 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5969 5970 // ASTContext::getTypeSize will return the size rounded up to a 5971 // power of 2, so instead of using that, we need to use the raw 5972 // element size multiplied by the element count. 5973 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5974 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5975 5976 return (srcLen * srcEltSize == destLen * destEltSize); 5977 } 5978 5979 /// Is this a legal conversion between two types, one of which is 5980 /// known to be a vector type? 5981 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5982 assert(destTy->isVectorType() || srcTy->isVectorType()); 5983 5984 if (!Context.getLangOpts().LaxVectorConversions) 5985 return false; 5986 return areLaxCompatibleVectorTypes(srcTy, destTy); 5987 } 5988 5989 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5990 CastKind &Kind) { 5991 assert(VectorTy->isVectorType() && "Not a vector type!"); 5992 5993 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5994 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5995 return Diag(R.getBegin(), 5996 Ty->isVectorType() ? 5997 diag::err_invalid_conversion_between_vectors : 5998 diag::err_invalid_conversion_between_vector_and_integer) 5999 << VectorTy << Ty << R; 6000 } else 6001 return Diag(R.getBegin(), 6002 diag::err_invalid_conversion_between_vector_and_scalar) 6003 << VectorTy << Ty << R; 6004 6005 Kind = CK_BitCast; 6006 return false; 6007 } 6008 6009 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6010 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6011 6012 if (DestElemTy == SplattedExpr->getType()) 6013 return SplattedExpr; 6014 6015 assert(DestElemTy->isFloatingType() || 6016 DestElemTy->isIntegralOrEnumerationType()); 6017 6018 CastKind CK; 6019 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6020 // OpenCL requires that we convert `true` boolean expressions to -1, but 6021 // only when splatting vectors. 6022 if (DestElemTy->isFloatingType()) { 6023 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6024 // in two steps: boolean to signed integral, then to floating. 6025 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6026 CK_BooleanToSignedIntegral); 6027 SplattedExpr = CastExprRes.get(); 6028 CK = CK_IntegralToFloating; 6029 } else { 6030 CK = CK_BooleanToSignedIntegral; 6031 } 6032 } else { 6033 ExprResult CastExprRes = SplattedExpr; 6034 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6035 if (CastExprRes.isInvalid()) 6036 return ExprError(); 6037 SplattedExpr = CastExprRes.get(); 6038 } 6039 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6040 } 6041 6042 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6043 Expr *CastExpr, CastKind &Kind) { 6044 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6045 6046 QualType SrcTy = CastExpr->getType(); 6047 6048 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6049 // an ExtVectorType. 6050 // In OpenCL, casts between vectors of different types are not allowed. 6051 // (See OpenCL 6.2). 6052 if (SrcTy->isVectorType()) { 6053 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6054 (getLangOpts().OpenCL && 6055 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6056 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6057 << DestTy << SrcTy << R; 6058 return ExprError(); 6059 } 6060 Kind = CK_BitCast; 6061 return CastExpr; 6062 } 6063 6064 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6065 // conversion will take place first from scalar to elt type, and then 6066 // splat from elt type to vector. 6067 if (SrcTy->isPointerType()) 6068 return Diag(R.getBegin(), 6069 diag::err_invalid_conversion_between_vector_and_scalar) 6070 << DestTy << SrcTy << R; 6071 6072 Kind = CK_VectorSplat; 6073 return prepareVectorSplat(DestTy, CastExpr); 6074 } 6075 6076 ExprResult 6077 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6078 Declarator &D, ParsedType &Ty, 6079 SourceLocation RParenLoc, Expr *CastExpr) { 6080 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6081 "ActOnCastExpr(): missing type or expr"); 6082 6083 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6084 if (D.isInvalidType()) 6085 return ExprError(); 6086 6087 if (getLangOpts().CPlusPlus) { 6088 // Check that there are no default arguments (C++ only). 6089 CheckExtraCXXDefaultArguments(D); 6090 } else { 6091 // Make sure any TypoExprs have been dealt with. 6092 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6093 if (!Res.isUsable()) 6094 return ExprError(); 6095 CastExpr = Res.get(); 6096 } 6097 6098 checkUnusedDeclAttributes(D); 6099 6100 QualType castType = castTInfo->getType(); 6101 Ty = CreateParsedType(castType, castTInfo); 6102 6103 bool isVectorLiteral = false; 6104 6105 // Check for an altivec or OpenCL literal, 6106 // i.e. all the elements are integer constants. 6107 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6108 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6109 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6110 && castType->isVectorType() && (PE || PLE)) { 6111 if (PLE && PLE->getNumExprs() == 0) { 6112 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6113 return ExprError(); 6114 } 6115 if (PE || PLE->getNumExprs() == 1) { 6116 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6117 if (!E->getType()->isVectorType()) 6118 isVectorLiteral = true; 6119 } 6120 else 6121 isVectorLiteral = true; 6122 } 6123 6124 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6125 // then handle it as such. 6126 if (isVectorLiteral) 6127 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6128 6129 // If the Expr being casted is a ParenListExpr, handle it specially. 6130 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6131 // sequence of BinOp comma operators. 6132 if (isa<ParenListExpr>(CastExpr)) { 6133 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6134 if (Result.isInvalid()) return ExprError(); 6135 CastExpr = Result.get(); 6136 } 6137 6138 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6139 !getSourceManager().isInSystemMacro(LParenLoc)) 6140 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6141 6142 CheckTollFreeBridgeCast(castType, CastExpr); 6143 6144 CheckObjCBridgeRelatedCast(castType, CastExpr); 6145 6146 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6147 6148 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6149 } 6150 6151 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6152 SourceLocation RParenLoc, Expr *E, 6153 TypeSourceInfo *TInfo) { 6154 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6155 "Expected paren or paren list expression"); 6156 6157 Expr **exprs; 6158 unsigned numExprs; 6159 Expr *subExpr; 6160 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6161 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6162 LiteralLParenLoc = PE->getLParenLoc(); 6163 LiteralRParenLoc = PE->getRParenLoc(); 6164 exprs = PE->getExprs(); 6165 numExprs = PE->getNumExprs(); 6166 } else { // isa<ParenExpr> by assertion at function entrance 6167 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6168 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6169 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6170 exprs = &subExpr; 6171 numExprs = 1; 6172 } 6173 6174 QualType Ty = TInfo->getType(); 6175 assert(Ty->isVectorType() && "Expected vector type"); 6176 6177 SmallVector<Expr *, 8> initExprs; 6178 const VectorType *VTy = Ty->getAs<VectorType>(); 6179 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6180 6181 // '(...)' form of vector initialization in AltiVec: the number of 6182 // initializers must be one or must match the size of the vector. 6183 // If a single value is specified in the initializer then it will be 6184 // replicated to all the components of the vector 6185 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6186 // The number of initializers must be one or must match the size of the 6187 // vector. If a single value is specified in the initializer then it will 6188 // be replicated to all the components of the vector 6189 if (numExprs == 1) { 6190 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6191 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6192 if (Literal.isInvalid()) 6193 return ExprError(); 6194 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6195 PrepareScalarCast(Literal, ElemTy)); 6196 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6197 } 6198 else if (numExprs < numElems) { 6199 Diag(E->getExprLoc(), 6200 diag::err_incorrect_number_of_vector_initializers); 6201 return ExprError(); 6202 } 6203 else 6204 initExprs.append(exprs, exprs + numExprs); 6205 } 6206 else { 6207 // For OpenCL, when the number of initializers is a single value, 6208 // it will be replicated to all components of the vector. 6209 if (getLangOpts().OpenCL && 6210 VTy->getVectorKind() == VectorType::GenericVector && 6211 numExprs == 1) { 6212 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6213 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6214 if (Literal.isInvalid()) 6215 return ExprError(); 6216 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6217 PrepareScalarCast(Literal, ElemTy)); 6218 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6219 } 6220 6221 initExprs.append(exprs, exprs + numExprs); 6222 } 6223 // FIXME: This means that pretty-printing the final AST will produce curly 6224 // braces instead of the original commas. 6225 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6226 initExprs, LiteralRParenLoc); 6227 initE->setType(Ty); 6228 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6229 } 6230 6231 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6232 /// the ParenListExpr into a sequence of comma binary operators. 6233 ExprResult 6234 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6235 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6236 if (!E) 6237 return OrigExpr; 6238 6239 ExprResult Result(E->getExpr(0)); 6240 6241 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6242 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6243 E->getExpr(i)); 6244 6245 if (Result.isInvalid()) return ExprError(); 6246 6247 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6248 } 6249 6250 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6251 SourceLocation R, 6252 MultiExprArg Val) { 6253 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6254 return expr; 6255 } 6256 6257 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6258 /// constant and the other is not a pointer. Returns true if a diagnostic is 6259 /// emitted. 6260 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6261 SourceLocation QuestionLoc) { 6262 Expr *NullExpr = LHSExpr; 6263 Expr *NonPointerExpr = RHSExpr; 6264 Expr::NullPointerConstantKind NullKind = 6265 NullExpr->isNullPointerConstant(Context, 6266 Expr::NPC_ValueDependentIsNotNull); 6267 6268 if (NullKind == Expr::NPCK_NotNull) { 6269 NullExpr = RHSExpr; 6270 NonPointerExpr = LHSExpr; 6271 NullKind = 6272 NullExpr->isNullPointerConstant(Context, 6273 Expr::NPC_ValueDependentIsNotNull); 6274 } 6275 6276 if (NullKind == Expr::NPCK_NotNull) 6277 return false; 6278 6279 if (NullKind == Expr::NPCK_ZeroExpression) 6280 return false; 6281 6282 if (NullKind == Expr::NPCK_ZeroLiteral) { 6283 // In this case, check to make sure that we got here from a "NULL" 6284 // string in the source code. 6285 NullExpr = NullExpr->IgnoreParenImpCasts(); 6286 SourceLocation loc = NullExpr->getExprLoc(); 6287 if (!findMacroSpelling(loc, "NULL")) 6288 return false; 6289 } 6290 6291 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6292 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6293 << NonPointerExpr->getType() << DiagType 6294 << NonPointerExpr->getSourceRange(); 6295 return true; 6296 } 6297 6298 /// \brief Return false if the condition expression is valid, true otherwise. 6299 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6300 QualType CondTy = Cond->getType(); 6301 6302 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6303 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6304 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6305 << CondTy << Cond->getSourceRange(); 6306 return true; 6307 } 6308 6309 // C99 6.5.15p2 6310 if (CondTy->isScalarType()) return false; 6311 6312 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6313 << CondTy << Cond->getSourceRange(); 6314 return true; 6315 } 6316 6317 /// \brief Handle when one or both operands are void type. 6318 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6319 ExprResult &RHS) { 6320 Expr *LHSExpr = LHS.get(); 6321 Expr *RHSExpr = RHS.get(); 6322 6323 if (!LHSExpr->getType()->isVoidType()) 6324 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6325 << RHSExpr->getSourceRange(); 6326 if (!RHSExpr->getType()->isVoidType()) 6327 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6328 << LHSExpr->getSourceRange(); 6329 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6330 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6331 return S.Context.VoidTy; 6332 } 6333 6334 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6335 /// true otherwise. 6336 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6337 QualType PointerTy) { 6338 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6339 !NullExpr.get()->isNullPointerConstant(S.Context, 6340 Expr::NPC_ValueDependentIsNull)) 6341 return true; 6342 6343 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6344 return false; 6345 } 6346 6347 /// \brief Checks compatibility between two pointers and return the resulting 6348 /// type. 6349 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6350 ExprResult &RHS, 6351 SourceLocation Loc) { 6352 QualType LHSTy = LHS.get()->getType(); 6353 QualType RHSTy = RHS.get()->getType(); 6354 6355 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6356 // Two identical pointers types are always compatible. 6357 return LHSTy; 6358 } 6359 6360 QualType lhptee, rhptee; 6361 6362 // Get the pointee types. 6363 bool IsBlockPointer = false; 6364 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6365 lhptee = LHSBTy->getPointeeType(); 6366 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6367 IsBlockPointer = true; 6368 } else { 6369 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6370 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6371 } 6372 6373 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6374 // differently qualified versions of compatible types, the result type is 6375 // a pointer to an appropriately qualified version of the composite 6376 // type. 6377 6378 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6379 // clause doesn't make sense for our extensions. E.g. address space 2 should 6380 // be incompatible with address space 3: they may live on different devices or 6381 // anything. 6382 Qualifiers lhQual = lhptee.getQualifiers(); 6383 Qualifiers rhQual = rhptee.getQualifiers(); 6384 6385 LangAS ResultAddrSpace = LangAS::Default; 6386 LangAS LAddrSpace = lhQual.getAddressSpace(); 6387 LangAS RAddrSpace = rhQual.getAddressSpace(); 6388 if (S.getLangOpts().OpenCL) { 6389 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6390 // spaces is disallowed. 6391 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6392 ResultAddrSpace = LAddrSpace; 6393 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6394 ResultAddrSpace = RAddrSpace; 6395 else { 6396 S.Diag(Loc, 6397 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6398 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6399 << RHS.get()->getSourceRange(); 6400 return QualType(); 6401 } 6402 } 6403 6404 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6405 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6406 lhQual.removeCVRQualifiers(); 6407 rhQual.removeCVRQualifiers(); 6408 6409 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6410 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6411 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6412 // qual types are compatible iff 6413 // * corresponded types are compatible 6414 // * CVR qualifiers are equal 6415 // * address spaces are equal 6416 // Thus for conditional operator we merge CVR and address space unqualified 6417 // pointees and if there is a composite type we return a pointer to it with 6418 // merged qualifiers. 6419 if (S.getLangOpts().OpenCL) { 6420 LHSCastKind = LAddrSpace == ResultAddrSpace 6421 ? CK_BitCast 6422 : CK_AddressSpaceConversion; 6423 RHSCastKind = RAddrSpace == ResultAddrSpace 6424 ? CK_BitCast 6425 : CK_AddressSpaceConversion; 6426 lhQual.removeAddressSpace(); 6427 rhQual.removeAddressSpace(); 6428 } 6429 6430 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6431 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6432 6433 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6434 6435 if (CompositeTy.isNull()) { 6436 // In this situation, we assume void* type. No especially good 6437 // reason, but this is what gcc does, and we do have to pick 6438 // to get a consistent AST. 6439 QualType incompatTy; 6440 incompatTy = S.Context.getPointerType( 6441 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6442 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6443 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6444 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6445 // for casts between types with incompatible address space qualifiers. 6446 // For the following code the compiler produces casts between global and 6447 // local address spaces of the corresponded innermost pointees: 6448 // local int *global *a; 6449 // global int *global *b; 6450 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6451 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6452 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6453 << RHS.get()->getSourceRange(); 6454 return incompatTy; 6455 } 6456 6457 // The pointer types are compatible. 6458 // In case of OpenCL ResultTy should have the address space qualifier 6459 // which is a superset of address spaces of both the 2nd and the 3rd 6460 // operands of the conditional operator. 6461 QualType ResultTy = [&, ResultAddrSpace]() { 6462 if (S.getLangOpts().OpenCL) { 6463 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6464 CompositeQuals.setAddressSpace(ResultAddrSpace); 6465 return S.Context 6466 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6467 .withCVRQualifiers(MergedCVRQual); 6468 } 6469 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6470 }(); 6471 if (IsBlockPointer) 6472 ResultTy = S.Context.getBlockPointerType(ResultTy); 6473 else 6474 ResultTy = S.Context.getPointerType(ResultTy); 6475 6476 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6477 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6478 return ResultTy; 6479 } 6480 6481 /// \brief Return the resulting type when the operands are both block pointers. 6482 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6483 ExprResult &LHS, 6484 ExprResult &RHS, 6485 SourceLocation Loc) { 6486 QualType LHSTy = LHS.get()->getType(); 6487 QualType RHSTy = RHS.get()->getType(); 6488 6489 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6490 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6491 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6492 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6493 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6494 return destType; 6495 } 6496 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6497 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6498 << RHS.get()->getSourceRange(); 6499 return QualType(); 6500 } 6501 6502 // We have 2 block pointer types. 6503 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6504 } 6505 6506 /// \brief Return the resulting type when the operands are both pointers. 6507 static QualType 6508 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6509 ExprResult &RHS, 6510 SourceLocation Loc) { 6511 // get the pointer types 6512 QualType LHSTy = LHS.get()->getType(); 6513 QualType RHSTy = RHS.get()->getType(); 6514 6515 // get the "pointed to" types 6516 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6517 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6518 6519 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6520 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6521 // Figure out necessary qualifiers (C99 6.5.15p6) 6522 QualType destPointee 6523 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6524 QualType destType = S.Context.getPointerType(destPointee); 6525 // Add qualifiers if necessary. 6526 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6527 // Promote to void*. 6528 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6529 return destType; 6530 } 6531 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6532 QualType destPointee 6533 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6534 QualType destType = S.Context.getPointerType(destPointee); 6535 // Add qualifiers if necessary. 6536 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6537 // Promote to void*. 6538 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6539 return destType; 6540 } 6541 6542 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6543 } 6544 6545 /// \brief Return false if the first expression is not an integer and the second 6546 /// expression is not a pointer, true otherwise. 6547 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6548 Expr* PointerExpr, SourceLocation Loc, 6549 bool IsIntFirstExpr) { 6550 if (!PointerExpr->getType()->isPointerType() || 6551 !Int.get()->getType()->isIntegerType()) 6552 return false; 6553 6554 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6555 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6556 6557 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6558 << Expr1->getType() << Expr2->getType() 6559 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6560 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6561 CK_IntegralToPointer); 6562 return true; 6563 } 6564 6565 /// \brief Simple conversion between integer and floating point types. 6566 /// 6567 /// Used when handling the OpenCL conditional operator where the 6568 /// condition is a vector while the other operands are scalar. 6569 /// 6570 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6571 /// types are either integer or floating type. Between the two 6572 /// operands, the type with the higher rank is defined as the "result 6573 /// type". The other operand needs to be promoted to the same type. No 6574 /// other type promotion is allowed. We cannot use 6575 /// UsualArithmeticConversions() for this purpose, since it always 6576 /// promotes promotable types. 6577 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6578 ExprResult &RHS, 6579 SourceLocation QuestionLoc) { 6580 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6581 if (LHS.isInvalid()) 6582 return QualType(); 6583 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6584 if (RHS.isInvalid()) 6585 return QualType(); 6586 6587 // For conversion purposes, we ignore any qualifiers. 6588 // For example, "const float" and "float" are equivalent. 6589 QualType LHSType = 6590 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6591 QualType RHSType = 6592 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6593 6594 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6595 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6596 << LHSType << LHS.get()->getSourceRange(); 6597 return QualType(); 6598 } 6599 6600 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6601 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6602 << RHSType << RHS.get()->getSourceRange(); 6603 return QualType(); 6604 } 6605 6606 // If both types are identical, no conversion is needed. 6607 if (LHSType == RHSType) 6608 return LHSType; 6609 6610 // Now handle "real" floating types (i.e. float, double, long double). 6611 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6612 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6613 /*IsCompAssign = */ false); 6614 6615 // Finally, we have two differing integer types. 6616 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6617 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6618 } 6619 6620 /// \brief Convert scalar operands to a vector that matches the 6621 /// condition in length. 6622 /// 6623 /// Used when handling the OpenCL conditional operator where the 6624 /// condition is a vector while the other operands are scalar. 6625 /// 6626 /// We first compute the "result type" for the scalar operands 6627 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6628 /// into a vector of that type where the length matches the condition 6629 /// vector type. s6.11.6 requires that the element types of the result 6630 /// and the condition must have the same number of bits. 6631 static QualType 6632 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6633 QualType CondTy, SourceLocation QuestionLoc) { 6634 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6635 if (ResTy.isNull()) return QualType(); 6636 6637 const VectorType *CV = CondTy->getAs<VectorType>(); 6638 assert(CV); 6639 6640 // Determine the vector result type 6641 unsigned NumElements = CV->getNumElements(); 6642 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6643 6644 // Ensure that all types have the same number of bits 6645 if (S.Context.getTypeSize(CV->getElementType()) 6646 != S.Context.getTypeSize(ResTy)) { 6647 // Since VectorTy is created internally, it does not pretty print 6648 // with an OpenCL name. Instead, we just print a description. 6649 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6650 SmallString<64> Str; 6651 llvm::raw_svector_ostream OS(Str); 6652 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6653 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6654 << CondTy << OS.str(); 6655 return QualType(); 6656 } 6657 6658 // Convert operands to the vector result type 6659 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6660 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6661 6662 return VectorTy; 6663 } 6664 6665 /// \brief Return false if this is a valid OpenCL condition vector 6666 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6667 SourceLocation QuestionLoc) { 6668 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6669 // integral type. 6670 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6671 assert(CondTy); 6672 QualType EleTy = CondTy->getElementType(); 6673 if (EleTy->isIntegerType()) return false; 6674 6675 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6676 << Cond->getType() << Cond->getSourceRange(); 6677 return true; 6678 } 6679 6680 /// \brief Return false if the vector condition type and the vector 6681 /// result type are compatible. 6682 /// 6683 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6684 /// number of elements, and their element types have the same number 6685 /// of bits. 6686 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6687 SourceLocation QuestionLoc) { 6688 const VectorType *CV = CondTy->getAs<VectorType>(); 6689 const VectorType *RV = VecResTy->getAs<VectorType>(); 6690 assert(CV && RV); 6691 6692 if (CV->getNumElements() != RV->getNumElements()) { 6693 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6694 << CondTy << VecResTy; 6695 return true; 6696 } 6697 6698 QualType CVE = CV->getElementType(); 6699 QualType RVE = RV->getElementType(); 6700 6701 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6702 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6703 << CondTy << VecResTy; 6704 return true; 6705 } 6706 6707 return false; 6708 } 6709 6710 /// \brief Return the resulting type for the conditional operator in 6711 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6712 /// s6.3.i) when the condition is a vector type. 6713 static QualType 6714 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6715 ExprResult &LHS, ExprResult &RHS, 6716 SourceLocation QuestionLoc) { 6717 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6718 if (Cond.isInvalid()) 6719 return QualType(); 6720 QualType CondTy = Cond.get()->getType(); 6721 6722 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6723 return QualType(); 6724 6725 // If either operand is a vector then find the vector type of the 6726 // result as specified in OpenCL v1.1 s6.3.i. 6727 if (LHS.get()->getType()->isVectorType() || 6728 RHS.get()->getType()->isVectorType()) { 6729 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6730 /*isCompAssign*/false, 6731 /*AllowBothBool*/true, 6732 /*AllowBoolConversions*/false); 6733 if (VecResTy.isNull()) return QualType(); 6734 // The result type must match the condition type as specified in 6735 // OpenCL v1.1 s6.11.6. 6736 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6737 return QualType(); 6738 return VecResTy; 6739 } 6740 6741 // Both operands are scalar. 6742 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6743 } 6744 6745 /// \brief Return true if the Expr is block type 6746 static bool checkBlockType(Sema &S, const Expr *E) { 6747 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6748 QualType Ty = CE->getCallee()->getType(); 6749 if (Ty->isBlockPointerType()) { 6750 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6751 return true; 6752 } 6753 } 6754 return false; 6755 } 6756 6757 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6758 /// In that case, LHS = cond. 6759 /// C99 6.5.15 6760 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6761 ExprResult &RHS, ExprValueKind &VK, 6762 ExprObjectKind &OK, 6763 SourceLocation QuestionLoc) { 6764 6765 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6766 if (!LHSResult.isUsable()) return QualType(); 6767 LHS = LHSResult; 6768 6769 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6770 if (!RHSResult.isUsable()) return QualType(); 6771 RHS = RHSResult; 6772 6773 // C++ is sufficiently different to merit its own checker. 6774 if (getLangOpts().CPlusPlus) 6775 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6776 6777 VK = VK_RValue; 6778 OK = OK_Ordinary; 6779 6780 // The OpenCL operator with a vector condition is sufficiently 6781 // different to merit its own checker. 6782 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6783 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6784 6785 // First, check the condition. 6786 Cond = UsualUnaryConversions(Cond.get()); 6787 if (Cond.isInvalid()) 6788 return QualType(); 6789 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6790 return QualType(); 6791 6792 // Now check the two expressions. 6793 if (LHS.get()->getType()->isVectorType() || 6794 RHS.get()->getType()->isVectorType()) 6795 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6796 /*AllowBothBool*/true, 6797 /*AllowBoolConversions*/false); 6798 6799 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6800 if (LHS.isInvalid() || RHS.isInvalid()) 6801 return QualType(); 6802 6803 QualType LHSTy = LHS.get()->getType(); 6804 QualType RHSTy = RHS.get()->getType(); 6805 6806 // Diagnose attempts to convert between __float128 and long double where 6807 // such conversions currently can't be handled. 6808 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6809 Diag(QuestionLoc, 6810 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6811 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6812 return QualType(); 6813 } 6814 6815 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6816 // selection operator (?:). 6817 if (getLangOpts().OpenCL && 6818 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6819 return QualType(); 6820 } 6821 6822 // If both operands have arithmetic type, do the usual arithmetic conversions 6823 // to find a common type: C99 6.5.15p3,5. 6824 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6825 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6826 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6827 6828 return ResTy; 6829 } 6830 6831 // If both operands are the same structure or union type, the result is that 6832 // type. 6833 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6834 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6835 if (LHSRT->getDecl() == RHSRT->getDecl()) 6836 // "If both the operands have structure or union type, the result has 6837 // that type." This implies that CV qualifiers are dropped. 6838 return LHSTy.getUnqualifiedType(); 6839 // FIXME: Type of conditional expression must be complete in C mode. 6840 } 6841 6842 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6843 // The following || allows only one side to be void (a GCC-ism). 6844 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6845 return checkConditionalVoidType(*this, LHS, RHS); 6846 } 6847 6848 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6849 // the type of the other operand." 6850 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6851 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6852 6853 // All objective-c pointer type analysis is done here. 6854 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6855 QuestionLoc); 6856 if (LHS.isInvalid() || RHS.isInvalid()) 6857 return QualType(); 6858 if (!compositeType.isNull()) 6859 return compositeType; 6860 6861 6862 // Handle block pointer types. 6863 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6864 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6865 QuestionLoc); 6866 6867 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6868 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6869 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6870 QuestionLoc); 6871 6872 // GCC compatibility: soften pointer/integer mismatch. Note that 6873 // null pointers have been filtered out by this point. 6874 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6875 /*isIntFirstExpr=*/true)) 6876 return RHSTy; 6877 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6878 /*isIntFirstExpr=*/false)) 6879 return LHSTy; 6880 6881 // Emit a better diagnostic if one of the expressions is a null pointer 6882 // constant and the other is not a pointer type. In this case, the user most 6883 // likely forgot to take the address of the other expression. 6884 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6885 return QualType(); 6886 6887 // Otherwise, the operands are not compatible. 6888 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6889 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6890 << RHS.get()->getSourceRange(); 6891 return QualType(); 6892 } 6893 6894 /// FindCompositeObjCPointerType - Helper method to find composite type of 6895 /// two objective-c pointer types of the two input expressions. 6896 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6897 SourceLocation QuestionLoc) { 6898 QualType LHSTy = LHS.get()->getType(); 6899 QualType RHSTy = RHS.get()->getType(); 6900 6901 // Handle things like Class and struct objc_class*. Here we case the result 6902 // to the pseudo-builtin, because that will be implicitly cast back to the 6903 // redefinition type if an attempt is made to access its fields. 6904 if (LHSTy->isObjCClassType() && 6905 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6906 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6907 return LHSTy; 6908 } 6909 if (RHSTy->isObjCClassType() && 6910 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6911 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6912 return RHSTy; 6913 } 6914 // And the same for struct objc_object* / id 6915 if (LHSTy->isObjCIdType() && 6916 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6917 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6918 return LHSTy; 6919 } 6920 if (RHSTy->isObjCIdType() && 6921 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6922 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6923 return RHSTy; 6924 } 6925 // And the same for struct objc_selector* / SEL 6926 if (Context.isObjCSelType(LHSTy) && 6927 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6928 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6929 return LHSTy; 6930 } 6931 if (Context.isObjCSelType(RHSTy) && 6932 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6933 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6934 return RHSTy; 6935 } 6936 // Check constraints for Objective-C object pointers types. 6937 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6938 6939 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6940 // Two identical object pointer types are always compatible. 6941 return LHSTy; 6942 } 6943 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6944 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6945 QualType compositeType = LHSTy; 6946 6947 // If both operands are interfaces and either operand can be 6948 // assigned to the other, use that type as the composite 6949 // type. This allows 6950 // xxx ? (A*) a : (B*) b 6951 // where B is a subclass of A. 6952 // 6953 // Additionally, as for assignment, if either type is 'id' 6954 // allow silent coercion. Finally, if the types are 6955 // incompatible then make sure to use 'id' as the composite 6956 // type so the result is acceptable for sending messages to. 6957 6958 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6959 // It could return the composite type. 6960 if (!(compositeType = 6961 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6962 // Nothing more to do. 6963 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6964 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6965 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6966 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6967 } else if ((LHSTy->isObjCQualifiedIdType() || 6968 RHSTy->isObjCQualifiedIdType()) && 6969 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6970 // Need to handle "id<xx>" explicitly. 6971 // GCC allows qualified id and any Objective-C type to devolve to 6972 // id. Currently localizing to here until clear this should be 6973 // part of ObjCQualifiedIdTypesAreCompatible. 6974 compositeType = Context.getObjCIdType(); 6975 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6976 compositeType = Context.getObjCIdType(); 6977 } else { 6978 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6979 << LHSTy << RHSTy 6980 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6981 QualType incompatTy = Context.getObjCIdType(); 6982 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6983 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6984 return incompatTy; 6985 } 6986 // The object pointer types are compatible. 6987 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6988 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6989 return compositeType; 6990 } 6991 // Check Objective-C object pointer types and 'void *' 6992 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6993 if (getLangOpts().ObjCAutoRefCount) { 6994 // ARC forbids the implicit conversion of object pointers to 'void *', 6995 // so these types are not compatible. 6996 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6997 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6998 LHS = RHS = true; 6999 return QualType(); 7000 } 7001 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7002 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7003 QualType destPointee 7004 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7005 QualType destType = Context.getPointerType(destPointee); 7006 // Add qualifiers if necessary. 7007 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7008 // Promote to void*. 7009 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7010 return destType; 7011 } 7012 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7013 if (getLangOpts().ObjCAutoRefCount) { 7014 // ARC forbids the implicit conversion of object pointers to 'void *', 7015 // so these types are not compatible. 7016 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7017 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7018 LHS = RHS = true; 7019 return QualType(); 7020 } 7021 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7022 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7023 QualType destPointee 7024 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7025 QualType destType = Context.getPointerType(destPointee); 7026 // Add qualifiers if necessary. 7027 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7028 // Promote to void*. 7029 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7030 return destType; 7031 } 7032 return QualType(); 7033 } 7034 7035 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7036 /// ParenRange in parentheses. 7037 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7038 const PartialDiagnostic &Note, 7039 SourceRange ParenRange) { 7040 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7041 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7042 EndLoc.isValid()) { 7043 Self.Diag(Loc, Note) 7044 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7045 << FixItHint::CreateInsertion(EndLoc, ")"); 7046 } else { 7047 // We can't display the parentheses, so just show the bare note. 7048 Self.Diag(Loc, Note) << ParenRange; 7049 } 7050 } 7051 7052 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7053 return BinaryOperator::isAdditiveOp(Opc) || 7054 BinaryOperator::isMultiplicativeOp(Opc) || 7055 BinaryOperator::isShiftOp(Opc); 7056 } 7057 7058 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7059 /// expression, either using a built-in or overloaded operator, 7060 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7061 /// expression. 7062 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7063 Expr **RHSExprs) { 7064 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7065 E = E->IgnoreImpCasts(); 7066 E = E->IgnoreConversionOperator(); 7067 E = E->IgnoreImpCasts(); 7068 7069 // Built-in binary operator. 7070 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7071 if (IsArithmeticOp(OP->getOpcode())) { 7072 *Opcode = OP->getOpcode(); 7073 *RHSExprs = OP->getRHS(); 7074 return true; 7075 } 7076 } 7077 7078 // Overloaded operator. 7079 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7080 if (Call->getNumArgs() != 2) 7081 return false; 7082 7083 // Make sure this is really a binary operator that is safe to pass into 7084 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7085 OverloadedOperatorKind OO = Call->getOperator(); 7086 if (OO < OO_Plus || OO > OO_Arrow || 7087 OO == OO_PlusPlus || OO == OO_MinusMinus) 7088 return false; 7089 7090 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7091 if (IsArithmeticOp(OpKind)) { 7092 *Opcode = OpKind; 7093 *RHSExprs = Call->getArg(1); 7094 return true; 7095 } 7096 } 7097 7098 return false; 7099 } 7100 7101 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7102 /// or is a logical expression such as (x==y) which has int type, but is 7103 /// commonly interpreted as boolean. 7104 static bool ExprLooksBoolean(Expr *E) { 7105 E = E->IgnoreParenImpCasts(); 7106 7107 if (E->getType()->isBooleanType()) 7108 return true; 7109 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7110 return OP->isComparisonOp() || OP->isLogicalOp(); 7111 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7112 return OP->getOpcode() == UO_LNot; 7113 if (E->getType()->isPointerType()) 7114 return true; 7115 7116 return false; 7117 } 7118 7119 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7120 /// and binary operator are mixed in a way that suggests the programmer assumed 7121 /// the conditional operator has higher precedence, for example: 7122 /// "int x = a + someBinaryCondition ? 1 : 2". 7123 static void DiagnoseConditionalPrecedence(Sema &Self, 7124 SourceLocation OpLoc, 7125 Expr *Condition, 7126 Expr *LHSExpr, 7127 Expr *RHSExpr) { 7128 BinaryOperatorKind CondOpcode; 7129 Expr *CondRHS; 7130 7131 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7132 return; 7133 if (!ExprLooksBoolean(CondRHS)) 7134 return; 7135 7136 // The condition is an arithmetic binary expression, with a right- 7137 // hand side that looks boolean, so warn. 7138 7139 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7140 << Condition->getSourceRange() 7141 << BinaryOperator::getOpcodeStr(CondOpcode); 7142 7143 SuggestParentheses(Self, OpLoc, 7144 Self.PDiag(diag::note_precedence_silence) 7145 << BinaryOperator::getOpcodeStr(CondOpcode), 7146 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7147 7148 SuggestParentheses(Self, OpLoc, 7149 Self.PDiag(diag::note_precedence_conditional_first), 7150 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7151 } 7152 7153 /// Compute the nullability of a conditional expression. 7154 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7155 QualType LHSTy, QualType RHSTy, 7156 ASTContext &Ctx) { 7157 if (!ResTy->isAnyPointerType()) 7158 return ResTy; 7159 7160 auto GetNullability = [&Ctx](QualType Ty) { 7161 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7162 if (Kind) 7163 return *Kind; 7164 return NullabilityKind::Unspecified; 7165 }; 7166 7167 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7168 NullabilityKind MergedKind; 7169 7170 // Compute nullability of a binary conditional expression. 7171 if (IsBin) { 7172 if (LHSKind == NullabilityKind::NonNull) 7173 MergedKind = NullabilityKind::NonNull; 7174 else 7175 MergedKind = RHSKind; 7176 // Compute nullability of a normal conditional expression. 7177 } else { 7178 if (LHSKind == NullabilityKind::Nullable || 7179 RHSKind == NullabilityKind::Nullable) 7180 MergedKind = NullabilityKind::Nullable; 7181 else if (LHSKind == NullabilityKind::NonNull) 7182 MergedKind = RHSKind; 7183 else if (RHSKind == NullabilityKind::NonNull) 7184 MergedKind = LHSKind; 7185 else 7186 MergedKind = NullabilityKind::Unspecified; 7187 } 7188 7189 // Return if ResTy already has the correct nullability. 7190 if (GetNullability(ResTy) == MergedKind) 7191 return ResTy; 7192 7193 // Strip all nullability from ResTy. 7194 while (ResTy->getNullability(Ctx)) 7195 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7196 7197 // Create a new AttributedType with the new nullability kind. 7198 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7199 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7200 } 7201 7202 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7203 /// in the case of a the GNU conditional expr extension. 7204 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7205 SourceLocation ColonLoc, 7206 Expr *CondExpr, Expr *LHSExpr, 7207 Expr *RHSExpr) { 7208 if (!getLangOpts().CPlusPlus) { 7209 // C cannot handle TypoExpr nodes in the condition because it 7210 // doesn't handle dependent types properly, so make sure any TypoExprs have 7211 // been dealt with before checking the operands. 7212 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7213 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7214 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7215 7216 if (!CondResult.isUsable()) 7217 return ExprError(); 7218 7219 if (LHSExpr) { 7220 if (!LHSResult.isUsable()) 7221 return ExprError(); 7222 } 7223 7224 if (!RHSResult.isUsable()) 7225 return ExprError(); 7226 7227 CondExpr = CondResult.get(); 7228 LHSExpr = LHSResult.get(); 7229 RHSExpr = RHSResult.get(); 7230 } 7231 7232 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7233 // was the condition. 7234 OpaqueValueExpr *opaqueValue = nullptr; 7235 Expr *commonExpr = nullptr; 7236 if (!LHSExpr) { 7237 commonExpr = CondExpr; 7238 // Lower out placeholder types first. This is important so that we don't 7239 // try to capture a placeholder. This happens in few cases in C++; such 7240 // as Objective-C++'s dictionary subscripting syntax. 7241 if (commonExpr->hasPlaceholderType()) { 7242 ExprResult result = CheckPlaceholderExpr(commonExpr); 7243 if (!result.isUsable()) return ExprError(); 7244 commonExpr = result.get(); 7245 } 7246 // We usually want to apply unary conversions *before* saving, except 7247 // in the special case of a C++ l-value conditional. 7248 if (!(getLangOpts().CPlusPlus 7249 && !commonExpr->isTypeDependent() 7250 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7251 && commonExpr->isGLValue() 7252 && commonExpr->isOrdinaryOrBitFieldObject() 7253 && RHSExpr->isOrdinaryOrBitFieldObject() 7254 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7255 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7256 if (commonRes.isInvalid()) 7257 return ExprError(); 7258 commonExpr = commonRes.get(); 7259 } 7260 7261 // If the common expression is a class or array prvalue, materialize it 7262 // so that we can safely refer to it multiple times. 7263 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7264 commonExpr->getType()->isArrayType())) { 7265 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7266 if (MatExpr.isInvalid()) 7267 return ExprError(); 7268 commonExpr = MatExpr.get(); 7269 } 7270 7271 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7272 commonExpr->getType(), 7273 commonExpr->getValueKind(), 7274 commonExpr->getObjectKind(), 7275 commonExpr); 7276 LHSExpr = CondExpr = opaqueValue; 7277 } 7278 7279 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7280 ExprValueKind VK = VK_RValue; 7281 ExprObjectKind OK = OK_Ordinary; 7282 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7283 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7284 VK, OK, QuestionLoc); 7285 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7286 RHS.isInvalid()) 7287 return ExprError(); 7288 7289 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7290 RHS.get()); 7291 7292 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7293 7294 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7295 Context); 7296 7297 if (!commonExpr) 7298 return new (Context) 7299 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7300 RHS.get(), result, VK, OK); 7301 7302 return new (Context) BinaryConditionalOperator( 7303 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7304 ColonLoc, result, VK, OK); 7305 } 7306 7307 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7308 // being closely modeled after the C99 spec:-). The odd characteristic of this 7309 // routine is it effectively iqnores the qualifiers on the top level pointee. 7310 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7311 // FIXME: add a couple examples in this comment. 7312 static Sema::AssignConvertType 7313 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7314 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7315 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7316 7317 // get the "pointed to" type (ignoring qualifiers at the top level) 7318 const Type *lhptee, *rhptee; 7319 Qualifiers lhq, rhq; 7320 std::tie(lhptee, lhq) = 7321 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7322 std::tie(rhptee, rhq) = 7323 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7324 7325 Sema::AssignConvertType ConvTy = Sema::Compatible; 7326 7327 // C99 6.5.16.1p1: This following citation is common to constraints 7328 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7329 // qualifiers of the type *pointed to* by the right; 7330 7331 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7332 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7333 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7334 // Ignore lifetime for further calculation. 7335 lhq.removeObjCLifetime(); 7336 rhq.removeObjCLifetime(); 7337 } 7338 7339 if (!lhq.compatiblyIncludes(rhq)) { 7340 // Treat address-space mismatches as fatal. TODO: address subspaces 7341 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7342 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7343 7344 // It's okay to add or remove GC or lifetime qualifiers when converting to 7345 // and from void*. 7346 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7347 .compatiblyIncludes( 7348 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7349 && (lhptee->isVoidType() || rhptee->isVoidType())) 7350 ; // keep old 7351 7352 // Treat lifetime mismatches as fatal. 7353 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7354 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7355 7356 // For GCC/MS compatibility, other qualifier mismatches are treated 7357 // as still compatible in C. 7358 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7359 } 7360 7361 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7362 // incomplete type and the other is a pointer to a qualified or unqualified 7363 // version of void... 7364 if (lhptee->isVoidType()) { 7365 if (rhptee->isIncompleteOrObjectType()) 7366 return ConvTy; 7367 7368 // As an extension, we allow cast to/from void* to function pointer. 7369 assert(rhptee->isFunctionType()); 7370 return Sema::FunctionVoidPointer; 7371 } 7372 7373 if (rhptee->isVoidType()) { 7374 if (lhptee->isIncompleteOrObjectType()) 7375 return ConvTy; 7376 7377 // As an extension, we allow cast to/from void* to function pointer. 7378 assert(lhptee->isFunctionType()); 7379 return Sema::FunctionVoidPointer; 7380 } 7381 7382 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7383 // unqualified versions of compatible types, ... 7384 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7385 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7386 // Check if the pointee types are compatible ignoring the sign. 7387 // We explicitly check for char so that we catch "char" vs 7388 // "unsigned char" on systems where "char" is unsigned. 7389 if (lhptee->isCharType()) 7390 ltrans = S.Context.UnsignedCharTy; 7391 else if (lhptee->hasSignedIntegerRepresentation()) 7392 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7393 7394 if (rhptee->isCharType()) 7395 rtrans = S.Context.UnsignedCharTy; 7396 else if (rhptee->hasSignedIntegerRepresentation()) 7397 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7398 7399 if (ltrans == rtrans) { 7400 // Types are compatible ignoring the sign. Qualifier incompatibility 7401 // takes priority over sign incompatibility because the sign 7402 // warning can be disabled. 7403 if (ConvTy != Sema::Compatible) 7404 return ConvTy; 7405 7406 return Sema::IncompatiblePointerSign; 7407 } 7408 7409 // If we are a multi-level pointer, it's possible that our issue is simply 7410 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7411 // the eventual target type is the same and the pointers have the same 7412 // level of indirection, this must be the issue. 7413 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7414 do { 7415 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7416 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7417 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7418 7419 if (lhptee == rhptee) 7420 return Sema::IncompatibleNestedPointerQualifiers; 7421 } 7422 7423 // General pointer incompatibility takes priority over qualifiers. 7424 return Sema::IncompatiblePointer; 7425 } 7426 if (!S.getLangOpts().CPlusPlus && 7427 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7428 return Sema::IncompatiblePointer; 7429 return ConvTy; 7430 } 7431 7432 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7433 /// block pointer types are compatible or whether a block and normal pointer 7434 /// are compatible. It is more restrict than comparing two function pointer 7435 // types. 7436 static Sema::AssignConvertType 7437 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7438 QualType RHSType) { 7439 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7440 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7441 7442 QualType lhptee, rhptee; 7443 7444 // get the "pointed to" type (ignoring qualifiers at the top level) 7445 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7446 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7447 7448 // In C++, the types have to match exactly. 7449 if (S.getLangOpts().CPlusPlus) 7450 return Sema::IncompatibleBlockPointer; 7451 7452 Sema::AssignConvertType ConvTy = Sema::Compatible; 7453 7454 // For blocks we enforce that qualifiers are identical. 7455 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7456 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7457 if (S.getLangOpts().OpenCL) { 7458 LQuals.removeAddressSpace(); 7459 RQuals.removeAddressSpace(); 7460 } 7461 if (LQuals != RQuals) 7462 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7463 7464 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7465 // assignment. 7466 // The current behavior is similar to C++ lambdas. A block might be 7467 // assigned to a variable iff its return type and parameters are compatible 7468 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7469 // an assignment. Presumably it should behave in way that a function pointer 7470 // assignment does in C, so for each parameter and return type: 7471 // * CVR and address space of LHS should be a superset of CVR and address 7472 // space of RHS. 7473 // * unqualified types should be compatible. 7474 if (S.getLangOpts().OpenCL) { 7475 if (!S.Context.typesAreBlockPointerCompatible( 7476 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7477 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7478 return Sema::IncompatibleBlockPointer; 7479 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7480 return Sema::IncompatibleBlockPointer; 7481 7482 return ConvTy; 7483 } 7484 7485 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7486 /// for assignment compatibility. 7487 static Sema::AssignConvertType 7488 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7489 QualType RHSType) { 7490 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7491 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7492 7493 if (LHSType->isObjCBuiltinType()) { 7494 // Class is not compatible with ObjC object pointers. 7495 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7496 !RHSType->isObjCQualifiedClassType()) 7497 return Sema::IncompatiblePointer; 7498 return Sema::Compatible; 7499 } 7500 if (RHSType->isObjCBuiltinType()) { 7501 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7502 !LHSType->isObjCQualifiedClassType()) 7503 return Sema::IncompatiblePointer; 7504 return Sema::Compatible; 7505 } 7506 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7507 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7508 7509 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7510 // make an exception for id<P> 7511 !LHSType->isObjCQualifiedIdType()) 7512 return Sema::CompatiblePointerDiscardsQualifiers; 7513 7514 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7515 return Sema::Compatible; 7516 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7517 return Sema::IncompatibleObjCQualifiedId; 7518 return Sema::IncompatiblePointer; 7519 } 7520 7521 Sema::AssignConvertType 7522 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7523 QualType LHSType, QualType RHSType) { 7524 // Fake up an opaque expression. We don't actually care about what 7525 // cast operations are required, so if CheckAssignmentConstraints 7526 // adds casts to this they'll be wasted, but fortunately that doesn't 7527 // usually happen on valid code. 7528 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7529 ExprResult RHSPtr = &RHSExpr; 7530 CastKind K; 7531 7532 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7533 } 7534 7535 /// This helper function returns true if QT is a vector type that has element 7536 /// type ElementType. 7537 static bool isVector(QualType QT, QualType ElementType) { 7538 if (const VectorType *VT = QT->getAs<VectorType>()) 7539 return VT->getElementType() == ElementType; 7540 return false; 7541 } 7542 7543 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7544 /// has code to accommodate several GCC extensions when type checking 7545 /// pointers. Here are some objectionable examples that GCC considers warnings: 7546 /// 7547 /// int a, *pint; 7548 /// short *pshort; 7549 /// struct foo *pfoo; 7550 /// 7551 /// pint = pshort; // warning: assignment from incompatible pointer type 7552 /// a = pint; // warning: assignment makes integer from pointer without a cast 7553 /// pint = a; // warning: assignment makes pointer from integer without a cast 7554 /// pint = pfoo; // warning: assignment from incompatible pointer type 7555 /// 7556 /// As a result, the code for dealing with pointers is more complex than the 7557 /// C99 spec dictates. 7558 /// 7559 /// Sets 'Kind' for any result kind except Incompatible. 7560 Sema::AssignConvertType 7561 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7562 CastKind &Kind, bool ConvertRHS) { 7563 QualType RHSType = RHS.get()->getType(); 7564 QualType OrigLHSType = LHSType; 7565 7566 // Get canonical types. We're not formatting these types, just comparing 7567 // them. 7568 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7569 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7570 7571 // Common case: no conversion required. 7572 if (LHSType == RHSType) { 7573 Kind = CK_NoOp; 7574 return Compatible; 7575 } 7576 7577 // If we have an atomic type, try a non-atomic assignment, then just add an 7578 // atomic qualification step. 7579 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7580 Sema::AssignConvertType result = 7581 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7582 if (result != Compatible) 7583 return result; 7584 if (Kind != CK_NoOp && ConvertRHS) 7585 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7586 Kind = CK_NonAtomicToAtomic; 7587 return Compatible; 7588 } 7589 7590 // If the left-hand side is a reference type, then we are in a 7591 // (rare!) case where we've allowed the use of references in C, 7592 // e.g., as a parameter type in a built-in function. In this case, 7593 // just make sure that the type referenced is compatible with the 7594 // right-hand side type. The caller is responsible for adjusting 7595 // LHSType so that the resulting expression does not have reference 7596 // type. 7597 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7598 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7599 Kind = CK_LValueBitCast; 7600 return Compatible; 7601 } 7602 return Incompatible; 7603 } 7604 7605 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7606 // to the same ExtVector type. 7607 if (LHSType->isExtVectorType()) { 7608 if (RHSType->isExtVectorType()) 7609 return Incompatible; 7610 if (RHSType->isArithmeticType()) { 7611 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7612 if (ConvertRHS) 7613 RHS = prepareVectorSplat(LHSType, RHS.get()); 7614 Kind = CK_VectorSplat; 7615 return Compatible; 7616 } 7617 } 7618 7619 // Conversions to or from vector type. 7620 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7621 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7622 // Allow assignments of an AltiVec vector type to an equivalent GCC 7623 // vector type and vice versa 7624 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7625 Kind = CK_BitCast; 7626 return Compatible; 7627 } 7628 7629 // If we are allowing lax vector conversions, and LHS and RHS are both 7630 // vectors, the total size only needs to be the same. This is a bitcast; 7631 // no bits are changed but the result type is different. 7632 if (isLaxVectorConversion(RHSType, LHSType)) { 7633 Kind = CK_BitCast; 7634 return IncompatibleVectors; 7635 } 7636 } 7637 7638 // When the RHS comes from another lax conversion (e.g. binops between 7639 // scalars and vectors) the result is canonicalized as a vector. When the 7640 // LHS is also a vector, the lax is allowed by the condition above. Handle 7641 // the case where LHS is a scalar. 7642 if (LHSType->isScalarType()) { 7643 const VectorType *VecType = RHSType->getAs<VectorType>(); 7644 if (VecType && VecType->getNumElements() == 1 && 7645 isLaxVectorConversion(RHSType, LHSType)) { 7646 ExprResult *VecExpr = &RHS; 7647 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7648 Kind = CK_BitCast; 7649 return Compatible; 7650 } 7651 } 7652 7653 return Incompatible; 7654 } 7655 7656 // Diagnose attempts to convert between __float128 and long double where 7657 // such conversions currently can't be handled. 7658 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7659 return Incompatible; 7660 7661 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7662 // discards the imaginary part. 7663 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7664 !LHSType->getAs<ComplexType>()) 7665 return Incompatible; 7666 7667 // Arithmetic conversions. 7668 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7669 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7670 if (ConvertRHS) 7671 Kind = PrepareScalarCast(RHS, LHSType); 7672 return Compatible; 7673 } 7674 7675 // Conversions to normal pointers. 7676 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7677 // U* -> T* 7678 if (isa<PointerType>(RHSType)) { 7679 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7680 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7681 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7682 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7683 } 7684 7685 // int -> T* 7686 if (RHSType->isIntegerType()) { 7687 Kind = CK_IntegralToPointer; // FIXME: null? 7688 return IntToPointer; 7689 } 7690 7691 // C pointers are not compatible with ObjC object pointers, 7692 // with two exceptions: 7693 if (isa<ObjCObjectPointerType>(RHSType)) { 7694 // - conversions to void* 7695 if (LHSPointer->getPointeeType()->isVoidType()) { 7696 Kind = CK_BitCast; 7697 return Compatible; 7698 } 7699 7700 // - conversions from 'Class' to the redefinition type 7701 if (RHSType->isObjCClassType() && 7702 Context.hasSameType(LHSType, 7703 Context.getObjCClassRedefinitionType())) { 7704 Kind = CK_BitCast; 7705 return Compatible; 7706 } 7707 7708 Kind = CK_BitCast; 7709 return IncompatiblePointer; 7710 } 7711 7712 // U^ -> void* 7713 if (RHSType->getAs<BlockPointerType>()) { 7714 if (LHSPointer->getPointeeType()->isVoidType()) { 7715 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7716 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7717 ->getPointeeType() 7718 .getAddressSpace(); 7719 Kind = 7720 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7721 return Compatible; 7722 } 7723 } 7724 7725 return Incompatible; 7726 } 7727 7728 // Conversions to block pointers. 7729 if (isa<BlockPointerType>(LHSType)) { 7730 // U^ -> T^ 7731 if (RHSType->isBlockPointerType()) { 7732 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7733 ->getPointeeType() 7734 .getAddressSpace(); 7735 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7736 ->getPointeeType() 7737 .getAddressSpace(); 7738 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7739 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7740 } 7741 7742 // int or null -> T^ 7743 if (RHSType->isIntegerType()) { 7744 Kind = CK_IntegralToPointer; // FIXME: null 7745 return IntToBlockPointer; 7746 } 7747 7748 // id -> T^ 7749 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7750 Kind = CK_AnyPointerToBlockPointerCast; 7751 return Compatible; 7752 } 7753 7754 // void* -> T^ 7755 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7756 if (RHSPT->getPointeeType()->isVoidType()) { 7757 Kind = CK_AnyPointerToBlockPointerCast; 7758 return Compatible; 7759 } 7760 7761 return Incompatible; 7762 } 7763 7764 // Conversions to Objective-C pointers. 7765 if (isa<ObjCObjectPointerType>(LHSType)) { 7766 // A* -> B* 7767 if (RHSType->isObjCObjectPointerType()) { 7768 Kind = CK_BitCast; 7769 Sema::AssignConvertType result = 7770 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7771 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7772 result == Compatible && 7773 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7774 result = IncompatibleObjCWeakRef; 7775 return result; 7776 } 7777 7778 // int or null -> A* 7779 if (RHSType->isIntegerType()) { 7780 Kind = CK_IntegralToPointer; // FIXME: null 7781 return IntToPointer; 7782 } 7783 7784 // In general, C pointers are not compatible with ObjC object pointers, 7785 // with two exceptions: 7786 if (isa<PointerType>(RHSType)) { 7787 Kind = CK_CPointerToObjCPointerCast; 7788 7789 // - conversions from 'void*' 7790 if (RHSType->isVoidPointerType()) { 7791 return Compatible; 7792 } 7793 7794 // - conversions to 'Class' from its redefinition type 7795 if (LHSType->isObjCClassType() && 7796 Context.hasSameType(RHSType, 7797 Context.getObjCClassRedefinitionType())) { 7798 return Compatible; 7799 } 7800 7801 return IncompatiblePointer; 7802 } 7803 7804 // Only under strict condition T^ is compatible with an Objective-C pointer. 7805 if (RHSType->isBlockPointerType() && 7806 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7807 if (ConvertRHS) 7808 maybeExtendBlockObject(RHS); 7809 Kind = CK_BlockPointerToObjCPointerCast; 7810 return Compatible; 7811 } 7812 7813 return Incompatible; 7814 } 7815 7816 // Conversions from pointers that are not covered by the above. 7817 if (isa<PointerType>(RHSType)) { 7818 // T* -> _Bool 7819 if (LHSType == Context.BoolTy) { 7820 Kind = CK_PointerToBoolean; 7821 return Compatible; 7822 } 7823 7824 // T* -> int 7825 if (LHSType->isIntegerType()) { 7826 Kind = CK_PointerToIntegral; 7827 return PointerToInt; 7828 } 7829 7830 return Incompatible; 7831 } 7832 7833 // Conversions from Objective-C pointers that are not covered by the above. 7834 if (isa<ObjCObjectPointerType>(RHSType)) { 7835 // T* -> _Bool 7836 if (LHSType == Context.BoolTy) { 7837 Kind = CK_PointerToBoolean; 7838 return Compatible; 7839 } 7840 7841 // T* -> int 7842 if (LHSType->isIntegerType()) { 7843 Kind = CK_PointerToIntegral; 7844 return PointerToInt; 7845 } 7846 7847 return Incompatible; 7848 } 7849 7850 // struct A -> struct B 7851 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7852 if (Context.typesAreCompatible(LHSType, RHSType)) { 7853 Kind = CK_NoOp; 7854 return Compatible; 7855 } 7856 } 7857 7858 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7859 Kind = CK_IntToOCLSampler; 7860 return Compatible; 7861 } 7862 7863 return Incompatible; 7864 } 7865 7866 /// \brief Constructs a transparent union from an expression that is 7867 /// used to initialize the transparent union. 7868 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7869 ExprResult &EResult, QualType UnionType, 7870 FieldDecl *Field) { 7871 // Build an initializer list that designates the appropriate member 7872 // of the transparent union. 7873 Expr *E = EResult.get(); 7874 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7875 E, SourceLocation()); 7876 Initializer->setType(UnionType); 7877 Initializer->setInitializedFieldInUnion(Field); 7878 7879 // Build a compound literal constructing a value of the transparent 7880 // union type from this initializer list. 7881 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7882 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7883 VK_RValue, Initializer, false); 7884 } 7885 7886 Sema::AssignConvertType 7887 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7888 ExprResult &RHS) { 7889 QualType RHSType = RHS.get()->getType(); 7890 7891 // If the ArgType is a Union type, we want to handle a potential 7892 // transparent_union GCC extension. 7893 const RecordType *UT = ArgType->getAsUnionType(); 7894 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7895 return Incompatible; 7896 7897 // The field to initialize within the transparent union. 7898 RecordDecl *UD = UT->getDecl(); 7899 FieldDecl *InitField = nullptr; 7900 // It's compatible if the expression matches any of the fields. 7901 for (auto *it : UD->fields()) { 7902 if (it->getType()->isPointerType()) { 7903 // If the transparent union contains a pointer type, we allow: 7904 // 1) void pointer 7905 // 2) null pointer constant 7906 if (RHSType->isPointerType()) 7907 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7908 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7909 InitField = it; 7910 break; 7911 } 7912 7913 if (RHS.get()->isNullPointerConstant(Context, 7914 Expr::NPC_ValueDependentIsNull)) { 7915 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7916 CK_NullToPointer); 7917 InitField = it; 7918 break; 7919 } 7920 } 7921 7922 CastKind Kind; 7923 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7924 == Compatible) { 7925 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7926 InitField = it; 7927 break; 7928 } 7929 } 7930 7931 if (!InitField) 7932 return Incompatible; 7933 7934 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7935 return Compatible; 7936 } 7937 7938 Sema::AssignConvertType 7939 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7940 bool Diagnose, 7941 bool DiagnoseCFAudited, 7942 bool ConvertRHS) { 7943 // We need to be able to tell the caller whether we diagnosed a problem, if 7944 // they ask us to issue diagnostics. 7945 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7946 7947 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7948 // we can't avoid *all* modifications at the moment, so we need some somewhere 7949 // to put the updated value. 7950 ExprResult LocalRHS = CallerRHS; 7951 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7952 7953 if (getLangOpts().CPlusPlus) { 7954 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7955 // C++ 5.17p3: If the left operand is not of class type, the 7956 // expression is implicitly converted (C++ 4) to the 7957 // cv-unqualified type of the left operand. 7958 QualType RHSType = RHS.get()->getType(); 7959 if (Diagnose) { 7960 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7961 AA_Assigning); 7962 } else { 7963 ImplicitConversionSequence ICS = 7964 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7965 /*SuppressUserConversions=*/false, 7966 /*AllowExplicit=*/false, 7967 /*InOverloadResolution=*/false, 7968 /*CStyle=*/false, 7969 /*AllowObjCWritebackConversion=*/false); 7970 if (ICS.isFailure()) 7971 return Incompatible; 7972 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7973 ICS, AA_Assigning); 7974 } 7975 if (RHS.isInvalid()) 7976 return Incompatible; 7977 Sema::AssignConvertType result = Compatible; 7978 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7979 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7980 result = IncompatibleObjCWeakRef; 7981 return result; 7982 } 7983 7984 // FIXME: Currently, we fall through and treat C++ classes like C 7985 // structures. 7986 // FIXME: We also fall through for atomics; not sure what should 7987 // happen there, though. 7988 } else if (RHS.get()->getType() == Context.OverloadTy) { 7989 // As a set of extensions to C, we support overloading on functions. These 7990 // functions need to be resolved here. 7991 DeclAccessPair DAP; 7992 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7993 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7994 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7995 else 7996 return Incompatible; 7997 } 7998 7999 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8000 // a null pointer constant. 8001 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8002 LHSType->isBlockPointerType()) && 8003 RHS.get()->isNullPointerConstant(Context, 8004 Expr::NPC_ValueDependentIsNull)) { 8005 if (Diagnose || ConvertRHS) { 8006 CastKind Kind; 8007 CXXCastPath Path; 8008 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8009 /*IgnoreBaseAccess=*/false, Diagnose); 8010 if (ConvertRHS) 8011 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8012 } 8013 return Compatible; 8014 } 8015 8016 // This check seems unnatural, however it is necessary to ensure the proper 8017 // conversion of functions/arrays. If the conversion were done for all 8018 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8019 // expressions that suppress this implicit conversion (&, sizeof). 8020 // 8021 // Suppress this for references: C++ 8.5.3p5. 8022 if (!LHSType->isReferenceType()) { 8023 // FIXME: We potentially allocate here even if ConvertRHS is false. 8024 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8025 if (RHS.isInvalid()) 8026 return Incompatible; 8027 } 8028 8029 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8030 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8031 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8032 if (PDecl && !PDecl->hasDefinition()) { 8033 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 8034 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8035 } 8036 } 8037 8038 CastKind Kind; 8039 Sema::AssignConvertType result = 8040 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8041 8042 // C99 6.5.16.1p2: The value of the right operand is converted to the 8043 // type of the assignment expression. 8044 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8045 // so that we can use references in built-in functions even in C. 8046 // The getNonReferenceType() call makes sure that the resulting expression 8047 // does not have reference type. 8048 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8049 QualType Ty = LHSType.getNonLValueExprType(Context); 8050 Expr *E = RHS.get(); 8051 8052 // Check for various Objective-C errors. If we are not reporting 8053 // diagnostics and just checking for errors, e.g., during overload 8054 // resolution, return Incompatible to indicate the failure. 8055 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8056 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8057 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8058 if (!Diagnose) 8059 return Incompatible; 8060 } 8061 if (getLangOpts().ObjC1 && 8062 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8063 E->getType(), E, Diagnose) || 8064 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8065 if (!Diagnose) 8066 return Incompatible; 8067 // Replace the expression with a corrected version and continue so we 8068 // can find further errors. 8069 RHS = E; 8070 return Compatible; 8071 } 8072 8073 if (ConvertRHS) 8074 RHS = ImpCastExprToType(E, Ty, Kind); 8075 } 8076 return result; 8077 } 8078 8079 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8080 ExprResult &RHS) { 8081 Diag(Loc, diag::err_typecheck_invalid_operands) 8082 << LHS.get()->getType() << RHS.get()->getType() 8083 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8084 return QualType(); 8085 } 8086 8087 // Diagnose cases where a scalar was implicitly converted to a vector and 8088 // diagnose the underlying types. Otherwise, diagnose the error 8089 // as invalid vector logical operands for non-C++ cases. 8090 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8091 ExprResult &RHS) { 8092 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8093 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8094 8095 bool LHSNatVec = LHSType->isVectorType(); 8096 bool RHSNatVec = RHSType->isVectorType(); 8097 8098 if (!(LHSNatVec && RHSNatVec)) { 8099 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8100 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8101 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8102 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8103 << Vector->getSourceRange(); 8104 return QualType(); 8105 } 8106 8107 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8108 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8109 << RHS.get()->getSourceRange(); 8110 8111 return QualType(); 8112 } 8113 8114 /// Try to convert a value of non-vector type to a vector type by converting 8115 /// the type to the element type of the vector and then performing a splat. 8116 /// If the language is OpenCL, we only use conversions that promote scalar 8117 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8118 /// for float->int. 8119 /// 8120 /// OpenCL V2.0 6.2.6.p2: 8121 /// An error shall occur if any scalar operand type has greater rank 8122 /// than the type of the vector element. 8123 /// 8124 /// \param scalar - if non-null, actually perform the conversions 8125 /// \return true if the operation fails (but without diagnosing the failure) 8126 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8127 QualType scalarTy, 8128 QualType vectorEltTy, 8129 QualType vectorTy, 8130 unsigned &DiagID) { 8131 // The conversion to apply to the scalar before splatting it, 8132 // if necessary. 8133 CastKind scalarCast = CK_NoOp; 8134 8135 if (vectorEltTy->isIntegralType(S.Context)) { 8136 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8137 (scalarTy->isIntegerType() && 8138 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8139 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8140 return true; 8141 } 8142 if (!scalarTy->isIntegralType(S.Context)) 8143 return true; 8144 scalarCast = CK_IntegralCast; 8145 } else if (vectorEltTy->isRealFloatingType()) { 8146 if (scalarTy->isRealFloatingType()) { 8147 if (S.getLangOpts().OpenCL && 8148 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8149 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8150 return true; 8151 } 8152 scalarCast = CK_FloatingCast; 8153 } 8154 else if (scalarTy->isIntegralType(S.Context)) 8155 scalarCast = CK_IntegralToFloating; 8156 else 8157 return true; 8158 } else { 8159 return true; 8160 } 8161 8162 // Adjust scalar if desired. 8163 if (scalar) { 8164 if (scalarCast != CK_NoOp) 8165 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8166 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8167 } 8168 return false; 8169 } 8170 8171 /// Convert vector E to a vector with the same number of elements but different 8172 /// element type. 8173 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8174 const auto *VecTy = E->getType()->getAs<VectorType>(); 8175 assert(VecTy && "Expression E must be a vector"); 8176 QualType NewVecTy = S.Context.getVectorType(ElementType, 8177 VecTy->getNumElements(), 8178 VecTy->getVectorKind()); 8179 8180 // Look through the implicit cast. Return the subexpression if its type is 8181 // NewVecTy. 8182 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8183 if (ICE->getSubExpr()->getType() == NewVecTy) 8184 return ICE->getSubExpr(); 8185 8186 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8187 return S.ImpCastExprToType(E, NewVecTy, Cast); 8188 } 8189 8190 /// Test if a (constant) integer Int can be casted to another integer type 8191 /// IntTy without losing precision. 8192 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8193 QualType OtherIntTy) { 8194 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8195 8196 // Reject cases where the value of the Int is unknown as that would 8197 // possibly cause truncation, but accept cases where the scalar can be 8198 // demoted without loss of precision. 8199 llvm::APSInt Result; 8200 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8201 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8202 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8203 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8204 8205 if (CstInt) { 8206 // If the scalar is constant and is of a higher order and has more active 8207 // bits that the vector element type, reject it. 8208 unsigned NumBits = IntSigned 8209 ? (Result.isNegative() ? Result.getMinSignedBits() 8210 : Result.getActiveBits()) 8211 : Result.getActiveBits(); 8212 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8213 return true; 8214 8215 // If the signedness of the scalar type and the vector element type 8216 // differs and the number of bits is greater than that of the vector 8217 // element reject it. 8218 return (IntSigned != OtherIntSigned && 8219 NumBits > S.Context.getIntWidth(OtherIntTy)); 8220 } 8221 8222 // Reject cases where the value of the scalar is not constant and it's 8223 // order is greater than that of the vector element type. 8224 return (Order < 0); 8225 } 8226 8227 /// Test if a (constant) integer Int can be casted to floating point type 8228 /// FloatTy without losing precision. 8229 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8230 QualType FloatTy) { 8231 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8232 8233 // Determine if the integer constant can be expressed as a floating point 8234 // number of the appropiate type. 8235 llvm::APSInt Result; 8236 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8237 uint64_t Bits = 0; 8238 if (CstInt) { 8239 // Reject constants that would be truncated if they were converted to 8240 // the floating point type. Test by simple to/from conversion. 8241 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8242 // could be avoided if there was a convertFromAPInt method 8243 // which could signal back if implicit truncation occurred. 8244 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8245 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8246 llvm::APFloat::rmTowardZero); 8247 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8248 !IntTy->hasSignedIntegerRepresentation()); 8249 bool Ignored = false; 8250 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8251 &Ignored); 8252 if (Result != ConvertBack) 8253 return true; 8254 } else { 8255 // Reject types that cannot be fully encoded into the mantissa of 8256 // the float. 8257 Bits = S.Context.getTypeSize(IntTy); 8258 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8259 S.Context.getFloatTypeSemantics(FloatTy)); 8260 if (Bits > FloatPrec) 8261 return true; 8262 } 8263 8264 return false; 8265 } 8266 8267 /// Attempt to convert and splat Scalar into a vector whose types matches 8268 /// Vector following GCC conversion rules. The rule is that implicit 8269 /// conversion can occur when Scalar can be casted to match Vector's element 8270 /// type without causing truncation of Scalar. 8271 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8272 ExprResult *Vector) { 8273 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8274 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8275 const VectorType *VT = VectorTy->getAs<VectorType>(); 8276 8277 assert(!isa<ExtVectorType>(VT) && 8278 "ExtVectorTypes should not be handled here!"); 8279 8280 QualType VectorEltTy = VT->getElementType(); 8281 8282 // Reject cases where the vector element type or the scalar element type are 8283 // not integral or floating point types. 8284 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8285 return true; 8286 8287 // The conversion to apply to the scalar before splatting it, 8288 // if necessary. 8289 CastKind ScalarCast = CK_NoOp; 8290 8291 // Accept cases where the vector elements are integers and the scalar is 8292 // an integer. 8293 // FIXME: Notionally if the scalar was a floating point value with a precise 8294 // integral representation, we could cast it to an appropriate integer 8295 // type and then perform the rest of the checks here. GCC will perform 8296 // this conversion in some cases as determined by the input language. 8297 // We should accept it on a language independent basis. 8298 if (VectorEltTy->isIntegralType(S.Context) && 8299 ScalarTy->isIntegralType(S.Context) && 8300 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8301 8302 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8303 return true; 8304 8305 ScalarCast = CK_IntegralCast; 8306 } else if (VectorEltTy->isRealFloatingType()) { 8307 if (ScalarTy->isRealFloatingType()) { 8308 8309 // Reject cases where the scalar type is not a constant and has a higher 8310 // Order than the vector element type. 8311 llvm::APFloat Result(0.0); 8312 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8313 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8314 if (!CstScalar && Order < 0) 8315 return true; 8316 8317 // If the scalar cannot be safely casted to the vector element type, 8318 // reject it. 8319 if (CstScalar) { 8320 bool Truncated = false; 8321 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8322 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8323 if (Truncated) 8324 return true; 8325 } 8326 8327 ScalarCast = CK_FloatingCast; 8328 } else if (ScalarTy->isIntegralType(S.Context)) { 8329 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8330 return true; 8331 8332 ScalarCast = CK_IntegralToFloating; 8333 } else 8334 return true; 8335 } 8336 8337 // Adjust scalar if desired. 8338 if (Scalar) { 8339 if (ScalarCast != CK_NoOp) 8340 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8341 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8342 } 8343 return false; 8344 } 8345 8346 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8347 SourceLocation Loc, bool IsCompAssign, 8348 bool AllowBothBool, 8349 bool AllowBoolConversions) { 8350 if (!IsCompAssign) { 8351 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8352 if (LHS.isInvalid()) 8353 return QualType(); 8354 } 8355 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8356 if (RHS.isInvalid()) 8357 return QualType(); 8358 8359 // For conversion purposes, we ignore any qualifiers. 8360 // For example, "const float" and "float" are equivalent. 8361 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8362 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8363 8364 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8365 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8366 assert(LHSVecType || RHSVecType); 8367 8368 // AltiVec-style "vector bool op vector bool" combinations are allowed 8369 // for some operators but not others. 8370 if (!AllowBothBool && 8371 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8372 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8373 return InvalidOperands(Loc, LHS, RHS); 8374 8375 // If the vector types are identical, return. 8376 if (Context.hasSameType(LHSType, RHSType)) 8377 return LHSType; 8378 8379 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8380 if (LHSVecType && RHSVecType && 8381 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8382 if (isa<ExtVectorType>(LHSVecType)) { 8383 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8384 return LHSType; 8385 } 8386 8387 if (!IsCompAssign) 8388 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8389 return RHSType; 8390 } 8391 8392 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8393 // can be mixed, with the result being the non-bool type. The non-bool 8394 // operand must have integer element type. 8395 if (AllowBoolConversions && LHSVecType && RHSVecType && 8396 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8397 (Context.getTypeSize(LHSVecType->getElementType()) == 8398 Context.getTypeSize(RHSVecType->getElementType()))) { 8399 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8400 LHSVecType->getElementType()->isIntegerType() && 8401 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8402 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8403 return LHSType; 8404 } 8405 if (!IsCompAssign && 8406 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8407 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8408 RHSVecType->getElementType()->isIntegerType()) { 8409 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8410 return RHSType; 8411 } 8412 } 8413 8414 // If there's a vector type and a scalar, try to convert the scalar to 8415 // the vector element type and splat. 8416 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8417 if (!RHSVecType) { 8418 if (isa<ExtVectorType>(LHSVecType)) { 8419 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8420 LHSVecType->getElementType(), LHSType, 8421 DiagID)) 8422 return LHSType; 8423 } else { 8424 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8425 return LHSType; 8426 } 8427 } 8428 if (!LHSVecType) { 8429 if (isa<ExtVectorType>(RHSVecType)) { 8430 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8431 LHSType, RHSVecType->getElementType(), 8432 RHSType, DiagID)) 8433 return RHSType; 8434 } else { 8435 if (LHS.get()->getValueKind() == VK_LValue || 8436 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8437 return RHSType; 8438 } 8439 } 8440 8441 // FIXME: The code below also handles conversion between vectors and 8442 // non-scalars, we should break this down into fine grained specific checks 8443 // and emit proper diagnostics. 8444 QualType VecType = LHSVecType ? LHSType : RHSType; 8445 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8446 QualType OtherType = LHSVecType ? RHSType : LHSType; 8447 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8448 if (isLaxVectorConversion(OtherType, VecType)) { 8449 // If we're allowing lax vector conversions, only the total (data) size 8450 // needs to be the same. For non compound assignment, if one of the types is 8451 // scalar, the result is always the vector type. 8452 if (!IsCompAssign) { 8453 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8454 return VecType; 8455 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8456 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8457 // type. Note that this is already done by non-compound assignments in 8458 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8459 // <1 x T> -> T. The result is also a vector type. 8460 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8461 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8462 ExprResult *RHSExpr = &RHS; 8463 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8464 return VecType; 8465 } 8466 } 8467 8468 // Okay, the expression is invalid. 8469 8470 // If there's a non-vector, non-real operand, diagnose that. 8471 if ((!RHSVecType && !RHSType->isRealType()) || 8472 (!LHSVecType && !LHSType->isRealType())) { 8473 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8474 << LHSType << RHSType 8475 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8476 return QualType(); 8477 } 8478 8479 // OpenCL V1.1 6.2.6.p1: 8480 // If the operands are of more than one vector type, then an error shall 8481 // occur. Implicit conversions between vector types are not permitted, per 8482 // section 6.2.1. 8483 if (getLangOpts().OpenCL && 8484 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8485 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8486 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8487 << RHSType; 8488 return QualType(); 8489 } 8490 8491 8492 // If there is a vector type that is not a ExtVector and a scalar, we reach 8493 // this point if scalar could not be converted to the vector's element type 8494 // without truncation. 8495 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8496 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8497 QualType Scalar = LHSVecType ? RHSType : LHSType; 8498 QualType Vector = LHSVecType ? LHSType : RHSType; 8499 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8500 Diag(Loc, 8501 diag::err_typecheck_vector_not_convertable_implict_truncation) 8502 << ScalarOrVector << Scalar << Vector; 8503 8504 return QualType(); 8505 } 8506 8507 // Otherwise, use the generic diagnostic. 8508 Diag(Loc, DiagID) 8509 << LHSType << RHSType 8510 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8511 return QualType(); 8512 } 8513 8514 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8515 // expression. These are mainly cases where the null pointer is used as an 8516 // integer instead of a pointer. 8517 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8518 SourceLocation Loc, bool IsCompare) { 8519 // The canonical way to check for a GNU null is with isNullPointerConstant, 8520 // but we use a bit of a hack here for speed; this is a relatively 8521 // hot path, and isNullPointerConstant is slow. 8522 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8523 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8524 8525 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8526 8527 // Avoid analyzing cases where the result will either be invalid (and 8528 // diagnosed as such) or entirely valid and not something to warn about. 8529 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8530 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8531 return; 8532 8533 // Comparison operations would not make sense with a null pointer no matter 8534 // what the other expression is. 8535 if (!IsCompare) { 8536 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8537 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8538 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8539 return; 8540 } 8541 8542 // The rest of the operations only make sense with a null pointer 8543 // if the other expression is a pointer. 8544 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8545 NonNullType->canDecayToPointerType()) 8546 return; 8547 8548 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8549 << LHSNull /* LHS is NULL */ << NonNullType 8550 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8551 } 8552 8553 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8554 ExprResult &RHS, 8555 SourceLocation Loc, bool IsDiv) { 8556 // Check for division/remainder by zero. 8557 llvm::APSInt RHSValue; 8558 if (!RHS.get()->isValueDependent() && 8559 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8560 S.DiagRuntimeBehavior(Loc, RHS.get(), 8561 S.PDiag(diag::warn_remainder_division_by_zero) 8562 << IsDiv << RHS.get()->getSourceRange()); 8563 } 8564 8565 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8566 SourceLocation Loc, 8567 bool IsCompAssign, bool IsDiv) { 8568 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8569 8570 if (LHS.get()->getType()->isVectorType() || 8571 RHS.get()->getType()->isVectorType()) 8572 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8573 /*AllowBothBool*/getLangOpts().AltiVec, 8574 /*AllowBoolConversions*/false); 8575 8576 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8577 if (LHS.isInvalid() || RHS.isInvalid()) 8578 return QualType(); 8579 8580 8581 if (compType.isNull() || !compType->isArithmeticType()) 8582 return InvalidOperands(Loc, LHS, RHS); 8583 if (IsDiv) 8584 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8585 return compType; 8586 } 8587 8588 QualType Sema::CheckRemainderOperands( 8589 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8590 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8591 8592 if (LHS.get()->getType()->isVectorType() || 8593 RHS.get()->getType()->isVectorType()) { 8594 if (LHS.get()->getType()->hasIntegerRepresentation() && 8595 RHS.get()->getType()->hasIntegerRepresentation()) 8596 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8597 /*AllowBothBool*/getLangOpts().AltiVec, 8598 /*AllowBoolConversions*/false); 8599 return InvalidOperands(Loc, LHS, RHS); 8600 } 8601 8602 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8603 if (LHS.isInvalid() || RHS.isInvalid()) 8604 return QualType(); 8605 8606 if (compType.isNull() || !compType->isIntegerType()) 8607 return InvalidOperands(Loc, LHS, RHS); 8608 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8609 return compType; 8610 } 8611 8612 /// \brief Diagnose invalid arithmetic on two void pointers. 8613 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8614 Expr *LHSExpr, Expr *RHSExpr) { 8615 S.Diag(Loc, S.getLangOpts().CPlusPlus 8616 ? diag::err_typecheck_pointer_arith_void_type 8617 : diag::ext_gnu_void_ptr) 8618 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8619 << RHSExpr->getSourceRange(); 8620 } 8621 8622 /// \brief Diagnose invalid arithmetic on a void pointer. 8623 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8624 Expr *Pointer) { 8625 S.Diag(Loc, S.getLangOpts().CPlusPlus 8626 ? diag::err_typecheck_pointer_arith_void_type 8627 : diag::ext_gnu_void_ptr) 8628 << 0 /* one pointer */ << Pointer->getSourceRange(); 8629 } 8630 8631 /// \brief Diagnose invalid arithmetic on a null pointer. 8632 /// 8633 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8634 /// idiom, which we recognize as a GNU extension. 8635 /// 8636 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8637 Expr *Pointer, bool IsGNUIdiom) { 8638 if (IsGNUIdiom) 8639 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8640 << Pointer->getSourceRange(); 8641 else 8642 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8643 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8644 } 8645 8646 /// \brief Diagnose invalid arithmetic on two function pointers. 8647 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8648 Expr *LHS, Expr *RHS) { 8649 assert(LHS->getType()->isAnyPointerType()); 8650 assert(RHS->getType()->isAnyPointerType()); 8651 S.Diag(Loc, S.getLangOpts().CPlusPlus 8652 ? diag::err_typecheck_pointer_arith_function_type 8653 : diag::ext_gnu_ptr_func_arith) 8654 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8655 // We only show the second type if it differs from the first. 8656 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8657 RHS->getType()) 8658 << RHS->getType()->getPointeeType() 8659 << LHS->getSourceRange() << RHS->getSourceRange(); 8660 } 8661 8662 /// \brief Diagnose invalid arithmetic on a function pointer. 8663 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8664 Expr *Pointer) { 8665 assert(Pointer->getType()->isAnyPointerType()); 8666 S.Diag(Loc, S.getLangOpts().CPlusPlus 8667 ? diag::err_typecheck_pointer_arith_function_type 8668 : diag::ext_gnu_ptr_func_arith) 8669 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8670 << 0 /* one pointer, so only one type */ 8671 << Pointer->getSourceRange(); 8672 } 8673 8674 /// \brief Emit error if Operand is incomplete pointer type 8675 /// 8676 /// \returns True if pointer has incomplete type 8677 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8678 Expr *Operand) { 8679 QualType ResType = Operand->getType(); 8680 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8681 ResType = ResAtomicType->getValueType(); 8682 8683 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8684 QualType PointeeTy = ResType->getPointeeType(); 8685 return S.RequireCompleteType(Loc, PointeeTy, 8686 diag::err_typecheck_arithmetic_incomplete_type, 8687 PointeeTy, Operand->getSourceRange()); 8688 } 8689 8690 /// \brief Check the validity of an arithmetic pointer operand. 8691 /// 8692 /// If the operand has pointer type, this code will check for pointer types 8693 /// which are invalid in arithmetic operations. These will be diagnosed 8694 /// appropriately, including whether or not the use is supported as an 8695 /// extension. 8696 /// 8697 /// \returns True when the operand is valid to use (even if as an extension). 8698 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8699 Expr *Operand) { 8700 QualType ResType = Operand->getType(); 8701 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8702 ResType = ResAtomicType->getValueType(); 8703 8704 if (!ResType->isAnyPointerType()) return true; 8705 8706 QualType PointeeTy = ResType->getPointeeType(); 8707 if (PointeeTy->isVoidType()) { 8708 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8709 return !S.getLangOpts().CPlusPlus; 8710 } 8711 if (PointeeTy->isFunctionType()) { 8712 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8713 return !S.getLangOpts().CPlusPlus; 8714 } 8715 8716 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8717 8718 return true; 8719 } 8720 8721 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8722 /// operands. 8723 /// 8724 /// This routine will diagnose any invalid arithmetic on pointer operands much 8725 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8726 /// for emitting a single diagnostic even for operations where both LHS and RHS 8727 /// are (potentially problematic) pointers. 8728 /// 8729 /// \returns True when the operand is valid to use (even if as an extension). 8730 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8731 Expr *LHSExpr, Expr *RHSExpr) { 8732 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8733 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8734 if (!isLHSPointer && !isRHSPointer) return true; 8735 8736 QualType LHSPointeeTy, RHSPointeeTy; 8737 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8738 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8739 8740 // if both are pointers check if operation is valid wrt address spaces 8741 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8742 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8743 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8744 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8745 S.Diag(Loc, 8746 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8747 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8748 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8749 return false; 8750 } 8751 } 8752 8753 // Check for arithmetic on pointers to incomplete types. 8754 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8755 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8756 if (isLHSVoidPtr || isRHSVoidPtr) { 8757 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8758 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8759 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8760 8761 return !S.getLangOpts().CPlusPlus; 8762 } 8763 8764 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8765 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8766 if (isLHSFuncPtr || isRHSFuncPtr) { 8767 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8768 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8769 RHSExpr); 8770 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8771 8772 return !S.getLangOpts().CPlusPlus; 8773 } 8774 8775 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8776 return false; 8777 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8778 return false; 8779 8780 return true; 8781 } 8782 8783 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8784 /// literal. 8785 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8786 Expr *LHSExpr, Expr *RHSExpr) { 8787 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8788 Expr* IndexExpr = RHSExpr; 8789 if (!StrExpr) { 8790 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8791 IndexExpr = LHSExpr; 8792 } 8793 8794 bool IsStringPlusInt = StrExpr && 8795 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8796 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8797 return; 8798 8799 llvm::APSInt index; 8800 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8801 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8802 if (index.isNonNegative() && 8803 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8804 index.isUnsigned())) 8805 return; 8806 } 8807 8808 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8809 Self.Diag(OpLoc, diag::warn_string_plus_int) 8810 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8811 8812 // Only print a fixit for "str" + int, not for int + "str". 8813 if (IndexExpr == RHSExpr) { 8814 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8815 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8816 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8817 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8818 << FixItHint::CreateInsertion(EndLoc, "]"); 8819 } else 8820 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8821 } 8822 8823 /// \brief Emit a warning when adding a char literal to a string. 8824 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8825 Expr *LHSExpr, Expr *RHSExpr) { 8826 const Expr *StringRefExpr = LHSExpr; 8827 const CharacterLiteral *CharExpr = 8828 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8829 8830 if (!CharExpr) { 8831 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8832 StringRefExpr = RHSExpr; 8833 } 8834 8835 if (!CharExpr || !StringRefExpr) 8836 return; 8837 8838 const QualType StringType = StringRefExpr->getType(); 8839 8840 // Return if not a PointerType. 8841 if (!StringType->isAnyPointerType()) 8842 return; 8843 8844 // Return if not a CharacterType. 8845 if (!StringType->getPointeeType()->isAnyCharacterType()) 8846 return; 8847 8848 ASTContext &Ctx = Self.getASTContext(); 8849 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8850 8851 const QualType CharType = CharExpr->getType(); 8852 if (!CharType->isAnyCharacterType() && 8853 CharType->isIntegerType() && 8854 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8855 Self.Diag(OpLoc, diag::warn_string_plus_char) 8856 << DiagRange << Ctx.CharTy; 8857 } else { 8858 Self.Diag(OpLoc, diag::warn_string_plus_char) 8859 << DiagRange << CharExpr->getType(); 8860 } 8861 8862 // Only print a fixit for str + char, not for char + str. 8863 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8864 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8865 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8866 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8867 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8868 << FixItHint::CreateInsertion(EndLoc, "]"); 8869 } else { 8870 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8871 } 8872 } 8873 8874 /// \brief Emit error when two pointers are incompatible. 8875 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8876 Expr *LHSExpr, Expr *RHSExpr) { 8877 assert(LHSExpr->getType()->isAnyPointerType()); 8878 assert(RHSExpr->getType()->isAnyPointerType()); 8879 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8880 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8881 << RHSExpr->getSourceRange(); 8882 } 8883 8884 // C99 6.5.6 8885 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8886 SourceLocation Loc, BinaryOperatorKind Opc, 8887 QualType* CompLHSTy) { 8888 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8889 8890 if (LHS.get()->getType()->isVectorType() || 8891 RHS.get()->getType()->isVectorType()) { 8892 QualType compType = CheckVectorOperands( 8893 LHS, RHS, Loc, CompLHSTy, 8894 /*AllowBothBool*/getLangOpts().AltiVec, 8895 /*AllowBoolConversions*/getLangOpts().ZVector); 8896 if (CompLHSTy) *CompLHSTy = compType; 8897 return compType; 8898 } 8899 8900 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8901 if (LHS.isInvalid() || RHS.isInvalid()) 8902 return QualType(); 8903 8904 // Diagnose "string literal" '+' int and string '+' "char literal". 8905 if (Opc == BO_Add) { 8906 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8907 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8908 } 8909 8910 // handle the common case first (both operands are arithmetic). 8911 if (!compType.isNull() && compType->isArithmeticType()) { 8912 if (CompLHSTy) *CompLHSTy = compType; 8913 return compType; 8914 } 8915 8916 // Type-checking. Ultimately the pointer's going to be in PExp; 8917 // note that we bias towards the LHS being the pointer. 8918 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8919 8920 bool isObjCPointer; 8921 if (PExp->getType()->isPointerType()) { 8922 isObjCPointer = false; 8923 } else if (PExp->getType()->isObjCObjectPointerType()) { 8924 isObjCPointer = true; 8925 } else { 8926 std::swap(PExp, IExp); 8927 if (PExp->getType()->isPointerType()) { 8928 isObjCPointer = false; 8929 } else if (PExp->getType()->isObjCObjectPointerType()) { 8930 isObjCPointer = true; 8931 } else { 8932 return InvalidOperands(Loc, LHS, RHS); 8933 } 8934 } 8935 assert(PExp->getType()->isAnyPointerType()); 8936 8937 if (!IExp->getType()->isIntegerType()) 8938 return InvalidOperands(Loc, LHS, RHS); 8939 8940 // Adding to a null pointer results in undefined behavior. 8941 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8942 Context, Expr::NPC_ValueDependentIsNotNull)) { 8943 // In C++ adding zero to a null pointer is defined. 8944 llvm::APSInt KnownVal; 8945 if (!getLangOpts().CPlusPlus || 8946 (!IExp->isValueDependent() && 8947 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8948 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8949 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8950 Context, BO_Add, PExp, IExp); 8951 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8952 } 8953 } 8954 8955 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8956 return QualType(); 8957 8958 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8959 return QualType(); 8960 8961 // Check array bounds for pointer arithemtic 8962 CheckArrayAccess(PExp, IExp); 8963 8964 if (CompLHSTy) { 8965 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8966 if (LHSTy.isNull()) { 8967 LHSTy = LHS.get()->getType(); 8968 if (LHSTy->isPromotableIntegerType()) 8969 LHSTy = Context.getPromotedIntegerType(LHSTy); 8970 } 8971 *CompLHSTy = LHSTy; 8972 } 8973 8974 return PExp->getType(); 8975 } 8976 8977 // C99 6.5.6 8978 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8979 SourceLocation Loc, 8980 QualType* CompLHSTy) { 8981 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8982 8983 if (LHS.get()->getType()->isVectorType() || 8984 RHS.get()->getType()->isVectorType()) { 8985 QualType compType = CheckVectorOperands( 8986 LHS, RHS, Loc, CompLHSTy, 8987 /*AllowBothBool*/getLangOpts().AltiVec, 8988 /*AllowBoolConversions*/getLangOpts().ZVector); 8989 if (CompLHSTy) *CompLHSTy = compType; 8990 return compType; 8991 } 8992 8993 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8994 if (LHS.isInvalid() || RHS.isInvalid()) 8995 return QualType(); 8996 8997 // Enforce type constraints: C99 6.5.6p3. 8998 8999 // Handle the common case first (both operands are arithmetic). 9000 if (!compType.isNull() && compType->isArithmeticType()) { 9001 if (CompLHSTy) *CompLHSTy = compType; 9002 return compType; 9003 } 9004 9005 // Either ptr - int or ptr - ptr. 9006 if (LHS.get()->getType()->isAnyPointerType()) { 9007 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9008 9009 // Diagnose bad cases where we step over interface counts. 9010 if (LHS.get()->getType()->isObjCObjectPointerType() && 9011 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9012 return QualType(); 9013 9014 // The result type of a pointer-int computation is the pointer type. 9015 if (RHS.get()->getType()->isIntegerType()) { 9016 // Subtracting from a null pointer should produce a warning. 9017 // The last argument to the diagnose call says this doesn't match the 9018 // GNU int-to-pointer idiom. 9019 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9020 Expr::NPC_ValueDependentIsNotNull)) { 9021 // In C++ adding zero to a null pointer is defined. 9022 llvm::APSInt KnownVal; 9023 if (!getLangOpts().CPlusPlus || 9024 (!RHS.get()->isValueDependent() && 9025 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9026 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9027 } 9028 } 9029 9030 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9031 return QualType(); 9032 9033 // Check array bounds for pointer arithemtic 9034 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9035 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9036 9037 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9038 return LHS.get()->getType(); 9039 } 9040 9041 // Handle pointer-pointer subtractions. 9042 if (const PointerType *RHSPTy 9043 = RHS.get()->getType()->getAs<PointerType>()) { 9044 QualType rpointee = RHSPTy->getPointeeType(); 9045 9046 if (getLangOpts().CPlusPlus) { 9047 // Pointee types must be the same: C++ [expr.add] 9048 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9049 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9050 } 9051 } else { 9052 // Pointee types must be compatible C99 6.5.6p3 9053 if (!Context.typesAreCompatible( 9054 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9055 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9056 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9057 return QualType(); 9058 } 9059 } 9060 9061 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9062 LHS.get(), RHS.get())) 9063 return QualType(); 9064 9065 // FIXME: Add warnings for nullptr - ptr. 9066 9067 // The pointee type may have zero size. As an extension, a structure or 9068 // union may have zero size or an array may have zero length. In this 9069 // case subtraction does not make sense. 9070 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9071 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9072 if (ElementSize.isZero()) { 9073 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9074 << rpointee.getUnqualifiedType() 9075 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9076 } 9077 } 9078 9079 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9080 return Context.getPointerDiffType(); 9081 } 9082 } 9083 9084 return InvalidOperands(Loc, LHS, RHS); 9085 } 9086 9087 static bool isScopedEnumerationType(QualType T) { 9088 if (const EnumType *ET = T->getAs<EnumType>()) 9089 return ET->getDecl()->isScoped(); 9090 return false; 9091 } 9092 9093 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9094 SourceLocation Loc, BinaryOperatorKind Opc, 9095 QualType LHSType) { 9096 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9097 // so skip remaining warnings as we don't want to modify values within Sema. 9098 if (S.getLangOpts().OpenCL) 9099 return; 9100 9101 llvm::APSInt Right; 9102 // Check right/shifter operand 9103 if (RHS.get()->isValueDependent() || 9104 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9105 return; 9106 9107 if (Right.isNegative()) { 9108 S.DiagRuntimeBehavior(Loc, RHS.get(), 9109 S.PDiag(diag::warn_shift_negative) 9110 << RHS.get()->getSourceRange()); 9111 return; 9112 } 9113 llvm::APInt LeftBits(Right.getBitWidth(), 9114 S.Context.getTypeSize(LHS.get()->getType())); 9115 if (Right.uge(LeftBits)) { 9116 S.DiagRuntimeBehavior(Loc, RHS.get(), 9117 S.PDiag(diag::warn_shift_gt_typewidth) 9118 << RHS.get()->getSourceRange()); 9119 return; 9120 } 9121 if (Opc != BO_Shl) 9122 return; 9123 9124 // When left shifting an ICE which is signed, we can check for overflow which 9125 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9126 // integers have defined behavior modulo one more than the maximum value 9127 // representable in the result type, so never warn for those. 9128 llvm::APSInt Left; 9129 if (LHS.get()->isValueDependent() || 9130 LHSType->hasUnsignedIntegerRepresentation() || 9131 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9132 return; 9133 9134 // If LHS does not have a signed type and non-negative value 9135 // then, the behavior is undefined. Warn about it. 9136 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9137 S.DiagRuntimeBehavior(Loc, LHS.get(), 9138 S.PDiag(diag::warn_shift_lhs_negative) 9139 << LHS.get()->getSourceRange()); 9140 return; 9141 } 9142 9143 llvm::APInt ResultBits = 9144 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9145 if (LeftBits.uge(ResultBits)) 9146 return; 9147 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9148 Result = Result.shl(Right); 9149 9150 // Print the bit representation of the signed integer as an unsigned 9151 // hexadecimal number. 9152 SmallString<40> HexResult; 9153 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9154 9155 // If we are only missing a sign bit, this is less likely to result in actual 9156 // bugs -- if the result is cast back to an unsigned type, it will have the 9157 // expected value. Thus we place this behind a different warning that can be 9158 // turned off separately if needed. 9159 if (LeftBits == ResultBits - 1) { 9160 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9161 << HexResult << LHSType 9162 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9163 return; 9164 } 9165 9166 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9167 << HexResult.str() << Result.getMinSignedBits() << LHSType 9168 << Left.getBitWidth() << LHS.get()->getSourceRange() 9169 << RHS.get()->getSourceRange(); 9170 } 9171 9172 /// \brief Return the resulting type when a vector is shifted 9173 /// by a scalar or vector shift amount. 9174 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9175 SourceLocation Loc, bool IsCompAssign) { 9176 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9177 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9178 !LHS.get()->getType()->isVectorType()) { 9179 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9180 << RHS.get()->getType() << LHS.get()->getType() 9181 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9182 return QualType(); 9183 } 9184 9185 if (!IsCompAssign) { 9186 LHS = S.UsualUnaryConversions(LHS.get()); 9187 if (LHS.isInvalid()) return QualType(); 9188 } 9189 9190 RHS = S.UsualUnaryConversions(RHS.get()); 9191 if (RHS.isInvalid()) return QualType(); 9192 9193 QualType LHSType = LHS.get()->getType(); 9194 // Note that LHS might be a scalar because the routine calls not only in 9195 // OpenCL case. 9196 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9197 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9198 9199 // Note that RHS might not be a vector. 9200 QualType RHSType = RHS.get()->getType(); 9201 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9202 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9203 9204 // The operands need to be integers. 9205 if (!LHSEleType->isIntegerType()) { 9206 S.Diag(Loc, diag::err_typecheck_expect_int) 9207 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9208 return QualType(); 9209 } 9210 9211 if (!RHSEleType->isIntegerType()) { 9212 S.Diag(Loc, diag::err_typecheck_expect_int) 9213 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9214 return QualType(); 9215 } 9216 9217 if (!LHSVecTy) { 9218 assert(RHSVecTy); 9219 if (IsCompAssign) 9220 return RHSType; 9221 if (LHSEleType != RHSEleType) { 9222 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9223 LHSEleType = RHSEleType; 9224 } 9225 QualType VecTy = 9226 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9227 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9228 LHSType = VecTy; 9229 } else if (RHSVecTy) { 9230 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9231 // are applied component-wise. So if RHS is a vector, then ensure 9232 // that the number of elements is the same as LHS... 9233 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9234 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9235 << LHS.get()->getType() << RHS.get()->getType() 9236 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9237 return QualType(); 9238 } 9239 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9240 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9241 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9242 if (LHSBT != RHSBT && 9243 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9244 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9245 << LHS.get()->getType() << RHS.get()->getType() 9246 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9247 } 9248 } 9249 } else { 9250 // ...else expand RHS to match the number of elements in LHS. 9251 QualType VecTy = 9252 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9253 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9254 } 9255 9256 return LHSType; 9257 } 9258 9259 // C99 6.5.7 9260 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9261 SourceLocation Loc, BinaryOperatorKind Opc, 9262 bool IsCompAssign) { 9263 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9264 9265 // Vector shifts promote their scalar inputs to vector type. 9266 if (LHS.get()->getType()->isVectorType() || 9267 RHS.get()->getType()->isVectorType()) { 9268 if (LangOpts.ZVector) { 9269 // The shift operators for the z vector extensions work basically 9270 // like general shifts, except that neither the LHS nor the RHS is 9271 // allowed to be a "vector bool". 9272 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9273 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9274 return InvalidOperands(Loc, LHS, RHS); 9275 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9276 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9277 return InvalidOperands(Loc, LHS, RHS); 9278 } 9279 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9280 } 9281 9282 // Shifts don't perform usual arithmetic conversions, they just do integer 9283 // promotions on each operand. C99 6.5.7p3 9284 9285 // For the LHS, do usual unary conversions, but then reset them away 9286 // if this is a compound assignment. 9287 ExprResult OldLHS = LHS; 9288 LHS = UsualUnaryConversions(LHS.get()); 9289 if (LHS.isInvalid()) 9290 return QualType(); 9291 QualType LHSType = LHS.get()->getType(); 9292 if (IsCompAssign) LHS = OldLHS; 9293 9294 // The RHS is simpler. 9295 RHS = UsualUnaryConversions(RHS.get()); 9296 if (RHS.isInvalid()) 9297 return QualType(); 9298 QualType RHSType = RHS.get()->getType(); 9299 9300 // C99 6.5.7p2: Each of the operands shall have integer type. 9301 if (!LHSType->hasIntegerRepresentation() || 9302 !RHSType->hasIntegerRepresentation()) 9303 return InvalidOperands(Loc, LHS, RHS); 9304 9305 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9306 // hasIntegerRepresentation() above instead of this. 9307 if (isScopedEnumerationType(LHSType) || 9308 isScopedEnumerationType(RHSType)) { 9309 return InvalidOperands(Loc, LHS, RHS); 9310 } 9311 // Sanity-check shift operands 9312 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9313 9314 // "The type of the result is that of the promoted left operand." 9315 return LHSType; 9316 } 9317 9318 /// If two different enums are compared, raise a warning. 9319 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9320 Expr *RHS) { 9321 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9322 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9323 9324 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9325 if (!LHSEnumType) 9326 return; 9327 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9328 if (!RHSEnumType) 9329 return; 9330 9331 // Ignore anonymous enums. 9332 if (!LHSEnumType->getDecl()->getIdentifier() && 9333 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9334 return; 9335 if (!RHSEnumType->getDecl()->getIdentifier() && 9336 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9337 return; 9338 9339 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9340 return; 9341 9342 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9343 << LHSStrippedType << RHSStrippedType 9344 << LHS->getSourceRange() << RHS->getSourceRange(); 9345 } 9346 9347 /// \brief Diagnose bad pointer comparisons. 9348 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9349 ExprResult &LHS, ExprResult &RHS, 9350 bool IsError) { 9351 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9352 : diag::ext_typecheck_comparison_of_distinct_pointers) 9353 << LHS.get()->getType() << RHS.get()->getType() 9354 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9355 } 9356 9357 /// \brief Returns false if the pointers are converted to a composite type, 9358 /// true otherwise. 9359 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9360 ExprResult &LHS, ExprResult &RHS) { 9361 // C++ [expr.rel]p2: 9362 // [...] Pointer conversions (4.10) and qualification 9363 // conversions (4.4) are performed on pointer operands (or on 9364 // a pointer operand and a null pointer constant) to bring 9365 // them to their composite pointer type. [...] 9366 // 9367 // C++ [expr.eq]p1 uses the same notion for (in)equality 9368 // comparisons of pointers. 9369 9370 QualType LHSType = LHS.get()->getType(); 9371 QualType RHSType = RHS.get()->getType(); 9372 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9373 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9374 9375 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9376 if (T.isNull()) { 9377 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9378 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9379 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9380 else 9381 S.InvalidOperands(Loc, LHS, RHS); 9382 return true; 9383 } 9384 9385 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9386 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9387 return false; 9388 } 9389 9390 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9391 ExprResult &LHS, 9392 ExprResult &RHS, 9393 bool IsError) { 9394 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9395 : diag::ext_typecheck_comparison_of_fptr_to_void) 9396 << LHS.get()->getType() << RHS.get()->getType() 9397 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9398 } 9399 9400 static bool isObjCObjectLiteral(ExprResult &E) { 9401 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9402 case Stmt::ObjCArrayLiteralClass: 9403 case Stmt::ObjCDictionaryLiteralClass: 9404 case Stmt::ObjCStringLiteralClass: 9405 case Stmt::ObjCBoxedExprClass: 9406 return true; 9407 default: 9408 // Note that ObjCBoolLiteral is NOT an object literal! 9409 return false; 9410 } 9411 } 9412 9413 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9414 const ObjCObjectPointerType *Type = 9415 LHS->getType()->getAs<ObjCObjectPointerType>(); 9416 9417 // If this is not actually an Objective-C object, bail out. 9418 if (!Type) 9419 return false; 9420 9421 // Get the LHS object's interface type. 9422 QualType InterfaceType = Type->getPointeeType(); 9423 9424 // If the RHS isn't an Objective-C object, bail out. 9425 if (!RHS->getType()->isObjCObjectPointerType()) 9426 return false; 9427 9428 // Try to find the -isEqual: method. 9429 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9430 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9431 InterfaceType, 9432 /*instance=*/true); 9433 if (!Method) { 9434 if (Type->isObjCIdType()) { 9435 // For 'id', just check the global pool. 9436 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9437 /*receiverId=*/true); 9438 } else { 9439 // Check protocols. 9440 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9441 /*instance=*/true); 9442 } 9443 } 9444 9445 if (!Method) 9446 return false; 9447 9448 QualType T = Method->parameters()[0]->getType(); 9449 if (!T->isObjCObjectPointerType()) 9450 return false; 9451 9452 QualType R = Method->getReturnType(); 9453 if (!R->isScalarType()) 9454 return false; 9455 9456 return true; 9457 } 9458 9459 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9460 FromE = FromE->IgnoreParenImpCasts(); 9461 switch (FromE->getStmtClass()) { 9462 default: 9463 break; 9464 case Stmt::ObjCStringLiteralClass: 9465 // "string literal" 9466 return LK_String; 9467 case Stmt::ObjCArrayLiteralClass: 9468 // "array literal" 9469 return LK_Array; 9470 case Stmt::ObjCDictionaryLiteralClass: 9471 // "dictionary literal" 9472 return LK_Dictionary; 9473 case Stmt::BlockExprClass: 9474 return LK_Block; 9475 case Stmt::ObjCBoxedExprClass: { 9476 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9477 switch (Inner->getStmtClass()) { 9478 case Stmt::IntegerLiteralClass: 9479 case Stmt::FloatingLiteralClass: 9480 case Stmt::CharacterLiteralClass: 9481 case Stmt::ObjCBoolLiteralExprClass: 9482 case Stmt::CXXBoolLiteralExprClass: 9483 // "numeric literal" 9484 return LK_Numeric; 9485 case Stmt::ImplicitCastExprClass: { 9486 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9487 // Boolean literals can be represented by implicit casts. 9488 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9489 return LK_Numeric; 9490 break; 9491 } 9492 default: 9493 break; 9494 } 9495 return LK_Boxed; 9496 } 9497 } 9498 return LK_None; 9499 } 9500 9501 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9502 ExprResult &LHS, ExprResult &RHS, 9503 BinaryOperator::Opcode Opc){ 9504 Expr *Literal; 9505 Expr *Other; 9506 if (isObjCObjectLiteral(LHS)) { 9507 Literal = LHS.get(); 9508 Other = RHS.get(); 9509 } else { 9510 Literal = RHS.get(); 9511 Other = LHS.get(); 9512 } 9513 9514 // Don't warn on comparisons against nil. 9515 Other = Other->IgnoreParenCasts(); 9516 if (Other->isNullPointerConstant(S.getASTContext(), 9517 Expr::NPC_ValueDependentIsNotNull)) 9518 return; 9519 9520 // This should be kept in sync with warn_objc_literal_comparison. 9521 // LK_String should always be after the other literals, since it has its own 9522 // warning flag. 9523 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9524 assert(LiteralKind != Sema::LK_Block); 9525 if (LiteralKind == Sema::LK_None) { 9526 llvm_unreachable("Unknown Objective-C object literal kind"); 9527 } 9528 9529 if (LiteralKind == Sema::LK_String) 9530 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9531 << Literal->getSourceRange(); 9532 else 9533 S.Diag(Loc, diag::warn_objc_literal_comparison) 9534 << LiteralKind << Literal->getSourceRange(); 9535 9536 if (BinaryOperator::isEqualityOp(Opc) && 9537 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9538 SourceLocation Start = LHS.get()->getLocStart(); 9539 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9540 CharSourceRange OpRange = 9541 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9542 9543 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9544 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9545 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9546 << FixItHint::CreateInsertion(End, "]"); 9547 } 9548 } 9549 9550 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9551 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9552 ExprResult &RHS, SourceLocation Loc, 9553 BinaryOperatorKind Opc) { 9554 // Check that left hand side is !something. 9555 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9556 if (!UO || UO->getOpcode() != UO_LNot) return; 9557 9558 // Only check if the right hand side is non-bool arithmetic type. 9559 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9560 9561 // Make sure that the something in !something is not bool. 9562 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9563 if (SubExpr->isKnownToHaveBooleanValue()) return; 9564 9565 // Emit warning. 9566 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9567 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9568 << Loc << IsBitwiseOp; 9569 9570 // First note suggest !(x < y) 9571 SourceLocation FirstOpen = SubExpr->getLocStart(); 9572 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9573 FirstClose = S.getLocForEndOfToken(FirstClose); 9574 if (FirstClose.isInvalid()) 9575 FirstOpen = SourceLocation(); 9576 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9577 << IsBitwiseOp 9578 << FixItHint::CreateInsertion(FirstOpen, "(") 9579 << FixItHint::CreateInsertion(FirstClose, ")"); 9580 9581 // Second note suggests (!x) < y 9582 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9583 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9584 SecondClose = S.getLocForEndOfToken(SecondClose); 9585 if (SecondClose.isInvalid()) 9586 SecondOpen = SourceLocation(); 9587 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9588 << FixItHint::CreateInsertion(SecondOpen, "(") 9589 << FixItHint::CreateInsertion(SecondClose, ")"); 9590 } 9591 9592 // Get the decl for a simple expression: a reference to a variable, 9593 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9594 static ValueDecl *getCompareDecl(Expr *E) { 9595 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9596 return DR->getDecl(); 9597 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9598 if (Ivar->isFreeIvar()) 9599 return Ivar->getDecl(); 9600 } 9601 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9602 if (Mem->isImplicitAccess()) 9603 return Mem->getMemberDecl(); 9604 } 9605 return nullptr; 9606 } 9607 9608 /// Diagnose some forms of syntactically-obvious tautological comparison. 9609 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9610 Expr *LHS, Expr *RHS, 9611 BinaryOperatorKind Opc) { 9612 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9613 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9614 9615 QualType LHSType = LHS->getType(); 9616 if (LHSType->hasFloatingRepresentation() || 9617 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9618 LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() || 9619 S.inTemplateInstantiation()) 9620 return; 9621 9622 // For non-floating point types, check for self-comparisons of the form 9623 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9624 // often indicate logic errors in the program. 9625 // 9626 // NOTE: Don't warn about comparison expressions resulting from macro 9627 // expansion. Also don't warn about comparisons which are only self 9628 // comparisons within a template instantiation. The warnings should catch 9629 // obvious cases in the definition of the template anyways. The idea is to 9630 // warn when the typed comparison operator will always evaluate to the same 9631 // result. 9632 ValueDecl *DL = getCompareDecl(LHSStripped); 9633 ValueDecl *DR = getCompareDecl(RHSStripped); 9634 if (DL && DR && declaresSameEntity(DL, DR)) { 9635 StringRef Result; 9636 switch (Opc) { 9637 case BO_EQ: case BO_LE: case BO_GE: 9638 Result = "true"; 9639 break; 9640 case BO_NE: case BO_LT: case BO_GT: 9641 Result = "false"; 9642 break; 9643 case BO_Cmp: 9644 Result = "'std::strong_ordering::equal'"; 9645 break; 9646 default: 9647 break; 9648 } 9649 S.DiagRuntimeBehavior(Loc, nullptr, 9650 S.PDiag(diag::warn_comparison_always) 9651 << 0 /*self-comparison*/ << !Result.empty() 9652 << Result); 9653 } else if (DL && DR && 9654 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9655 !DL->isWeak() && !DR->isWeak()) { 9656 // What is it always going to evaluate to? 9657 StringRef Result; 9658 switch(Opc) { 9659 case BO_EQ: // e.g. array1 == array2 9660 Result = "false"; 9661 break; 9662 case BO_NE: // e.g. array1 != array2 9663 Result = "true"; 9664 break; 9665 default: // e.g. array1 <= array2 9666 // The best we can say is 'a constant' 9667 break; 9668 } 9669 S.DiagRuntimeBehavior(Loc, nullptr, 9670 S.PDiag(diag::warn_comparison_always) 9671 << 1 /*array comparison*/ 9672 << !Result.empty() << Result); 9673 } 9674 9675 if (isa<CastExpr>(LHSStripped)) 9676 LHSStripped = LHSStripped->IgnoreParenCasts(); 9677 if (isa<CastExpr>(RHSStripped)) 9678 RHSStripped = RHSStripped->IgnoreParenCasts(); 9679 9680 // Warn about comparisons against a string constant (unless the other 9681 // operand is null); the user probably wants strcmp. 9682 Expr *LiteralString = nullptr; 9683 Expr *LiteralStringStripped = nullptr; 9684 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9685 !RHSStripped->isNullPointerConstant(S.Context, 9686 Expr::NPC_ValueDependentIsNull)) { 9687 LiteralString = LHS; 9688 LiteralStringStripped = LHSStripped; 9689 } else if ((isa<StringLiteral>(RHSStripped) || 9690 isa<ObjCEncodeExpr>(RHSStripped)) && 9691 !LHSStripped->isNullPointerConstant(S.Context, 9692 Expr::NPC_ValueDependentIsNull)) { 9693 LiteralString = RHS; 9694 LiteralStringStripped = RHSStripped; 9695 } 9696 9697 if (LiteralString) { 9698 S.DiagRuntimeBehavior(Loc, nullptr, 9699 S.PDiag(diag::warn_stringcompare) 9700 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9701 << LiteralString->getSourceRange()); 9702 } 9703 } 9704 9705 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 9706 ExprResult &RHS, 9707 SourceLocation Loc, 9708 BinaryOperatorKind Opc) { 9709 // C99 6.5.8p3 / C99 6.5.9p4 9710 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9711 if (LHS.isInvalid() || RHS.isInvalid()) 9712 return QualType(); 9713 if (Type.isNull()) 9714 return S.InvalidOperands(Loc, LHS, RHS); 9715 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9716 9717 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 9718 9719 enum { StrongEquality, PartialOrdering, StrongOrdering } Ordering; 9720 if (Type->isAnyComplexType()) 9721 Ordering = StrongEquality; 9722 else if (Type->isFloatingType()) 9723 Ordering = PartialOrdering; 9724 else 9725 Ordering = StrongOrdering; 9726 9727 if (Ordering == StrongEquality && BinaryOperator::isRelationalOp(Opc)) 9728 return S.InvalidOperands(Loc, LHS, RHS); 9729 9730 // Check for comparisons of floating point operands using != and ==. 9731 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 9732 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9733 9734 // The result of comparisons is 'bool' in C++, 'int' in C. 9735 // FIXME: For BO_Cmp, return the relevant comparison category type. 9736 return S.Context.getLogicalOperationType(); 9737 } 9738 9739 // C99 6.5.8, C++ [expr.rel] 9740 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9741 SourceLocation Loc, BinaryOperatorKind Opc, 9742 bool IsRelational) { 9743 // Comparisons expect an rvalue, so convert to rvalue before any 9744 // type-related checks. 9745 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9746 if (LHS.isInvalid()) 9747 return QualType(); 9748 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9749 if (RHS.isInvalid()) 9750 return QualType(); 9751 9752 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9753 9754 // Handle vector comparisons separately. 9755 if (LHS.get()->getType()->isVectorType() || 9756 RHS.get()->getType()->isVectorType()) 9757 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 9758 9759 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9760 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 9761 9762 QualType LHSType = LHS.get()->getType(); 9763 QualType RHSType = RHS.get()->getType(); 9764 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 9765 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 9766 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 9767 9768 QualType ResultTy = Context.getLogicalOperationType(); 9769 9770 const Expr::NullPointerConstantKind LHSNullKind = 9771 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9772 const Expr::NullPointerConstantKind RHSNullKind = 9773 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9774 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9775 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9776 9777 if (!IsRelational && LHSIsNull != RHSIsNull) { 9778 bool IsEquality = Opc == BO_EQ; 9779 if (RHSIsNull) 9780 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9781 RHS.get()->getSourceRange()); 9782 else 9783 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9784 LHS.get()->getSourceRange()); 9785 } 9786 9787 if ((LHSType->isIntegerType() && !LHSIsNull) || 9788 (RHSType->isIntegerType() && !RHSIsNull)) { 9789 // Skip normal pointer conversion checks in this case; we have better 9790 // diagnostics for this below. 9791 } else if (getLangOpts().CPlusPlus) { 9792 // Equality comparison of a function pointer to a void pointer is invalid, 9793 // but we allow it as an extension. 9794 // FIXME: If we really want to allow this, should it be part of composite 9795 // pointer type computation so it works in conditionals too? 9796 if (!IsRelational && 9797 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9798 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9799 // This is a gcc extension compatibility comparison. 9800 // In a SFINAE context, we treat this as a hard error to maintain 9801 // conformance with the C++ standard. 9802 diagnoseFunctionPointerToVoidComparison( 9803 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9804 9805 if (isSFINAEContext()) 9806 return QualType(); 9807 9808 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9809 return ResultTy; 9810 } 9811 9812 // C++ [expr.eq]p2: 9813 // If at least one operand is a pointer [...] bring them to their 9814 // composite pointer type. 9815 // C++ [expr.rel]p2: 9816 // If both operands are pointers, [...] bring them to their composite 9817 // pointer type. 9818 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9819 (IsRelational ? 2 : 1) && 9820 (!LangOpts.ObjCAutoRefCount || 9821 !(LHSType->isObjCObjectPointerType() || 9822 RHSType->isObjCObjectPointerType()))) { 9823 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9824 return QualType(); 9825 else 9826 return ResultTy; 9827 } 9828 } else if (LHSType->isPointerType() && 9829 RHSType->isPointerType()) { // C99 6.5.8p2 9830 // All of the following pointer-related warnings are GCC extensions, except 9831 // when handling null pointer constants. 9832 QualType LCanPointeeTy = 9833 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9834 QualType RCanPointeeTy = 9835 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9836 9837 // C99 6.5.9p2 and C99 6.5.8p2 9838 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9839 RCanPointeeTy.getUnqualifiedType())) { 9840 // Valid unless a relational comparison of function pointers 9841 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9842 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9843 << LHSType << RHSType << LHS.get()->getSourceRange() 9844 << RHS.get()->getSourceRange(); 9845 } 9846 } else if (!IsRelational && 9847 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9848 // Valid unless comparison between non-null pointer and function pointer 9849 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9850 && !LHSIsNull && !RHSIsNull) 9851 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9852 /*isError*/false); 9853 } else { 9854 // Invalid 9855 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9856 } 9857 if (LCanPointeeTy != RCanPointeeTy) { 9858 // Treat NULL constant as a special case in OpenCL. 9859 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9860 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9861 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9862 Diag(Loc, 9863 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9864 << LHSType << RHSType << 0 /* comparison */ 9865 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9866 } 9867 } 9868 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9869 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9870 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9871 : CK_BitCast; 9872 if (LHSIsNull && !RHSIsNull) 9873 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9874 else 9875 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9876 } 9877 return ResultTy; 9878 } 9879 9880 if (getLangOpts().CPlusPlus) { 9881 // C++ [expr.eq]p4: 9882 // Two operands of type std::nullptr_t or one operand of type 9883 // std::nullptr_t and the other a null pointer constant compare equal. 9884 if (!IsRelational && LHSIsNull && RHSIsNull) { 9885 if (LHSType->isNullPtrType()) { 9886 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9887 return ResultTy; 9888 } 9889 if (RHSType->isNullPtrType()) { 9890 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9891 return ResultTy; 9892 } 9893 } 9894 9895 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9896 // These aren't covered by the composite pointer type rules. 9897 if (!IsRelational && RHSType->isNullPtrType() && 9898 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9899 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9900 return ResultTy; 9901 } 9902 if (!IsRelational && LHSType->isNullPtrType() && 9903 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9904 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9905 return ResultTy; 9906 } 9907 9908 if (IsRelational && 9909 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9910 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9911 // HACK: Relational comparison of nullptr_t against a pointer type is 9912 // invalid per DR583, but we allow it within std::less<> and friends, 9913 // since otherwise common uses of it break. 9914 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9915 // friends to have std::nullptr_t overload candidates. 9916 DeclContext *DC = CurContext; 9917 if (isa<FunctionDecl>(DC)) 9918 DC = DC->getParent(); 9919 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9920 if (CTSD->isInStdNamespace() && 9921 llvm::StringSwitch<bool>(CTSD->getName()) 9922 .Cases("less", "less_equal", "greater", "greater_equal", true) 9923 .Default(false)) { 9924 if (RHSType->isNullPtrType()) 9925 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9926 else 9927 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9928 return ResultTy; 9929 } 9930 } 9931 } 9932 9933 // C++ [expr.eq]p2: 9934 // If at least one operand is a pointer to member, [...] bring them to 9935 // their composite pointer type. 9936 if (!IsRelational && 9937 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9938 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9939 return QualType(); 9940 else 9941 return ResultTy; 9942 } 9943 } 9944 9945 // Handle block pointer types. 9946 if (!IsRelational && LHSType->isBlockPointerType() && 9947 RHSType->isBlockPointerType()) { 9948 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9949 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9950 9951 if (!LHSIsNull && !RHSIsNull && 9952 !Context.typesAreCompatible(lpointee, rpointee)) { 9953 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9954 << LHSType << RHSType << LHS.get()->getSourceRange() 9955 << RHS.get()->getSourceRange(); 9956 } 9957 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9958 return ResultTy; 9959 } 9960 9961 // Allow block pointers to be compared with null pointer constants. 9962 if (!IsRelational 9963 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9964 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9965 if (!LHSIsNull && !RHSIsNull) { 9966 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9967 ->getPointeeType()->isVoidType()) 9968 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9969 ->getPointeeType()->isVoidType()))) 9970 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9971 << LHSType << RHSType << LHS.get()->getSourceRange() 9972 << RHS.get()->getSourceRange(); 9973 } 9974 if (LHSIsNull && !RHSIsNull) 9975 LHS = ImpCastExprToType(LHS.get(), RHSType, 9976 RHSType->isPointerType() ? CK_BitCast 9977 : CK_AnyPointerToBlockPointerCast); 9978 else 9979 RHS = ImpCastExprToType(RHS.get(), LHSType, 9980 LHSType->isPointerType() ? CK_BitCast 9981 : CK_AnyPointerToBlockPointerCast); 9982 return ResultTy; 9983 } 9984 9985 if (LHSType->isObjCObjectPointerType() || 9986 RHSType->isObjCObjectPointerType()) { 9987 const PointerType *LPT = LHSType->getAs<PointerType>(); 9988 const PointerType *RPT = RHSType->getAs<PointerType>(); 9989 if (LPT || RPT) { 9990 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9991 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9992 9993 if (!LPtrToVoid && !RPtrToVoid && 9994 !Context.typesAreCompatible(LHSType, RHSType)) { 9995 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9996 /*isError*/false); 9997 } 9998 if (LHSIsNull && !RHSIsNull) { 9999 Expr *E = LHS.get(); 10000 if (getLangOpts().ObjCAutoRefCount) 10001 CheckObjCConversion(SourceRange(), RHSType, E, 10002 CCK_ImplicitConversion); 10003 LHS = ImpCastExprToType(E, RHSType, 10004 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10005 } 10006 else { 10007 Expr *E = RHS.get(); 10008 if (getLangOpts().ObjCAutoRefCount) 10009 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10010 /*Diagnose=*/true, 10011 /*DiagnoseCFAudited=*/false, Opc); 10012 RHS = ImpCastExprToType(E, LHSType, 10013 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10014 } 10015 return ResultTy; 10016 } 10017 if (LHSType->isObjCObjectPointerType() && 10018 RHSType->isObjCObjectPointerType()) { 10019 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10020 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10021 /*isError*/false); 10022 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10023 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10024 10025 if (LHSIsNull && !RHSIsNull) 10026 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10027 else 10028 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10029 return ResultTy; 10030 } 10031 } 10032 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10033 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10034 unsigned DiagID = 0; 10035 bool isError = false; 10036 if (LangOpts.DebuggerSupport) { 10037 // Under a debugger, allow the comparison of pointers to integers, 10038 // since users tend to want to compare addresses. 10039 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10040 (RHSIsNull && RHSType->isIntegerType())) { 10041 if (IsRelational) { 10042 isError = getLangOpts().CPlusPlus; 10043 DiagID = 10044 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10045 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10046 } 10047 } else if (getLangOpts().CPlusPlus) { 10048 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10049 isError = true; 10050 } else if (IsRelational) 10051 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10052 else 10053 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10054 10055 if (DiagID) { 10056 Diag(Loc, DiagID) 10057 << LHSType << RHSType << LHS.get()->getSourceRange() 10058 << RHS.get()->getSourceRange(); 10059 if (isError) 10060 return QualType(); 10061 } 10062 10063 if (LHSType->isIntegerType()) 10064 LHS = ImpCastExprToType(LHS.get(), RHSType, 10065 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10066 else 10067 RHS = ImpCastExprToType(RHS.get(), LHSType, 10068 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10069 return ResultTy; 10070 } 10071 10072 // Handle block pointers. 10073 if (!IsRelational && RHSIsNull 10074 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10075 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10076 return ResultTy; 10077 } 10078 if (!IsRelational && LHSIsNull 10079 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10080 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10081 return ResultTy; 10082 } 10083 10084 if (getLangOpts().OpenCLVersion >= 200) { 10085 if (LHSIsNull && RHSType->isQueueT()) { 10086 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10087 return ResultTy; 10088 } 10089 10090 if (LHSType->isQueueT() && RHSIsNull) { 10091 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10092 return ResultTy; 10093 } 10094 } 10095 10096 return InvalidOperands(Loc, LHS, RHS); 10097 } 10098 10099 // Return a signed ext_vector_type that is of identical size and number of 10100 // elements. For floating point vectors, return an integer type of identical 10101 // size and number of elements. In the non ext_vector_type case, search from 10102 // the largest type to the smallest type to avoid cases where long long == long, 10103 // where long gets picked over long long. 10104 QualType Sema::GetSignedVectorType(QualType V) { 10105 const VectorType *VTy = V->getAs<VectorType>(); 10106 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10107 10108 if (isa<ExtVectorType>(VTy)) { 10109 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10110 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10111 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10112 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10113 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10114 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10115 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10116 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10117 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10118 "Unhandled vector element size in vector compare"); 10119 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10120 } 10121 10122 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10123 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10124 VectorType::GenericVector); 10125 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10126 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10127 VectorType::GenericVector); 10128 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10129 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10130 VectorType::GenericVector); 10131 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10132 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10133 VectorType::GenericVector); 10134 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10135 "Unhandled vector element size in vector compare"); 10136 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10137 VectorType::GenericVector); 10138 } 10139 10140 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10141 /// operates on extended vector types. Instead of producing an IntTy result, 10142 /// like a scalar comparison, a vector comparison produces a vector of integer 10143 /// types. 10144 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10145 SourceLocation Loc, 10146 BinaryOperatorKind Opc) { 10147 // Check to make sure we're operating on vectors of the same type and width, 10148 // Allowing one side to be a scalar of element type. 10149 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10150 /*AllowBothBool*/true, 10151 /*AllowBoolConversions*/getLangOpts().ZVector); 10152 if (vType.isNull()) 10153 return vType; 10154 10155 QualType LHSType = LHS.get()->getType(); 10156 10157 // If AltiVec, the comparison results in a numeric type, i.e. 10158 // bool for C++, int for C 10159 if (getLangOpts().AltiVec && 10160 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10161 return Context.getLogicalOperationType(); 10162 10163 // For non-floating point types, check for self-comparisons of the form 10164 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10165 // often indicate logic errors in the program. 10166 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10167 10168 // Check for comparisons of floating point operands using != and ==. 10169 if (BinaryOperator::isEqualityOp(Opc) && 10170 LHSType->hasFloatingRepresentation()) { 10171 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10172 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10173 } 10174 10175 // Return a signed type for the vector. 10176 return GetSignedVectorType(vType); 10177 } 10178 10179 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10180 SourceLocation Loc) { 10181 // Ensure that either both operands are of the same vector type, or 10182 // one operand is of a vector type and the other is of its element type. 10183 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10184 /*AllowBothBool*/true, 10185 /*AllowBoolConversions*/false); 10186 if (vType.isNull()) 10187 return InvalidOperands(Loc, LHS, RHS); 10188 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10189 vType->hasFloatingRepresentation()) 10190 return InvalidOperands(Loc, LHS, RHS); 10191 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10192 // usage of the logical operators && and || with vectors in C. This 10193 // check could be notionally dropped. 10194 if (!getLangOpts().CPlusPlus && 10195 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10196 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10197 10198 return GetSignedVectorType(LHS.get()->getType()); 10199 } 10200 10201 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10202 SourceLocation Loc, 10203 BinaryOperatorKind Opc) { 10204 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10205 10206 bool IsCompAssign = 10207 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10208 10209 if (LHS.get()->getType()->isVectorType() || 10210 RHS.get()->getType()->isVectorType()) { 10211 if (LHS.get()->getType()->hasIntegerRepresentation() && 10212 RHS.get()->getType()->hasIntegerRepresentation()) 10213 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10214 /*AllowBothBool*/true, 10215 /*AllowBoolConversions*/getLangOpts().ZVector); 10216 return InvalidOperands(Loc, LHS, RHS); 10217 } 10218 10219 if (Opc == BO_And) 10220 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10221 10222 ExprResult LHSResult = LHS, RHSResult = RHS; 10223 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10224 IsCompAssign); 10225 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10226 return QualType(); 10227 LHS = LHSResult.get(); 10228 RHS = RHSResult.get(); 10229 10230 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10231 return compType; 10232 return InvalidOperands(Loc, LHS, RHS); 10233 } 10234 10235 // C99 6.5.[13,14] 10236 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10237 SourceLocation Loc, 10238 BinaryOperatorKind Opc) { 10239 // Check vector operands differently. 10240 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10241 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10242 10243 // Diagnose cases where the user write a logical and/or but probably meant a 10244 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10245 // is a constant. 10246 if (LHS.get()->getType()->isIntegerType() && 10247 !LHS.get()->getType()->isBooleanType() && 10248 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10249 // Don't warn in macros or template instantiations. 10250 !Loc.isMacroID() && !inTemplateInstantiation()) { 10251 // If the RHS can be constant folded, and if it constant folds to something 10252 // that isn't 0 or 1 (which indicate a potential logical operation that 10253 // happened to fold to true/false) then warn. 10254 // Parens on the RHS are ignored. 10255 llvm::APSInt Result; 10256 if (RHS.get()->EvaluateAsInt(Result, Context)) 10257 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10258 !RHS.get()->getExprLoc().isMacroID()) || 10259 (Result != 0 && Result != 1)) { 10260 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10261 << RHS.get()->getSourceRange() 10262 << (Opc == BO_LAnd ? "&&" : "||"); 10263 // Suggest replacing the logical operator with the bitwise version 10264 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10265 << (Opc == BO_LAnd ? "&" : "|") 10266 << FixItHint::CreateReplacement(SourceRange( 10267 Loc, getLocForEndOfToken(Loc)), 10268 Opc == BO_LAnd ? "&" : "|"); 10269 if (Opc == BO_LAnd) 10270 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10271 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10272 << FixItHint::CreateRemoval( 10273 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10274 RHS.get()->getLocEnd())); 10275 } 10276 } 10277 10278 if (!Context.getLangOpts().CPlusPlus) { 10279 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10280 // not operate on the built-in scalar and vector float types. 10281 if (Context.getLangOpts().OpenCL && 10282 Context.getLangOpts().OpenCLVersion < 120) { 10283 if (LHS.get()->getType()->isFloatingType() || 10284 RHS.get()->getType()->isFloatingType()) 10285 return InvalidOperands(Loc, LHS, RHS); 10286 } 10287 10288 LHS = UsualUnaryConversions(LHS.get()); 10289 if (LHS.isInvalid()) 10290 return QualType(); 10291 10292 RHS = UsualUnaryConversions(RHS.get()); 10293 if (RHS.isInvalid()) 10294 return QualType(); 10295 10296 if (!LHS.get()->getType()->isScalarType() || 10297 !RHS.get()->getType()->isScalarType()) 10298 return InvalidOperands(Loc, LHS, RHS); 10299 10300 return Context.IntTy; 10301 } 10302 10303 // The following is safe because we only use this method for 10304 // non-overloadable operands. 10305 10306 // C++ [expr.log.and]p1 10307 // C++ [expr.log.or]p1 10308 // The operands are both contextually converted to type bool. 10309 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10310 if (LHSRes.isInvalid()) 10311 return InvalidOperands(Loc, LHS, RHS); 10312 LHS = LHSRes; 10313 10314 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10315 if (RHSRes.isInvalid()) 10316 return InvalidOperands(Loc, LHS, RHS); 10317 RHS = RHSRes; 10318 10319 // C++ [expr.log.and]p2 10320 // C++ [expr.log.or]p2 10321 // The result is a bool. 10322 return Context.BoolTy; 10323 } 10324 10325 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10326 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10327 if (!ME) return false; 10328 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10329 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10330 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10331 if (!Base) return false; 10332 return Base->getMethodDecl() != nullptr; 10333 } 10334 10335 /// Is the given expression (which must be 'const') a reference to a 10336 /// variable which was originally non-const, but which has become 10337 /// 'const' due to being captured within a block? 10338 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10339 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10340 assert(E->isLValue() && E->getType().isConstQualified()); 10341 E = E->IgnoreParens(); 10342 10343 // Must be a reference to a declaration from an enclosing scope. 10344 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10345 if (!DRE) return NCCK_None; 10346 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10347 10348 // The declaration must be a variable which is not declared 'const'. 10349 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10350 if (!var) return NCCK_None; 10351 if (var->getType().isConstQualified()) return NCCK_None; 10352 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10353 10354 // Decide whether the first capture was for a block or a lambda. 10355 DeclContext *DC = S.CurContext, *Prev = nullptr; 10356 // Decide whether the first capture was for a block or a lambda. 10357 while (DC) { 10358 // For init-capture, it is possible that the variable belongs to the 10359 // template pattern of the current context. 10360 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10361 if (var->isInitCapture() && 10362 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10363 break; 10364 if (DC == var->getDeclContext()) 10365 break; 10366 Prev = DC; 10367 DC = DC->getParent(); 10368 } 10369 // Unless we have an init-capture, we've gone one step too far. 10370 if (!var->isInitCapture()) 10371 DC = Prev; 10372 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10373 } 10374 10375 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10376 Ty = Ty.getNonReferenceType(); 10377 if (IsDereference && Ty->isPointerType()) 10378 Ty = Ty->getPointeeType(); 10379 return !Ty.isConstQualified(); 10380 } 10381 10382 // Update err_typecheck_assign_const and note_typecheck_assign_const 10383 // when this enum is changed. 10384 enum { 10385 ConstFunction, 10386 ConstVariable, 10387 ConstMember, 10388 ConstMethod, 10389 NestedConstMember, 10390 ConstUnknown, // Keep as last element 10391 }; 10392 10393 /// Emit the "read-only variable not assignable" error and print notes to give 10394 /// more information about why the variable is not assignable, such as pointing 10395 /// to the declaration of a const variable, showing that a method is const, or 10396 /// that the function is returning a const reference. 10397 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10398 SourceLocation Loc) { 10399 SourceRange ExprRange = E->getSourceRange(); 10400 10401 // Only emit one error on the first const found. All other consts will emit 10402 // a note to the error. 10403 bool DiagnosticEmitted = false; 10404 10405 // Track if the current expression is the result of a dereference, and if the 10406 // next checked expression is the result of a dereference. 10407 bool IsDereference = false; 10408 bool NextIsDereference = false; 10409 10410 // Loop to process MemberExpr chains. 10411 while (true) { 10412 IsDereference = NextIsDereference; 10413 10414 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10415 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10416 NextIsDereference = ME->isArrow(); 10417 const ValueDecl *VD = ME->getMemberDecl(); 10418 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10419 // Mutable fields can be modified even if the class is const. 10420 if (Field->isMutable()) { 10421 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10422 break; 10423 } 10424 10425 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10426 if (!DiagnosticEmitted) { 10427 S.Diag(Loc, diag::err_typecheck_assign_const) 10428 << ExprRange << ConstMember << false /*static*/ << Field 10429 << Field->getType(); 10430 DiagnosticEmitted = true; 10431 } 10432 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10433 << ConstMember << false /*static*/ << Field << Field->getType() 10434 << Field->getSourceRange(); 10435 } 10436 E = ME->getBase(); 10437 continue; 10438 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10439 if (VDecl->getType().isConstQualified()) { 10440 if (!DiagnosticEmitted) { 10441 S.Diag(Loc, diag::err_typecheck_assign_const) 10442 << ExprRange << ConstMember << true /*static*/ << VDecl 10443 << VDecl->getType(); 10444 DiagnosticEmitted = true; 10445 } 10446 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10447 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10448 << VDecl->getSourceRange(); 10449 } 10450 // Static fields do not inherit constness from parents. 10451 break; 10452 } 10453 break; // End MemberExpr 10454 } else if (const ArraySubscriptExpr *ASE = 10455 dyn_cast<ArraySubscriptExpr>(E)) { 10456 E = ASE->getBase()->IgnoreParenImpCasts(); 10457 continue; 10458 } else if (const ExtVectorElementExpr *EVE = 10459 dyn_cast<ExtVectorElementExpr>(E)) { 10460 E = EVE->getBase()->IgnoreParenImpCasts(); 10461 continue; 10462 } 10463 break; 10464 } 10465 10466 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10467 // Function calls 10468 const FunctionDecl *FD = CE->getDirectCallee(); 10469 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10470 if (!DiagnosticEmitted) { 10471 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10472 << ConstFunction << FD; 10473 DiagnosticEmitted = true; 10474 } 10475 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10476 diag::note_typecheck_assign_const) 10477 << ConstFunction << FD << FD->getReturnType() 10478 << FD->getReturnTypeSourceRange(); 10479 } 10480 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10481 // Point to variable declaration. 10482 if (const ValueDecl *VD = DRE->getDecl()) { 10483 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10484 if (!DiagnosticEmitted) { 10485 S.Diag(Loc, diag::err_typecheck_assign_const) 10486 << ExprRange << ConstVariable << VD << VD->getType(); 10487 DiagnosticEmitted = true; 10488 } 10489 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10490 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10491 } 10492 } 10493 } else if (isa<CXXThisExpr>(E)) { 10494 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10495 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10496 if (MD->isConst()) { 10497 if (!DiagnosticEmitted) { 10498 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10499 << ConstMethod << MD; 10500 DiagnosticEmitted = true; 10501 } 10502 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10503 << ConstMethod << MD << MD->getSourceRange(); 10504 } 10505 } 10506 } 10507 } 10508 10509 if (DiagnosticEmitted) 10510 return; 10511 10512 // Can't determine a more specific message, so display the generic error. 10513 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10514 } 10515 10516 enum OriginalExprKind { 10517 OEK_Variable, 10518 OEK_Member, 10519 OEK_LValue 10520 }; 10521 10522 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10523 const RecordType *Ty, 10524 SourceLocation Loc, SourceRange Range, 10525 OriginalExprKind OEK, 10526 bool &DiagnosticEmitted, 10527 bool IsNested = false) { 10528 // We walk the record hierarchy breadth-first to ensure that we print 10529 // diagnostics in field nesting order. 10530 // First, check every field for constness. 10531 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10532 if (Field->getType().isConstQualified()) { 10533 if (!DiagnosticEmitted) { 10534 S.Diag(Loc, diag::err_typecheck_assign_const) 10535 << Range << NestedConstMember << OEK << VD 10536 << IsNested << Field; 10537 DiagnosticEmitted = true; 10538 } 10539 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10540 << NestedConstMember << IsNested << Field 10541 << Field->getType() << Field->getSourceRange(); 10542 } 10543 } 10544 // Then, recurse. 10545 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10546 QualType FTy = Field->getType(); 10547 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10548 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10549 OEK, DiagnosticEmitted, true); 10550 } 10551 } 10552 10553 /// Emit an error for the case where a record we are trying to assign to has a 10554 /// const-qualified field somewhere in its hierarchy. 10555 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10556 SourceLocation Loc) { 10557 QualType Ty = E->getType(); 10558 assert(Ty->isRecordType() && "lvalue was not record?"); 10559 SourceRange Range = E->getSourceRange(); 10560 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10561 bool DiagEmitted = false; 10562 10563 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10564 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10565 Range, OEK_Member, DiagEmitted); 10566 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10567 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10568 Range, OEK_Variable, DiagEmitted); 10569 else 10570 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10571 Range, OEK_LValue, DiagEmitted); 10572 if (!DiagEmitted) 10573 DiagnoseConstAssignment(S, E, Loc); 10574 } 10575 10576 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10577 /// emit an error and return true. If so, return false. 10578 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10579 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10580 10581 S.CheckShadowingDeclModification(E, Loc); 10582 10583 SourceLocation OrigLoc = Loc; 10584 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10585 &Loc); 10586 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10587 IsLV = Expr::MLV_InvalidMessageExpression; 10588 if (IsLV == Expr::MLV_Valid) 10589 return false; 10590 10591 unsigned DiagID = 0; 10592 bool NeedType = false; 10593 switch (IsLV) { // C99 6.5.16p2 10594 case Expr::MLV_ConstQualified: 10595 // Use a specialized diagnostic when we're assigning to an object 10596 // from an enclosing function or block. 10597 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10598 if (NCCK == NCCK_Block) 10599 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10600 else 10601 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10602 break; 10603 } 10604 10605 // In ARC, use some specialized diagnostics for occasions where we 10606 // infer 'const'. These are always pseudo-strong variables. 10607 if (S.getLangOpts().ObjCAutoRefCount) { 10608 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10609 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10610 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10611 10612 // Use the normal diagnostic if it's pseudo-__strong but the 10613 // user actually wrote 'const'. 10614 if (var->isARCPseudoStrong() && 10615 (!var->getTypeSourceInfo() || 10616 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10617 // There are two pseudo-strong cases: 10618 // - self 10619 ObjCMethodDecl *method = S.getCurMethodDecl(); 10620 if (method && var == method->getSelfDecl()) 10621 DiagID = method->isClassMethod() 10622 ? diag::err_typecheck_arc_assign_self_class_method 10623 : diag::err_typecheck_arc_assign_self; 10624 10625 // - fast enumeration variables 10626 else 10627 DiagID = diag::err_typecheck_arr_assign_enumeration; 10628 10629 SourceRange Assign; 10630 if (Loc != OrigLoc) 10631 Assign = SourceRange(OrigLoc, OrigLoc); 10632 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10633 // We need to preserve the AST regardless, so migration tool 10634 // can do its job. 10635 return false; 10636 } 10637 } 10638 } 10639 10640 // If none of the special cases above are triggered, then this is a 10641 // simple const assignment. 10642 if (DiagID == 0) { 10643 DiagnoseConstAssignment(S, E, Loc); 10644 return true; 10645 } 10646 10647 break; 10648 case Expr::MLV_ConstAddrSpace: 10649 DiagnoseConstAssignment(S, E, Loc); 10650 return true; 10651 case Expr::MLV_ConstQualifiedField: 10652 DiagnoseRecursiveConstFields(S, E, Loc); 10653 return true; 10654 case Expr::MLV_ArrayType: 10655 case Expr::MLV_ArrayTemporary: 10656 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10657 NeedType = true; 10658 break; 10659 case Expr::MLV_NotObjectType: 10660 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10661 NeedType = true; 10662 break; 10663 case Expr::MLV_LValueCast: 10664 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10665 break; 10666 case Expr::MLV_Valid: 10667 llvm_unreachable("did not take early return for MLV_Valid"); 10668 case Expr::MLV_InvalidExpression: 10669 case Expr::MLV_MemberFunction: 10670 case Expr::MLV_ClassTemporary: 10671 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10672 break; 10673 case Expr::MLV_IncompleteType: 10674 case Expr::MLV_IncompleteVoidType: 10675 return S.RequireCompleteType(Loc, E->getType(), 10676 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10677 case Expr::MLV_DuplicateVectorComponents: 10678 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10679 break; 10680 case Expr::MLV_NoSetterProperty: 10681 llvm_unreachable("readonly properties should be processed differently"); 10682 case Expr::MLV_InvalidMessageExpression: 10683 DiagID = diag::err_readonly_message_assignment; 10684 break; 10685 case Expr::MLV_SubObjCPropertySetting: 10686 DiagID = diag::err_no_subobject_property_setting; 10687 break; 10688 } 10689 10690 SourceRange Assign; 10691 if (Loc != OrigLoc) 10692 Assign = SourceRange(OrigLoc, OrigLoc); 10693 if (NeedType) 10694 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10695 else 10696 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10697 return true; 10698 } 10699 10700 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10701 SourceLocation Loc, 10702 Sema &Sema) { 10703 // C / C++ fields 10704 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10705 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10706 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10707 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10708 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10709 } 10710 10711 // Objective-C instance variables 10712 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10713 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10714 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10715 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10716 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10717 if (RL && RR && RL->getDecl() == RR->getDecl()) 10718 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10719 } 10720 } 10721 10722 // C99 6.5.16.1 10723 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10724 SourceLocation Loc, 10725 QualType CompoundType) { 10726 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10727 10728 // Verify that LHS is a modifiable lvalue, and emit error if not. 10729 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10730 return QualType(); 10731 10732 QualType LHSType = LHSExpr->getType(); 10733 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10734 CompoundType; 10735 // OpenCL v1.2 s6.1.1.1 p2: 10736 // The half data type can only be used to declare a pointer to a buffer that 10737 // contains half values 10738 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10739 LHSType->isHalfType()) { 10740 Diag(Loc, diag::err_opencl_half_load_store) << 1 10741 << LHSType.getUnqualifiedType(); 10742 return QualType(); 10743 } 10744 10745 AssignConvertType ConvTy; 10746 if (CompoundType.isNull()) { 10747 Expr *RHSCheck = RHS.get(); 10748 10749 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10750 10751 QualType LHSTy(LHSType); 10752 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10753 if (RHS.isInvalid()) 10754 return QualType(); 10755 // Special case of NSObject attributes on c-style pointer types. 10756 if (ConvTy == IncompatiblePointer && 10757 ((Context.isObjCNSObjectType(LHSType) && 10758 RHSType->isObjCObjectPointerType()) || 10759 (Context.isObjCNSObjectType(RHSType) && 10760 LHSType->isObjCObjectPointerType()))) 10761 ConvTy = Compatible; 10762 10763 if (ConvTy == Compatible && 10764 LHSType->isObjCObjectType()) 10765 Diag(Loc, diag::err_objc_object_assignment) 10766 << LHSType; 10767 10768 // If the RHS is a unary plus or minus, check to see if they = and + are 10769 // right next to each other. If so, the user may have typo'd "x =+ 4" 10770 // instead of "x += 4". 10771 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10772 RHSCheck = ICE->getSubExpr(); 10773 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10774 if ((UO->getOpcode() == UO_Plus || 10775 UO->getOpcode() == UO_Minus) && 10776 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10777 // Only if the two operators are exactly adjacent. 10778 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10779 // And there is a space or other character before the subexpr of the 10780 // unary +/-. We don't want to warn on "x=-1". 10781 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10782 UO->getSubExpr()->getLocStart().isFileID()) { 10783 Diag(Loc, diag::warn_not_compound_assign) 10784 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10785 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10786 } 10787 } 10788 10789 if (ConvTy == Compatible) { 10790 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10791 // Warn about retain cycles where a block captures the LHS, but 10792 // not if the LHS is a simple variable into which the block is 10793 // being stored...unless that variable can be captured by reference! 10794 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10795 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10796 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10797 checkRetainCycles(LHSExpr, RHS.get()); 10798 } 10799 10800 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10801 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10802 // It is safe to assign a weak reference into a strong variable. 10803 // Although this code can still have problems: 10804 // id x = self.weakProp; 10805 // id y = self.weakProp; 10806 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10807 // paths through the function. This should be revisited if 10808 // -Wrepeated-use-of-weak is made flow-sensitive. 10809 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10810 // variable, which will be valid for the current autorelease scope. 10811 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10812 RHS.get()->getLocStart())) 10813 getCurFunction()->markSafeWeakUse(RHS.get()); 10814 10815 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10816 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10817 } 10818 } 10819 } else { 10820 // Compound assignment "x += y" 10821 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10822 } 10823 10824 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10825 RHS.get(), AA_Assigning)) 10826 return QualType(); 10827 10828 CheckForNullPointerDereference(*this, LHSExpr); 10829 10830 // C99 6.5.16p3: The type of an assignment expression is the type of the 10831 // left operand unless the left operand has qualified type, in which case 10832 // it is the unqualified version of the type of the left operand. 10833 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10834 // is converted to the type of the assignment expression (above). 10835 // C++ 5.17p1: the type of the assignment expression is that of its left 10836 // operand. 10837 return (getLangOpts().CPlusPlus 10838 ? LHSType : LHSType.getUnqualifiedType()); 10839 } 10840 10841 // Only ignore explicit casts to void. 10842 static bool IgnoreCommaOperand(const Expr *E) { 10843 E = E->IgnoreParens(); 10844 10845 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10846 if (CE->getCastKind() == CK_ToVoid) { 10847 return true; 10848 } 10849 } 10850 10851 return false; 10852 } 10853 10854 // Look for instances where it is likely the comma operator is confused with 10855 // another operator. There is a whitelist of acceptable expressions for the 10856 // left hand side of the comma operator, otherwise emit a warning. 10857 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10858 // No warnings in macros 10859 if (Loc.isMacroID()) 10860 return; 10861 10862 // Don't warn in template instantiations. 10863 if (inTemplateInstantiation()) 10864 return; 10865 10866 // Scope isn't fine-grained enough to whitelist the specific cases, so 10867 // instead, skip more than needed, then call back into here with the 10868 // CommaVisitor in SemaStmt.cpp. 10869 // The whitelisted locations are the initialization and increment portions 10870 // of a for loop. The additional checks are on the condition of 10871 // if statements, do/while loops, and for loops. 10872 const unsigned ForIncrementFlags = 10873 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10874 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10875 const unsigned ScopeFlags = getCurScope()->getFlags(); 10876 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10877 (ScopeFlags & ForInitFlags) == ForInitFlags) 10878 return; 10879 10880 // If there are multiple comma operators used together, get the RHS of the 10881 // of the comma operator as the LHS. 10882 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10883 if (BO->getOpcode() != BO_Comma) 10884 break; 10885 LHS = BO->getRHS(); 10886 } 10887 10888 // Only allow some expressions on LHS to not warn. 10889 if (IgnoreCommaOperand(LHS)) 10890 return; 10891 10892 Diag(Loc, diag::warn_comma_operator); 10893 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10894 << LHS->getSourceRange() 10895 << FixItHint::CreateInsertion(LHS->getLocStart(), 10896 LangOpts.CPlusPlus ? "static_cast<void>(" 10897 : "(void)(") 10898 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10899 ")"); 10900 } 10901 10902 // C99 6.5.17 10903 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10904 SourceLocation Loc) { 10905 LHS = S.CheckPlaceholderExpr(LHS.get()); 10906 RHS = S.CheckPlaceholderExpr(RHS.get()); 10907 if (LHS.isInvalid() || RHS.isInvalid()) 10908 return QualType(); 10909 10910 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10911 // operands, but not unary promotions. 10912 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10913 10914 // So we treat the LHS as a ignored value, and in C++ we allow the 10915 // containing site to determine what should be done with the RHS. 10916 LHS = S.IgnoredValueConversions(LHS.get()); 10917 if (LHS.isInvalid()) 10918 return QualType(); 10919 10920 S.DiagnoseUnusedExprResult(LHS.get()); 10921 10922 if (!S.getLangOpts().CPlusPlus) { 10923 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10924 if (RHS.isInvalid()) 10925 return QualType(); 10926 if (!RHS.get()->getType()->isVoidType()) 10927 S.RequireCompleteType(Loc, RHS.get()->getType(), 10928 diag::err_incomplete_type); 10929 } 10930 10931 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10932 S.DiagnoseCommaOperator(LHS.get(), Loc); 10933 10934 return RHS.get()->getType(); 10935 } 10936 10937 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10938 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10939 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10940 ExprValueKind &VK, 10941 ExprObjectKind &OK, 10942 SourceLocation OpLoc, 10943 bool IsInc, bool IsPrefix) { 10944 if (Op->isTypeDependent()) 10945 return S.Context.DependentTy; 10946 10947 QualType ResType = Op->getType(); 10948 // Atomic types can be used for increment / decrement where the non-atomic 10949 // versions can, so ignore the _Atomic() specifier for the purpose of 10950 // checking. 10951 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10952 ResType = ResAtomicType->getValueType(); 10953 10954 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10955 10956 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10957 // Decrement of bool is not allowed. 10958 if (!IsInc) { 10959 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10960 return QualType(); 10961 } 10962 // Increment of bool sets it to true, but is deprecated. 10963 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 10964 : diag::warn_increment_bool) 10965 << Op->getSourceRange(); 10966 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10967 // Error on enum increments and decrements in C++ mode 10968 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10969 return QualType(); 10970 } else if (ResType->isRealType()) { 10971 // OK! 10972 } else if (ResType->isPointerType()) { 10973 // C99 6.5.2.4p2, 6.5.6p2 10974 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10975 return QualType(); 10976 } else if (ResType->isObjCObjectPointerType()) { 10977 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10978 // Otherwise, we just need a complete type. 10979 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10980 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10981 return QualType(); 10982 } else if (ResType->isAnyComplexType()) { 10983 // C99 does not support ++/-- on complex types, we allow as an extension. 10984 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10985 << ResType << Op->getSourceRange(); 10986 } else if (ResType->isPlaceholderType()) { 10987 ExprResult PR = S.CheckPlaceholderExpr(Op); 10988 if (PR.isInvalid()) return QualType(); 10989 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10990 IsInc, IsPrefix); 10991 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10992 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10993 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10994 (ResType->getAs<VectorType>()->getVectorKind() != 10995 VectorType::AltiVecBool)) { 10996 // The z vector extensions allow ++ and -- for non-bool vectors. 10997 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10998 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10999 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11000 } else { 11001 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11002 << ResType << int(IsInc) << Op->getSourceRange(); 11003 return QualType(); 11004 } 11005 // At this point, we know we have a real, complex or pointer type. 11006 // Now make sure the operand is a modifiable lvalue. 11007 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11008 return QualType(); 11009 // In C++, a prefix increment is the same type as the operand. Otherwise 11010 // (in C or with postfix), the increment is the unqualified type of the 11011 // operand. 11012 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11013 VK = VK_LValue; 11014 OK = Op->getObjectKind(); 11015 return ResType; 11016 } else { 11017 VK = VK_RValue; 11018 return ResType.getUnqualifiedType(); 11019 } 11020 } 11021 11022 11023 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11024 /// This routine allows us to typecheck complex/recursive expressions 11025 /// where the declaration is needed for type checking. We only need to 11026 /// handle cases when the expression references a function designator 11027 /// or is an lvalue. Here are some examples: 11028 /// - &(x) => x 11029 /// - &*****f => f for f a function designator. 11030 /// - &s.xx => s 11031 /// - &s.zz[1].yy -> s, if zz is an array 11032 /// - *(x + 1) -> x, if x is an array 11033 /// - &"123"[2] -> 0 11034 /// - & __real__ x -> x 11035 static ValueDecl *getPrimaryDecl(Expr *E) { 11036 switch (E->getStmtClass()) { 11037 case Stmt::DeclRefExprClass: 11038 return cast<DeclRefExpr>(E)->getDecl(); 11039 case Stmt::MemberExprClass: 11040 // If this is an arrow operator, the address is an offset from 11041 // the base's value, so the object the base refers to is 11042 // irrelevant. 11043 if (cast<MemberExpr>(E)->isArrow()) 11044 return nullptr; 11045 // Otherwise, the expression refers to a part of the base 11046 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11047 case Stmt::ArraySubscriptExprClass: { 11048 // FIXME: This code shouldn't be necessary! We should catch the implicit 11049 // promotion of register arrays earlier. 11050 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11051 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11052 if (ICE->getSubExpr()->getType()->isArrayType()) 11053 return getPrimaryDecl(ICE->getSubExpr()); 11054 } 11055 return nullptr; 11056 } 11057 case Stmt::UnaryOperatorClass: { 11058 UnaryOperator *UO = cast<UnaryOperator>(E); 11059 11060 switch(UO->getOpcode()) { 11061 case UO_Real: 11062 case UO_Imag: 11063 case UO_Extension: 11064 return getPrimaryDecl(UO->getSubExpr()); 11065 default: 11066 return nullptr; 11067 } 11068 } 11069 case Stmt::ParenExprClass: 11070 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11071 case Stmt::ImplicitCastExprClass: 11072 // If the result of an implicit cast is an l-value, we care about 11073 // the sub-expression; otherwise, the result here doesn't matter. 11074 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11075 default: 11076 return nullptr; 11077 } 11078 } 11079 11080 namespace { 11081 enum { 11082 AO_Bit_Field = 0, 11083 AO_Vector_Element = 1, 11084 AO_Property_Expansion = 2, 11085 AO_Register_Variable = 3, 11086 AO_No_Error = 4 11087 }; 11088 } 11089 /// \brief Diagnose invalid operand for address of operations. 11090 /// 11091 /// \param Type The type of operand which cannot have its address taken. 11092 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11093 Expr *E, unsigned Type) { 11094 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11095 } 11096 11097 /// CheckAddressOfOperand - The operand of & must be either a function 11098 /// designator or an lvalue designating an object. If it is an lvalue, the 11099 /// object cannot be declared with storage class register or be a bit field. 11100 /// Note: The usual conversions are *not* applied to the operand of the & 11101 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11102 /// In C++, the operand might be an overloaded function name, in which case 11103 /// we allow the '&' but retain the overloaded-function type. 11104 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11105 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11106 if (PTy->getKind() == BuiltinType::Overload) { 11107 Expr *E = OrigOp.get()->IgnoreParens(); 11108 if (!isa<OverloadExpr>(E)) { 11109 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11110 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11111 << OrigOp.get()->getSourceRange(); 11112 return QualType(); 11113 } 11114 11115 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11116 if (isa<UnresolvedMemberExpr>(Ovl)) 11117 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11118 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11119 << OrigOp.get()->getSourceRange(); 11120 return QualType(); 11121 } 11122 11123 return Context.OverloadTy; 11124 } 11125 11126 if (PTy->getKind() == BuiltinType::UnknownAny) 11127 return Context.UnknownAnyTy; 11128 11129 if (PTy->getKind() == BuiltinType::BoundMember) { 11130 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11131 << OrigOp.get()->getSourceRange(); 11132 return QualType(); 11133 } 11134 11135 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11136 if (OrigOp.isInvalid()) return QualType(); 11137 } 11138 11139 if (OrigOp.get()->isTypeDependent()) 11140 return Context.DependentTy; 11141 11142 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11143 11144 // Make sure to ignore parentheses in subsequent checks 11145 Expr *op = OrigOp.get()->IgnoreParens(); 11146 11147 // In OpenCL captures for blocks called as lambda functions 11148 // are located in the private address space. Blocks used in 11149 // enqueue_kernel can be located in a different address space 11150 // depending on a vendor implementation. Thus preventing 11151 // taking an address of the capture to avoid invalid AS casts. 11152 if (LangOpts.OpenCL) { 11153 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11154 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11155 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11156 return QualType(); 11157 } 11158 } 11159 11160 if (getLangOpts().C99) { 11161 // Implement C99-only parts of addressof rules. 11162 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11163 if (uOp->getOpcode() == UO_Deref) 11164 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11165 // (assuming the deref expression is valid). 11166 return uOp->getSubExpr()->getType(); 11167 } 11168 // Technically, there should be a check for array subscript 11169 // expressions here, but the result of one is always an lvalue anyway. 11170 } 11171 ValueDecl *dcl = getPrimaryDecl(op); 11172 11173 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11174 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11175 op->getLocStart())) 11176 return QualType(); 11177 11178 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11179 unsigned AddressOfError = AO_No_Error; 11180 11181 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11182 bool sfinae = (bool)isSFINAEContext(); 11183 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11184 : diag::ext_typecheck_addrof_temporary) 11185 << op->getType() << op->getSourceRange(); 11186 if (sfinae) 11187 return QualType(); 11188 // Materialize the temporary as an lvalue so that we can take its address. 11189 OrigOp = op = 11190 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11191 } else if (isa<ObjCSelectorExpr>(op)) { 11192 return Context.getPointerType(op->getType()); 11193 } else if (lval == Expr::LV_MemberFunction) { 11194 // If it's an instance method, make a member pointer. 11195 // The expression must have exactly the form &A::foo. 11196 11197 // If the underlying expression isn't a decl ref, give up. 11198 if (!isa<DeclRefExpr>(op)) { 11199 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11200 << OrigOp.get()->getSourceRange(); 11201 return QualType(); 11202 } 11203 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11204 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11205 11206 // The id-expression was parenthesized. 11207 if (OrigOp.get() != DRE) { 11208 Diag(OpLoc, diag::err_parens_pointer_member_function) 11209 << OrigOp.get()->getSourceRange(); 11210 11211 // The method was named without a qualifier. 11212 } else if (!DRE->getQualifier()) { 11213 if (MD->getParent()->getName().empty()) 11214 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11215 << op->getSourceRange(); 11216 else { 11217 SmallString<32> Str; 11218 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11219 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11220 << op->getSourceRange() 11221 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11222 } 11223 } 11224 11225 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11226 if (isa<CXXDestructorDecl>(MD)) 11227 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11228 11229 QualType MPTy = Context.getMemberPointerType( 11230 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11231 // Under the MS ABI, lock down the inheritance model now. 11232 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11233 (void)isCompleteType(OpLoc, MPTy); 11234 return MPTy; 11235 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11236 // C99 6.5.3.2p1 11237 // The operand must be either an l-value or a function designator 11238 if (!op->getType()->isFunctionType()) { 11239 // Use a special diagnostic for loads from property references. 11240 if (isa<PseudoObjectExpr>(op)) { 11241 AddressOfError = AO_Property_Expansion; 11242 } else { 11243 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11244 << op->getType() << op->getSourceRange(); 11245 return QualType(); 11246 } 11247 } 11248 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11249 // The operand cannot be a bit-field 11250 AddressOfError = AO_Bit_Field; 11251 } else if (op->getObjectKind() == OK_VectorComponent) { 11252 // The operand cannot be an element of a vector 11253 AddressOfError = AO_Vector_Element; 11254 } else if (dcl) { // C99 6.5.3.2p1 11255 // We have an lvalue with a decl. Make sure the decl is not declared 11256 // with the register storage-class specifier. 11257 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11258 // in C++ it is not error to take address of a register 11259 // variable (c++03 7.1.1P3) 11260 if (vd->getStorageClass() == SC_Register && 11261 !getLangOpts().CPlusPlus) { 11262 AddressOfError = AO_Register_Variable; 11263 } 11264 } else if (isa<MSPropertyDecl>(dcl)) { 11265 AddressOfError = AO_Property_Expansion; 11266 } else if (isa<FunctionTemplateDecl>(dcl)) { 11267 return Context.OverloadTy; 11268 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11269 // Okay: we can take the address of a field. 11270 // Could be a pointer to member, though, if there is an explicit 11271 // scope qualifier for the class. 11272 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11273 DeclContext *Ctx = dcl->getDeclContext(); 11274 if (Ctx && Ctx->isRecord()) { 11275 if (dcl->getType()->isReferenceType()) { 11276 Diag(OpLoc, 11277 diag::err_cannot_form_pointer_to_member_of_reference_type) 11278 << dcl->getDeclName() << dcl->getType(); 11279 return QualType(); 11280 } 11281 11282 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11283 Ctx = Ctx->getParent(); 11284 11285 QualType MPTy = Context.getMemberPointerType( 11286 op->getType(), 11287 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11288 // Under the MS ABI, lock down the inheritance model now. 11289 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11290 (void)isCompleteType(OpLoc, MPTy); 11291 return MPTy; 11292 } 11293 } 11294 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11295 !isa<BindingDecl>(dcl)) 11296 llvm_unreachable("Unknown/unexpected decl type"); 11297 } 11298 11299 if (AddressOfError != AO_No_Error) { 11300 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11301 return QualType(); 11302 } 11303 11304 if (lval == Expr::LV_IncompleteVoidType) { 11305 // Taking the address of a void variable is technically illegal, but we 11306 // allow it in cases which are otherwise valid. 11307 // Example: "extern void x; void* y = &x;". 11308 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11309 } 11310 11311 // If the operand has type "type", the result has type "pointer to type". 11312 if (op->getType()->isObjCObjectType()) 11313 return Context.getObjCObjectPointerType(op->getType()); 11314 11315 CheckAddressOfPackedMember(op); 11316 11317 return Context.getPointerType(op->getType()); 11318 } 11319 11320 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11321 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11322 if (!DRE) 11323 return; 11324 const Decl *D = DRE->getDecl(); 11325 if (!D) 11326 return; 11327 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11328 if (!Param) 11329 return; 11330 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11331 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11332 return; 11333 if (FunctionScopeInfo *FD = S.getCurFunction()) 11334 if (!FD->ModifiedNonNullParams.count(Param)) 11335 FD->ModifiedNonNullParams.insert(Param); 11336 } 11337 11338 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11339 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11340 SourceLocation OpLoc) { 11341 if (Op->isTypeDependent()) 11342 return S.Context.DependentTy; 11343 11344 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11345 if (ConvResult.isInvalid()) 11346 return QualType(); 11347 Op = ConvResult.get(); 11348 QualType OpTy = Op->getType(); 11349 QualType Result; 11350 11351 if (isa<CXXReinterpretCastExpr>(Op)) { 11352 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11353 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11354 Op->getSourceRange()); 11355 } 11356 11357 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11358 { 11359 Result = PT->getPointeeType(); 11360 } 11361 else if (const ObjCObjectPointerType *OPT = 11362 OpTy->getAs<ObjCObjectPointerType>()) 11363 Result = OPT->getPointeeType(); 11364 else { 11365 ExprResult PR = S.CheckPlaceholderExpr(Op); 11366 if (PR.isInvalid()) return QualType(); 11367 if (PR.get() != Op) 11368 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11369 } 11370 11371 if (Result.isNull()) { 11372 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11373 << OpTy << Op->getSourceRange(); 11374 return QualType(); 11375 } 11376 11377 // Note that per both C89 and C99, indirection is always legal, even if Result 11378 // is an incomplete type or void. It would be possible to warn about 11379 // dereferencing a void pointer, but it's completely well-defined, and such a 11380 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11381 // for pointers to 'void' but is fine for any other pointer type: 11382 // 11383 // C++ [expr.unary.op]p1: 11384 // [...] the expression to which [the unary * operator] is applied shall 11385 // be a pointer to an object type, or a pointer to a function type 11386 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11387 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11388 << OpTy << Op->getSourceRange(); 11389 11390 // Dereferences are usually l-values... 11391 VK = VK_LValue; 11392 11393 // ...except that certain expressions are never l-values in C. 11394 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11395 VK = VK_RValue; 11396 11397 return Result; 11398 } 11399 11400 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11401 BinaryOperatorKind Opc; 11402 switch (Kind) { 11403 default: llvm_unreachable("Unknown binop!"); 11404 case tok::periodstar: Opc = BO_PtrMemD; break; 11405 case tok::arrowstar: Opc = BO_PtrMemI; break; 11406 case tok::star: Opc = BO_Mul; break; 11407 case tok::slash: Opc = BO_Div; break; 11408 case tok::percent: Opc = BO_Rem; break; 11409 case tok::plus: Opc = BO_Add; break; 11410 case tok::minus: Opc = BO_Sub; break; 11411 case tok::lessless: Opc = BO_Shl; break; 11412 case tok::greatergreater: Opc = BO_Shr; break; 11413 case tok::lessequal: Opc = BO_LE; break; 11414 case tok::less: Opc = BO_LT; break; 11415 case tok::greaterequal: Opc = BO_GE; break; 11416 case tok::greater: Opc = BO_GT; break; 11417 case tok::exclaimequal: Opc = BO_NE; break; 11418 case tok::equalequal: Opc = BO_EQ; break; 11419 case tok::spaceship: Opc = BO_Cmp; break; 11420 case tok::amp: Opc = BO_And; break; 11421 case tok::caret: Opc = BO_Xor; break; 11422 case tok::pipe: Opc = BO_Or; break; 11423 case tok::ampamp: Opc = BO_LAnd; break; 11424 case tok::pipepipe: Opc = BO_LOr; break; 11425 case tok::equal: Opc = BO_Assign; break; 11426 case tok::starequal: Opc = BO_MulAssign; break; 11427 case tok::slashequal: Opc = BO_DivAssign; break; 11428 case tok::percentequal: Opc = BO_RemAssign; break; 11429 case tok::plusequal: Opc = BO_AddAssign; break; 11430 case tok::minusequal: Opc = BO_SubAssign; break; 11431 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11432 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11433 case tok::ampequal: Opc = BO_AndAssign; break; 11434 case tok::caretequal: Opc = BO_XorAssign; break; 11435 case tok::pipeequal: Opc = BO_OrAssign; break; 11436 case tok::comma: Opc = BO_Comma; break; 11437 } 11438 return Opc; 11439 } 11440 11441 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11442 tok::TokenKind Kind) { 11443 UnaryOperatorKind Opc; 11444 switch (Kind) { 11445 default: llvm_unreachable("Unknown unary op!"); 11446 case tok::plusplus: Opc = UO_PreInc; break; 11447 case tok::minusminus: Opc = UO_PreDec; break; 11448 case tok::amp: Opc = UO_AddrOf; break; 11449 case tok::star: Opc = UO_Deref; break; 11450 case tok::plus: Opc = UO_Plus; break; 11451 case tok::minus: Opc = UO_Minus; break; 11452 case tok::tilde: Opc = UO_Not; break; 11453 case tok::exclaim: Opc = UO_LNot; break; 11454 case tok::kw___real: Opc = UO_Real; break; 11455 case tok::kw___imag: Opc = UO_Imag; break; 11456 case tok::kw___extension__: Opc = UO_Extension; break; 11457 } 11458 return Opc; 11459 } 11460 11461 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11462 /// This warning is only emitted for builtin assignment operations. It is also 11463 /// suppressed in the event of macro expansions. 11464 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11465 SourceLocation OpLoc) { 11466 if (S.inTemplateInstantiation()) 11467 return; 11468 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11469 return; 11470 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11471 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11472 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11473 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11474 if (!LHSDeclRef || !RHSDeclRef || 11475 LHSDeclRef->getLocation().isMacroID() || 11476 RHSDeclRef->getLocation().isMacroID()) 11477 return; 11478 const ValueDecl *LHSDecl = 11479 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11480 const ValueDecl *RHSDecl = 11481 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11482 if (LHSDecl != RHSDecl) 11483 return; 11484 if (LHSDecl->getType().isVolatileQualified()) 11485 return; 11486 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11487 if (RefTy->getPointeeType().isVolatileQualified()) 11488 return; 11489 11490 S.Diag(OpLoc, diag::warn_self_assignment) 11491 << LHSDeclRef->getType() 11492 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11493 } 11494 11495 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11496 /// is usually indicative of introspection within the Objective-C pointer. 11497 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11498 SourceLocation OpLoc) { 11499 if (!S.getLangOpts().ObjC1) 11500 return; 11501 11502 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11503 const Expr *LHS = L.get(); 11504 const Expr *RHS = R.get(); 11505 11506 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11507 ObjCPointerExpr = LHS; 11508 OtherExpr = RHS; 11509 } 11510 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11511 ObjCPointerExpr = RHS; 11512 OtherExpr = LHS; 11513 } 11514 11515 // This warning is deliberately made very specific to reduce false 11516 // positives with logic that uses '&' for hashing. This logic mainly 11517 // looks for code trying to introspect into tagged pointers, which 11518 // code should generally never do. 11519 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11520 unsigned Diag = diag::warn_objc_pointer_masking; 11521 // Determine if we are introspecting the result of performSelectorXXX. 11522 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11523 // Special case messages to -performSelector and friends, which 11524 // can return non-pointer values boxed in a pointer value. 11525 // Some clients may wish to silence warnings in this subcase. 11526 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11527 Selector S = ME->getSelector(); 11528 StringRef SelArg0 = S.getNameForSlot(0); 11529 if (SelArg0.startswith("performSelector")) 11530 Diag = diag::warn_objc_pointer_masking_performSelector; 11531 } 11532 11533 S.Diag(OpLoc, Diag) 11534 << ObjCPointerExpr->getSourceRange(); 11535 } 11536 } 11537 11538 static NamedDecl *getDeclFromExpr(Expr *E) { 11539 if (!E) 11540 return nullptr; 11541 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11542 return DRE->getDecl(); 11543 if (auto *ME = dyn_cast<MemberExpr>(E)) 11544 return ME->getMemberDecl(); 11545 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11546 return IRE->getDecl(); 11547 return nullptr; 11548 } 11549 11550 // This helper function promotes a binary operator's operands (which are of a 11551 // half vector type) to a vector of floats and then truncates the result to 11552 // a vector of either half or short. 11553 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11554 BinaryOperatorKind Opc, QualType ResultTy, 11555 ExprValueKind VK, ExprObjectKind OK, 11556 bool IsCompAssign, SourceLocation OpLoc, 11557 FPOptions FPFeatures) { 11558 auto &Context = S.getASTContext(); 11559 assert((isVector(ResultTy, Context.HalfTy) || 11560 isVector(ResultTy, Context.ShortTy)) && 11561 "Result must be a vector of half or short"); 11562 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11563 isVector(RHS.get()->getType(), Context.HalfTy) && 11564 "both operands expected to be a half vector"); 11565 11566 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11567 QualType BinOpResTy = RHS.get()->getType(); 11568 11569 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11570 // change BinOpResTy to a vector of ints. 11571 if (isVector(ResultTy, Context.ShortTy)) 11572 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11573 11574 if (IsCompAssign) 11575 return new (Context) CompoundAssignOperator( 11576 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11577 OpLoc, FPFeatures); 11578 11579 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11580 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11581 VK, OK, OpLoc, FPFeatures); 11582 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11583 } 11584 11585 static std::pair<ExprResult, ExprResult> 11586 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11587 Expr *RHSExpr) { 11588 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11589 if (!S.getLangOpts().CPlusPlus) { 11590 // C cannot handle TypoExpr nodes on either side of a binop because it 11591 // doesn't handle dependent types properly, so make sure any TypoExprs have 11592 // been dealt with before checking the operands. 11593 LHS = S.CorrectDelayedTyposInExpr(LHS); 11594 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11595 if (Opc != BO_Assign) 11596 return ExprResult(E); 11597 // Avoid correcting the RHS to the same Expr as the LHS. 11598 Decl *D = getDeclFromExpr(E); 11599 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11600 }); 11601 } 11602 return std::make_pair(LHS, RHS); 11603 } 11604 11605 /// Returns true if conversion between vectors of halfs and vectors of floats 11606 /// is needed. 11607 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11608 QualType SrcType) { 11609 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11610 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11611 isVector(SrcType, Ctx.HalfTy); 11612 } 11613 11614 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11615 /// operator @p Opc at location @c TokLoc. This routine only supports 11616 /// built-in operations; ActOnBinOp handles overloaded operators. 11617 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11618 BinaryOperatorKind Opc, 11619 Expr *LHSExpr, Expr *RHSExpr) { 11620 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11621 // The syntax only allows initializer lists on the RHS of assignment, 11622 // so we don't need to worry about accepting invalid code for 11623 // non-assignment operators. 11624 // C++11 5.17p9: 11625 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11626 // of x = {} is x = T(). 11627 InitializationKind Kind = InitializationKind::CreateDirectList( 11628 RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11629 InitializedEntity Entity = 11630 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11631 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11632 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11633 if (Init.isInvalid()) 11634 return Init; 11635 RHSExpr = Init.get(); 11636 } 11637 11638 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11639 QualType ResultTy; // Result type of the binary operator. 11640 // The following two variables are used for compound assignment operators 11641 QualType CompLHSTy; // Type of LHS after promotions for computation 11642 QualType CompResultTy; // Type of computation result 11643 ExprValueKind VK = VK_RValue; 11644 ExprObjectKind OK = OK_Ordinary; 11645 bool ConvertHalfVec = false; 11646 11647 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11648 if (!LHS.isUsable() || !RHS.isUsable()) 11649 return ExprError(); 11650 11651 if (getLangOpts().OpenCL) { 11652 QualType LHSTy = LHSExpr->getType(); 11653 QualType RHSTy = RHSExpr->getType(); 11654 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11655 // the ATOMIC_VAR_INIT macro. 11656 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11657 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11658 if (BO_Assign == Opc) 11659 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11660 else 11661 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11662 return ExprError(); 11663 } 11664 11665 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11666 // only with a builtin functions and therefore should be disallowed here. 11667 if (LHSTy->isImageType() || RHSTy->isImageType() || 11668 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11669 LHSTy->isPipeType() || RHSTy->isPipeType() || 11670 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11671 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11672 return ExprError(); 11673 } 11674 } 11675 11676 switch (Opc) { 11677 case BO_Assign: 11678 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11679 if (getLangOpts().CPlusPlus && 11680 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11681 VK = LHS.get()->getValueKind(); 11682 OK = LHS.get()->getObjectKind(); 11683 } 11684 if (!ResultTy.isNull()) { 11685 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11686 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11687 } 11688 RecordModifiableNonNullParam(*this, LHS.get()); 11689 break; 11690 case BO_PtrMemD: 11691 case BO_PtrMemI: 11692 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11693 Opc == BO_PtrMemI); 11694 break; 11695 case BO_Mul: 11696 case BO_Div: 11697 ConvertHalfVec = true; 11698 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11699 Opc == BO_Div); 11700 break; 11701 case BO_Rem: 11702 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11703 break; 11704 case BO_Add: 11705 ConvertHalfVec = true; 11706 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11707 break; 11708 case BO_Sub: 11709 ConvertHalfVec = true; 11710 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11711 break; 11712 case BO_Shl: 11713 case BO_Shr: 11714 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11715 break; 11716 case BO_LE: 11717 case BO_LT: 11718 case BO_GE: 11719 case BO_GT: 11720 ConvertHalfVec = true; 11721 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11722 break; 11723 case BO_EQ: 11724 case BO_NE: 11725 ConvertHalfVec = true; 11726 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11727 break; 11728 case BO_Cmp: 11729 // FIXME: Implement proper semantic checking of '<=>'. 11730 ConvertHalfVec = true; 11731 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11732 if (!ResultTy.isNull()) 11733 ResultTy = Context.VoidTy; 11734 break; 11735 case BO_And: 11736 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11737 LLVM_FALLTHROUGH; 11738 case BO_Xor: 11739 case BO_Or: 11740 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11741 break; 11742 case BO_LAnd: 11743 case BO_LOr: 11744 ConvertHalfVec = true; 11745 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11746 break; 11747 case BO_MulAssign: 11748 case BO_DivAssign: 11749 ConvertHalfVec = true; 11750 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11751 Opc == BO_DivAssign); 11752 CompLHSTy = CompResultTy; 11753 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11754 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11755 break; 11756 case BO_RemAssign: 11757 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11758 CompLHSTy = CompResultTy; 11759 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11760 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11761 break; 11762 case BO_AddAssign: 11763 ConvertHalfVec = true; 11764 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11765 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11766 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11767 break; 11768 case BO_SubAssign: 11769 ConvertHalfVec = true; 11770 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11771 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11772 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11773 break; 11774 case BO_ShlAssign: 11775 case BO_ShrAssign: 11776 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11777 CompLHSTy = CompResultTy; 11778 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11779 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11780 break; 11781 case BO_AndAssign: 11782 case BO_OrAssign: // fallthrough 11783 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11784 LLVM_FALLTHROUGH; 11785 case BO_XorAssign: 11786 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11787 CompLHSTy = CompResultTy; 11788 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11789 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11790 break; 11791 case BO_Comma: 11792 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11793 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11794 VK = RHS.get()->getValueKind(); 11795 OK = RHS.get()->getObjectKind(); 11796 } 11797 break; 11798 } 11799 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11800 return ExprError(); 11801 11802 // Some of the binary operations require promoting operands of half vector to 11803 // float vectors and truncating the result back to half vector. For now, we do 11804 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 11805 // arm64). 11806 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 11807 isVector(LHS.get()->getType(), Context.HalfTy) && 11808 "both sides are half vectors or neither sides are"); 11809 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 11810 LHS.get()->getType()); 11811 11812 // Check for array bounds violations for both sides of the BinaryOperator 11813 CheckArrayAccess(LHS.get()); 11814 CheckArrayAccess(RHS.get()); 11815 11816 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11817 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11818 &Context.Idents.get("object_setClass"), 11819 SourceLocation(), LookupOrdinaryName); 11820 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11821 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11822 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11823 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11824 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11825 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11826 } 11827 else 11828 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11829 } 11830 else if (const ObjCIvarRefExpr *OIRE = 11831 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11832 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11833 11834 // Opc is not a compound assignment if CompResultTy is null. 11835 if (CompResultTy.isNull()) { 11836 if (ConvertHalfVec) 11837 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 11838 OpLoc, FPFeatures); 11839 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11840 OK, OpLoc, FPFeatures); 11841 } 11842 11843 // Handle compound assignments. 11844 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11845 OK_ObjCProperty) { 11846 VK = VK_LValue; 11847 OK = LHS.get()->getObjectKind(); 11848 } 11849 11850 if (ConvertHalfVec) 11851 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 11852 OpLoc, FPFeatures); 11853 11854 return new (Context) CompoundAssignOperator( 11855 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11856 OpLoc, FPFeatures); 11857 } 11858 11859 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11860 /// operators are mixed in a way that suggests that the programmer forgot that 11861 /// comparison operators have higher precedence. The most typical example of 11862 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11863 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11864 SourceLocation OpLoc, Expr *LHSExpr, 11865 Expr *RHSExpr) { 11866 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11867 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11868 11869 // Check that one of the sides is a comparison operator and the other isn't. 11870 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11871 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11872 if (isLeftComp == isRightComp) 11873 return; 11874 11875 // Bitwise operations are sometimes used as eager logical ops. 11876 // Don't diagnose this. 11877 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11878 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11879 if (isLeftBitwise || isRightBitwise) 11880 return; 11881 11882 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11883 OpLoc) 11884 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11885 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11886 SourceRange ParensRange = isLeftComp ? 11887 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11888 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11889 11890 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11891 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11892 SuggestParentheses(Self, OpLoc, 11893 Self.PDiag(diag::note_precedence_silence) << OpStr, 11894 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11895 SuggestParentheses(Self, OpLoc, 11896 Self.PDiag(diag::note_precedence_bitwise_first) 11897 << BinaryOperator::getOpcodeStr(Opc), 11898 ParensRange); 11899 } 11900 11901 /// \brief It accepts a '&&' expr that is inside a '||' one. 11902 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11903 /// in parentheses. 11904 static void 11905 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11906 BinaryOperator *Bop) { 11907 assert(Bop->getOpcode() == BO_LAnd); 11908 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11909 << Bop->getSourceRange() << OpLoc; 11910 SuggestParentheses(Self, Bop->getOperatorLoc(), 11911 Self.PDiag(diag::note_precedence_silence) 11912 << Bop->getOpcodeStr(), 11913 Bop->getSourceRange()); 11914 } 11915 11916 /// \brief Returns true if the given expression can be evaluated as a constant 11917 /// 'true'. 11918 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11919 bool Res; 11920 return !E->isValueDependent() && 11921 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11922 } 11923 11924 /// \brief Returns true if the given expression can be evaluated as a constant 11925 /// 'false'. 11926 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11927 bool Res; 11928 return !E->isValueDependent() && 11929 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11930 } 11931 11932 /// \brief Look for '&&' in the left hand of a '||' expr. 11933 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11934 Expr *LHSExpr, Expr *RHSExpr) { 11935 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11936 if (Bop->getOpcode() == BO_LAnd) { 11937 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11938 if (EvaluatesAsFalse(S, RHSExpr)) 11939 return; 11940 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11941 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11942 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11943 } else if (Bop->getOpcode() == BO_LOr) { 11944 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11945 // If it's "a || b && 1 || c" we didn't warn earlier for 11946 // "a || b && 1", but warn now. 11947 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11948 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11949 } 11950 } 11951 } 11952 } 11953 11954 /// \brief Look for '&&' in the right hand of a '||' expr. 11955 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11956 Expr *LHSExpr, Expr *RHSExpr) { 11957 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11958 if (Bop->getOpcode() == BO_LAnd) { 11959 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11960 if (EvaluatesAsFalse(S, LHSExpr)) 11961 return; 11962 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11963 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11964 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11965 } 11966 } 11967 } 11968 11969 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11970 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11971 /// the '&' expression in parentheses. 11972 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11973 SourceLocation OpLoc, Expr *SubExpr) { 11974 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11975 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11976 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11977 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11978 << Bop->getSourceRange() << OpLoc; 11979 SuggestParentheses(S, Bop->getOperatorLoc(), 11980 S.PDiag(diag::note_precedence_silence) 11981 << Bop->getOpcodeStr(), 11982 Bop->getSourceRange()); 11983 } 11984 } 11985 } 11986 11987 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11988 Expr *SubExpr, StringRef Shift) { 11989 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11990 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11991 StringRef Op = Bop->getOpcodeStr(); 11992 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11993 << Bop->getSourceRange() << OpLoc << Shift << Op; 11994 SuggestParentheses(S, Bop->getOperatorLoc(), 11995 S.PDiag(diag::note_precedence_silence) << Op, 11996 Bop->getSourceRange()); 11997 } 11998 } 11999 } 12000 12001 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12002 Expr *LHSExpr, Expr *RHSExpr) { 12003 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12004 if (!OCE) 12005 return; 12006 12007 FunctionDecl *FD = OCE->getDirectCallee(); 12008 if (!FD || !FD->isOverloadedOperator()) 12009 return; 12010 12011 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12012 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12013 return; 12014 12015 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12016 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12017 << (Kind == OO_LessLess); 12018 SuggestParentheses(S, OCE->getOperatorLoc(), 12019 S.PDiag(diag::note_precedence_silence) 12020 << (Kind == OO_LessLess ? "<<" : ">>"), 12021 OCE->getSourceRange()); 12022 SuggestParentheses(S, OpLoc, 12023 S.PDiag(diag::note_evaluate_comparison_first), 12024 SourceRange(OCE->getArg(1)->getLocStart(), 12025 RHSExpr->getLocEnd())); 12026 } 12027 12028 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12029 /// precedence. 12030 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12031 SourceLocation OpLoc, Expr *LHSExpr, 12032 Expr *RHSExpr){ 12033 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12034 if (BinaryOperator::isBitwiseOp(Opc)) 12035 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12036 12037 // Diagnose "arg1 & arg2 | arg3" 12038 if ((Opc == BO_Or || Opc == BO_Xor) && 12039 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12040 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12041 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12042 } 12043 12044 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12045 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12046 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12047 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12048 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12049 } 12050 12051 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12052 || Opc == BO_Shr) { 12053 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12054 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12055 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12056 } 12057 12058 // Warn on overloaded shift operators and comparisons, such as: 12059 // cout << 5 == 4; 12060 if (BinaryOperator::isComparisonOp(Opc)) 12061 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12062 } 12063 12064 // Binary Operators. 'Tok' is the token for the operator. 12065 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12066 tok::TokenKind Kind, 12067 Expr *LHSExpr, Expr *RHSExpr) { 12068 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12069 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12070 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12071 12072 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12073 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12074 12075 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12076 } 12077 12078 /// Build an overloaded binary operator expression in the given scope. 12079 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12080 BinaryOperatorKind Opc, 12081 Expr *LHS, Expr *RHS) { 12082 // Find all of the overloaded operators visible from this 12083 // point. We perform both an operator-name lookup from the local 12084 // scope and an argument-dependent lookup based on the types of 12085 // the arguments. 12086 UnresolvedSet<16> Functions; 12087 OverloadedOperatorKind OverOp 12088 = BinaryOperator::getOverloadedOperator(Opc); 12089 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12090 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12091 RHS->getType(), Functions); 12092 12093 // Build the (potentially-overloaded, potentially-dependent) 12094 // binary operation. 12095 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12096 } 12097 12098 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12099 BinaryOperatorKind Opc, 12100 Expr *LHSExpr, Expr *RHSExpr) { 12101 ExprResult LHS, RHS; 12102 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12103 if (!LHS.isUsable() || !RHS.isUsable()) 12104 return ExprError(); 12105 LHSExpr = LHS.get(); 12106 RHSExpr = RHS.get(); 12107 12108 // We want to end up calling one of checkPseudoObjectAssignment 12109 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12110 // both expressions are overloadable or either is type-dependent), 12111 // or CreateBuiltinBinOp (in any other case). We also want to get 12112 // any placeholder types out of the way. 12113 12114 // Handle pseudo-objects in the LHS. 12115 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12116 // Assignments with a pseudo-object l-value need special analysis. 12117 if (pty->getKind() == BuiltinType::PseudoObject && 12118 BinaryOperator::isAssignmentOp(Opc)) 12119 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12120 12121 // Don't resolve overloads if the other type is overloadable. 12122 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12123 // We can't actually test that if we still have a placeholder, 12124 // though. Fortunately, none of the exceptions we see in that 12125 // code below are valid when the LHS is an overload set. Note 12126 // that an overload set can be dependently-typed, but it never 12127 // instantiates to having an overloadable type. 12128 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12129 if (resolvedRHS.isInvalid()) return ExprError(); 12130 RHSExpr = resolvedRHS.get(); 12131 12132 if (RHSExpr->isTypeDependent() || 12133 RHSExpr->getType()->isOverloadableType()) 12134 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12135 } 12136 12137 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12138 // template, diagnose the missing 'template' keyword instead of diagnosing 12139 // an invalid use of a bound member function. 12140 // 12141 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12142 // to C++1z [over.over]/1.4, but we already checked for that case above. 12143 if (Opc == BO_LT && inTemplateInstantiation() && 12144 (pty->getKind() == BuiltinType::BoundMember || 12145 pty->getKind() == BuiltinType::Overload)) { 12146 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12147 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12148 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12149 return isa<FunctionTemplateDecl>(ND); 12150 })) { 12151 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12152 : OE->getNameLoc(), 12153 diag::err_template_kw_missing) 12154 << OE->getName().getAsString() << ""; 12155 return ExprError(); 12156 } 12157 } 12158 12159 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12160 if (LHS.isInvalid()) return ExprError(); 12161 LHSExpr = LHS.get(); 12162 } 12163 12164 // Handle pseudo-objects in the RHS. 12165 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12166 // An overload in the RHS can potentially be resolved by the type 12167 // being assigned to. 12168 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12169 if (getLangOpts().CPlusPlus && 12170 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12171 LHSExpr->getType()->isOverloadableType())) 12172 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12173 12174 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12175 } 12176 12177 // Don't resolve overloads if the other type is overloadable. 12178 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12179 LHSExpr->getType()->isOverloadableType()) 12180 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12181 12182 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12183 if (!resolvedRHS.isUsable()) return ExprError(); 12184 RHSExpr = resolvedRHS.get(); 12185 } 12186 12187 if (getLangOpts().CPlusPlus) { 12188 // If either expression is type-dependent, always build an 12189 // overloaded op. 12190 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12191 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12192 12193 // Otherwise, build an overloaded op if either expression has an 12194 // overloadable type. 12195 if (LHSExpr->getType()->isOverloadableType() || 12196 RHSExpr->getType()->isOverloadableType()) 12197 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12198 } 12199 12200 // Build a built-in binary operation. 12201 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12202 } 12203 12204 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12205 if (T.isNull() || T->isDependentType()) 12206 return false; 12207 12208 if (!T->isPromotableIntegerType()) 12209 return true; 12210 12211 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12212 } 12213 12214 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12215 UnaryOperatorKind Opc, 12216 Expr *InputExpr) { 12217 ExprResult Input = InputExpr; 12218 ExprValueKind VK = VK_RValue; 12219 ExprObjectKind OK = OK_Ordinary; 12220 QualType resultType; 12221 bool CanOverflow = false; 12222 12223 bool ConvertHalfVec = false; 12224 if (getLangOpts().OpenCL) { 12225 QualType Ty = InputExpr->getType(); 12226 // The only legal unary operation for atomics is '&'. 12227 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12228 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12229 // only with a builtin functions and therefore should be disallowed here. 12230 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12231 || Ty->isBlockPointerType())) { 12232 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12233 << InputExpr->getType() 12234 << Input.get()->getSourceRange()); 12235 } 12236 } 12237 switch (Opc) { 12238 case UO_PreInc: 12239 case UO_PreDec: 12240 case UO_PostInc: 12241 case UO_PostDec: 12242 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12243 OpLoc, 12244 Opc == UO_PreInc || 12245 Opc == UO_PostInc, 12246 Opc == UO_PreInc || 12247 Opc == UO_PreDec); 12248 CanOverflow = isOverflowingIntegerType(Context, resultType); 12249 break; 12250 case UO_AddrOf: 12251 resultType = CheckAddressOfOperand(Input, OpLoc); 12252 RecordModifiableNonNullParam(*this, InputExpr); 12253 break; 12254 case UO_Deref: { 12255 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12256 if (Input.isInvalid()) return ExprError(); 12257 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12258 break; 12259 } 12260 case UO_Plus: 12261 case UO_Minus: 12262 CanOverflow = Opc == UO_Minus && 12263 isOverflowingIntegerType(Context, Input.get()->getType()); 12264 Input = UsualUnaryConversions(Input.get()); 12265 if (Input.isInvalid()) return ExprError(); 12266 // Unary plus and minus require promoting an operand of half vector to a 12267 // float vector and truncating the result back to a half vector. For now, we 12268 // do this only when HalfArgsAndReturns is set (that is, when the target is 12269 // arm or arm64). 12270 ConvertHalfVec = 12271 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12272 12273 // If the operand is a half vector, promote it to a float vector. 12274 if (ConvertHalfVec) 12275 Input = convertVector(Input.get(), Context.FloatTy, *this); 12276 resultType = Input.get()->getType(); 12277 if (resultType->isDependentType()) 12278 break; 12279 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12280 break; 12281 else if (resultType->isVectorType() && 12282 // The z vector extensions don't allow + or - with bool vectors. 12283 (!Context.getLangOpts().ZVector || 12284 resultType->getAs<VectorType>()->getVectorKind() != 12285 VectorType::AltiVecBool)) 12286 break; 12287 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12288 Opc == UO_Plus && 12289 resultType->isPointerType()) 12290 break; 12291 12292 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12293 << resultType << Input.get()->getSourceRange()); 12294 12295 case UO_Not: // bitwise complement 12296 Input = UsualUnaryConversions(Input.get()); 12297 if (Input.isInvalid()) 12298 return ExprError(); 12299 resultType = Input.get()->getType(); 12300 12301 if (resultType->isDependentType()) 12302 break; 12303 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12304 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12305 // C99 does not support '~' for complex conjugation. 12306 Diag(OpLoc, diag::ext_integer_complement_complex) 12307 << resultType << Input.get()->getSourceRange(); 12308 else if (resultType->hasIntegerRepresentation()) 12309 break; 12310 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12311 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12312 // on vector float types. 12313 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12314 if (!T->isIntegerType()) 12315 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12316 << resultType << Input.get()->getSourceRange()); 12317 } else { 12318 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12319 << resultType << Input.get()->getSourceRange()); 12320 } 12321 break; 12322 12323 case UO_LNot: // logical negation 12324 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12325 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12326 if (Input.isInvalid()) return ExprError(); 12327 resultType = Input.get()->getType(); 12328 12329 // Though we still have to promote half FP to float... 12330 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12331 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12332 resultType = Context.FloatTy; 12333 } 12334 12335 if (resultType->isDependentType()) 12336 break; 12337 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12338 // C99 6.5.3.3p1: ok, fallthrough; 12339 if (Context.getLangOpts().CPlusPlus) { 12340 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12341 // operand contextually converted to bool. 12342 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12343 ScalarTypeToBooleanCastKind(resultType)); 12344 } else if (Context.getLangOpts().OpenCL && 12345 Context.getLangOpts().OpenCLVersion < 120) { 12346 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12347 // operate on scalar float types. 12348 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12349 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12350 << resultType << Input.get()->getSourceRange()); 12351 } 12352 } else if (resultType->isExtVectorType()) { 12353 if (Context.getLangOpts().OpenCL && 12354 Context.getLangOpts().OpenCLVersion < 120) { 12355 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12356 // operate on vector float types. 12357 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12358 if (!T->isIntegerType()) 12359 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12360 << resultType << Input.get()->getSourceRange()); 12361 } 12362 // Vector logical not returns the signed variant of the operand type. 12363 resultType = GetSignedVectorType(resultType); 12364 break; 12365 } else { 12366 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12367 // type in C++. We should allow that here too. 12368 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12369 << resultType << Input.get()->getSourceRange()); 12370 } 12371 12372 // LNot always has type int. C99 6.5.3.3p5. 12373 // In C++, it's bool. C++ 5.3.1p8 12374 resultType = Context.getLogicalOperationType(); 12375 break; 12376 case UO_Real: 12377 case UO_Imag: 12378 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12379 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12380 // complex l-values to ordinary l-values and all other values to r-values. 12381 if (Input.isInvalid()) return ExprError(); 12382 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12383 if (Input.get()->getValueKind() != VK_RValue && 12384 Input.get()->getObjectKind() == OK_Ordinary) 12385 VK = Input.get()->getValueKind(); 12386 } else if (!getLangOpts().CPlusPlus) { 12387 // In C, a volatile scalar is read by __imag. In C++, it is not. 12388 Input = DefaultLvalueConversion(Input.get()); 12389 } 12390 break; 12391 case UO_Extension: 12392 resultType = Input.get()->getType(); 12393 VK = Input.get()->getValueKind(); 12394 OK = Input.get()->getObjectKind(); 12395 break; 12396 case UO_Coawait: 12397 // It's unnessesary to represent the pass-through operator co_await in the 12398 // AST; just return the input expression instead. 12399 assert(!Input.get()->getType()->isDependentType() && 12400 "the co_await expression must be non-dependant before " 12401 "building operator co_await"); 12402 return Input; 12403 } 12404 if (resultType.isNull() || Input.isInvalid()) 12405 return ExprError(); 12406 12407 // Check for array bounds violations in the operand of the UnaryOperator, 12408 // except for the '*' and '&' operators that have to be handled specially 12409 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12410 // that are explicitly defined as valid by the standard). 12411 if (Opc != UO_AddrOf && Opc != UO_Deref) 12412 CheckArrayAccess(Input.get()); 12413 12414 auto *UO = new (Context) 12415 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12416 // Convert the result back to a half vector. 12417 if (ConvertHalfVec) 12418 return convertVector(UO, Context.HalfTy, *this); 12419 return UO; 12420 } 12421 12422 /// \brief Determine whether the given expression is a qualified member 12423 /// access expression, of a form that could be turned into a pointer to member 12424 /// with the address-of operator. 12425 static bool isQualifiedMemberAccess(Expr *E) { 12426 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12427 if (!DRE->getQualifier()) 12428 return false; 12429 12430 ValueDecl *VD = DRE->getDecl(); 12431 if (!VD->isCXXClassMember()) 12432 return false; 12433 12434 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12435 return true; 12436 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12437 return Method->isInstance(); 12438 12439 return false; 12440 } 12441 12442 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12443 if (!ULE->getQualifier()) 12444 return false; 12445 12446 for (NamedDecl *D : ULE->decls()) { 12447 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12448 if (Method->isInstance()) 12449 return true; 12450 } else { 12451 // Overload set does not contain methods. 12452 break; 12453 } 12454 } 12455 12456 return false; 12457 } 12458 12459 return false; 12460 } 12461 12462 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12463 UnaryOperatorKind Opc, Expr *Input) { 12464 // First things first: handle placeholders so that the 12465 // overloaded-operator check considers the right type. 12466 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12467 // Increment and decrement of pseudo-object references. 12468 if (pty->getKind() == BuiltinType::PseudoObject && 12469 UnaryOperator::isIncrementDecrementOp(Opc)) 12470 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12471 12472 // extension is always a builtin operator. 12473 if (Opc == UO_Extension) 12474 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12475 12476 // & gets special logic for several kinds of placeholder. 12477 // The builtin code knows what to do. 12478 if (Opc == UO_AddrOf && 12479 (pty->getKind() == BuiltinType::Overload || 12480 pty->getKind() == BuiltinType::UnknownAny || 12481 pty->getKind() == BuiltinType::BoundMember)) 12482 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12483 12484 // Anything else needs to be handled now. 12485 ExprResult Result = CheckPlaceholderExpr(Input); 12486 if (Result.isInvalid()) return ExprError(); 12487 Input = Result.get(); 12488 } 12489 12490 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12491 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12492 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12493 // Find all of the overloaded operators visible from this 12494 // point. We perform both an operator-name lookup from the local 12495 // scope and an argument-dependent lookup based on the types of 12496 // the arguments. 12497 UnresolvedSet<16> Functions; 12498 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12499 if (S && OverOp != OO_None) 12500 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12501 Functions); 12502 12503 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12504 } 12505 12506 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12507 } 12508 12509 // Unary Operators. 'Tok' is the token for the operator. 12510 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12511 tok::TokenKind Op, Expr *Input) { 12512 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12513 } 12514 12515 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12516 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12517 LabelDecl *TheDecl) { 12518 TheDecl->markUsed(Context); 12519 // Create the AST node. The address of a label always has type 'void*'. 12520 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12521 Context.getPointerType(Context.VoidTy)); 12522 } 12523 12524 /// Given the last statement in a statement-expression, check whether 12525 /// the result is a producing expression (like a call to an 12526 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12527 /// release out of the full-expression. Otherwise, return null. 12528 /// Cannot fail. 12529 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12530 // Should always be wrapped with one of these. 12531 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12532 if (!cleanups) return nullptr; 12533 12534 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12535 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12536 return nullptr; 12537 12538 // Splice out the cast. This shouldn't modify any interesting 12539 // features of the statement. 12540 Expr *producer = cast->getSubExpr(); 12541 assert(producer->getType() == cast->getType()); 12542 assert(producer->getValueKind() == cast->getValueKind()); 12543 cleanups->setSubExpr(producer); 12544 return cleanups; 12545 } 12546 12547 void Sema::ActOnStartStmtExpr() { 12548 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12549 } 12550 12551 void Sema::ActOnStmtExprError() { 12552 // Note that function is also called by TreeTransform when leaving a 12553 // StmtExpr scope without rebuilding anything. 12554 12555 DiscardCleanupsInEvaluationContext(); 12556 PopExpressionEvaluationContext(); 12557 } 12558 12559 ExprResult 12560 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12561 SourceLocation RPLoc) { // "({..})" 12562 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12563 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12564 12565 if (hasAnyUnrecoverableErrorsInThisFunction()) 12566 DiscardCleanupsInEvaluationContext(); 12567 assert(!Cleanup.exprNeedsCleanups() && 12568 "cleanups within StmtExpr not correctly bound!"); 12569 PopExpressionEvaluationContext(); 12570 12571 // FIXME: there are a variety of strange constraints to enforce here, for 12572 // example, it is not possible to goto into a stmt expression apparently. 12573 // More semantic analysis is needed. 12574 12575 // If there are sub-stmts in the compound stmt, take the type of the last one 12576 // as the type of the stmtexpr. 12577 QualType Ty = Context.VoidTy; 12578 bool StmtExprMayBindToTemp = false; 12579 if (!Compound->body_empty()) { 12580 Stmt *LastStmt = Compound->body_back(); 12581 LabelStmt *LastLabelStmt = nullptr; 12582 // If LastStmt is a label, skip down through into the body. 12583 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12584 LastLabelStmt = Label; 12585 LastStmt = Label->getSubStmt(); 12586 } 12587 12588 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12589 // Do function/array conversion on the last expression, but not 12590 // lvalue-to-rvalue. However, initialize an unqualified type. 12591 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12592 if (LastExpr.isInvalid()) 12593 return ExprError(); 12594 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12595 12596 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12597 // In ARC, if the final expression ends in a consume, splice 12598 // the consume out and bind it later. In the alternate case 12599 // (when dealing with a retainable type), the result 12600 // initialization will create a produce. In both cases the 12601 // result will be +1, and we'll need to balance that out with 12602 // a bind. 12603 if (Expr *rebuiltLastStmt 12604 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12605 LastExpr = rebuiltLastStmt; 12606 } else { 12607 LastExpr = PerformCopyInitialization( 12608 InitializedEntity::InitializeResult(LPLoc, 12609 Ty, 12610 false), 12611 SourceLocation(), 12612 LastExpr); 12613 } 12614 12615 if (LastExpr.isInvalid()) 12616 return ExprError(); 12617 if (LastExpr.get() != nullptr) { 12618 if (!LastLabelStmt) 12619 Compound->setLastStmt(LastExpr.get()); 12620 else 12621 LastLabelStmt->setSubStmt(LastExpr.get()); 12622 StmtExprMayBindToTemp = true; 12623 } 12624 } 12625 } 12626 } 12627 12628 // FIXME: Check that expression type is complete/non-abstract; statement 12629 // expressions are not lvalues. 12630 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12631 if (StmtExprMayBindToTemp) 12632 return MaybeBindToTemporary(ResStmtExpr); 12633 return ResStmtExpr; 12634 } 12635 12636 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12637 TypeSourceInfo *TInfo, 12638 ArrayRef<OffsetOfComponent> Components, 12639 SourceLocation RParenLoc) { 12640 QualType ArgTy = TInfo->getType(); 12641 bool Dependent = ArgTy->isDependentType(); 12642 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12643 12644 // We must have at least one component that refers to the type, and the first 12645 // one is known to be a field designator. Verify that the ArgTy represents 12646 // a struct/union/class. 12647 if (!Dependent && !ArgTy->isRecordType()) 12648 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12649 << ArgTy << TypeRange); 12650 12651 // Type must be complete per C99 7.17p3 because a declaring a variable 12652 // with an incomplete type would be ill-formed. 12653 if (!Dependent 12654 && RequireCompleteType(BuiltinLoc, ArgTy, 12655 diag::err_offsetof_incomplete_type, TypeRange)) 12656 return ExprError(); 12657 12658 bool DidWarnAboutNonPOD = false; 12659 QualType CurrentType = ArgTy; 12660 SmallVector<OffsetOfNode, 4> Comps; 12661 SmallVector<Expr*, 4> Exprs; 12662 for (const OffsetOfComponent &OC : Components) { 12663 if (OC.isBrackets) { 12664 // Offset of an array sub-field. TODO: Should we allow vector elements? 12665 if (!CurrentType->isDependentType()) { 12666 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12667 if(!AT) 12668 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12669 << CurrentType); 12670 CurrentType = AT->getElementType(); 12671 } else 12672 CurrentType = Context.DependentTy; 12673 12674 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12675 if (IdxRval.isInvalid()) 12676 return ExprError(); 12677 Expr *Idx = IdxRval.get(); 12678 12679 // The expression must be an integral expression. 12680 // FIXME: An integral constant expression? 12681 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12682 !Idx->getType()->isIntegerType()) 12683 return ExprError(Diag(Idx->getLocStart(), 12684 diag::err_typecheck_subscript_not_integer) 12685 << Idx->getSourceRange()); 12686 12687 // Record this array index. 12688 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12689 Exprs.push_back(Idx); 12690 continue; 12691 } 12692 12693 // Offset of a field. 12694 if (CurrentType->isDependentType()) { 12695 // We have the offset of a field, but we can't look into the dependent 12696 // type. Just record the identifier of the field. 12697 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12698 CurrentType = Context.DependentTy; 12699 continue; 12700 } 12701 12702 // We need to have a complete type to look into. 12703 if (RequireCompleteType(OC.LocStart, CurrentType, 12704 diag::err_offsetof_incomplete_type)) 12705 return ExprError(); 12706 12707 // Look for the designated field. 12708 const RecordType *RC = CurrentType->getAs<RecordType>(); 12709 if (!RC) 12710 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12711 << CurrentType); 12712 RecordDecl *RD = RC->getDecl(); 12713 12714 // C++ [lib.support.types]p5: 12715 // The macro offsetof accepts a restricted set of type arguments in this 12716 // International Standard. type shall be a POD structure or a POD union 12717 // (clause 9). 12718 // C++11 [support.types]p4: 12719 // If type is not a standard-layout class (Clause 9), the results are 12720 // undefined. 12721 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12722 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12723 unsigned DiagID = 12724 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12725 : diag::ext_offsetof_non_pod_type; 12726 12727 if (!IsSafe && !DidWarnAboutNonPOD && 12728 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12729 PDiag(DiagID) 12730 << SourceRange(Components[0].LocStart, OC.LocEnd) 12731 << CurrentType)) 12732 DidWarnAboutNonPOD = true; 12733 } 12734 12735 // Look for the field. 12736 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12737 LookupQualifiedName(R, RD); 12738 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12739 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12740 if (!MemberDecl) { 12741 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12742 MemberDecl = IndirectMemberDecl->getAnonField(); 12743 } 12744 12745 if (!MemberDecl) 12746 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12747 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12748 OC.LocEnd)); 12749 12750 // C99 7.17p3: 12751 // (If the specified member is a bit-field, the behavior is undefined.) 12752 // 12753 // We diagnose this as an error. 12754 if (MemberDecl->isBitField()) { 12755 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12756 << MemberDecl->getDeclName() 12757 << SourceRange(BuiltinLoc, RParenLoc); 12758 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12759 return ExprError(); 12760 } 12761 12762 RecordDecl *Parent = MemberDecl->getParent(); 12763 if (IndirectMemberDecl) 12764 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12765 12766 // If the member was found in a base class, introduce OffsetOfNodes for 12767 // the base class indirections. 12768 CXXBasePaths Paths; 12769 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12770 Paths)) { 12771 if (Paths.getDetectedVirtual()) { 12772 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12773 << MemberDecl->getDeclName() 12774 << SourceRange(BuiltinLoc, RParenLoc); 12775 return ExprError(); 12776 } 12777 12778 CXXBasePath &Path = Paths.front(); 12779 for (const CXXBasePathElement &B : Path) 12780 Comps.push_back(OffsetOfNode(B.Base)); 12781 } 12782 12783 if (IndirectMemberDecl) { 12784 for (auto *FI : IndirectMemberDecl->chain()) { 12785 assert(isa<FieldDecl>(FI)); 12786 Comps.push_back(OffsetOfNode(OC.LocStart, 12787 cast<FieldDecl>(FI), OC.LocEnd)); 12788 } 12789 } else 12790 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12791 12792 CurrentType = MemberDecl->getType().getNonReferenceType(); 12793 } 12794 12795 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12796 Comps, Exprs, RParenLoc); 12797 } 12798 12799 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12800 SourceLocation BuiltinLoc, 12801 SourceLocation TypeLoc, 12802 ParsedType ParsedArgTy, 12803 ArrayRef<OffsetOfComponent> Components, 12804 SourceLocation RParenLoc) { 12805 12806 TypeSourceInfo *ArgTInfo; 12807 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12808 if (ArgTy.isNull()) 12809 return ExprError(); 12810 12811 if (!ArgTInfo) 12812 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12813 12814 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12815 } 12816 12817 12818 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12819 Expr *CondExpr, 12820 Expr *LHSExpr, Expr *RHSExpr, 12821 SourceLocation RPLoc) { 12822 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12823 12824 ExprValueKind VK = VK_RValue; 12825 ExprObjectKind OK = OK_Ordinary; 12826 QualType resType; 12827 bool ValueDependent = false; 12828 bool CondIsTrue = false; 12829 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12830 resType = Context.DependentTy; 12831 ValueDependent = true; 12832 } else { 12833 // The conditional expression is required to be a constant expression. 12834 llvm::APSInt condEval(32); 12835 ExprResult CondICE 12836 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12837 diag::err_typecheck_choose_expr_requires_constant, false); 12838 if (CondICE.isInvalid()) 12839 return ExprError(); 12840 CondExpr = CondICE.get(); 12841 CondIsTrue = condEval.getZExtValue(); 12842 12843 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12844 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12845 12846 resType = ActiveExpr->getType(); 12847 ValueDependent = ActiveExpr->isValueDependent(); 12848 VK = ActiveExpr->getValueKind(); 12849 OK = ActiveExpr->getObjectKind(); 12850 } 12851 12852 return new (Context) 12853 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12854 CondIsTrue, resType->isDependentType(), ValueDependent); 12855 } 12856 12857 //===----------------------------------------------------------------------===// 12858 // Clang Extensions. 12859 //===----------------------------------------------------------------------===// 12860 12861 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12862 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12863 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12864 12865 if (LangOpts.CPlusPlus) { 12866 Decl *ManglingContextDecl; 12867 if (MangleNumberingContext *MCtx = 12868 getCurrentMangleNumberContext(Block->getDeclContext(), 12869 ManglingContextDecl)) { 12870 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12871 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12872 } 12873 } 12874 12875 PushBlockScope(CurScope, Block); 12876 CurContext->addDecl(Block); 12877 if (CurScope) 12878 PushDeclContext(CurScope, Block); 12879 else 12880 CurContext = Block; 12881 12882 getCurBlock()->HasImplicitReturnType = true; 12883 12884 // Enter a new evaluation context to insulate the block from any 12885 // cleanups from the enclosing full-expression. 12886 PushExpressionEvaluationContext( 12887 ExpressionEvaluationContext::PotentiallyEvaluated); 12888 } 12889 12890 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12891 Scope *CurScope) { 12892 assert(ParamInfo.getIdentifier() == nullptr && 12893 "block-id should have no identifier!"); 12894 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 12895 BlockScopeInfo *CurBlock = getCurBlock(); 12896 12897 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12898 QualType T = Sig->getType(); 12899 12900 // FIXME: We should allow unexpanded parameter packs here, but that would, 12901 // in turn, make the block expression contain unexpanded parameter packs. 12902 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12903 // Drop the parameters. 12904 FunctionProtoType::ExtProtoInfo EPI; 12905 EPI.HasTrailingReturn = false; 12906 EPI.TypeQuals |= DeclSpec::TQ_const; 12907 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12908 Sig = Context.getTrivialTypeSourceInfo(T); 12909 } 12910 12911 // GetTypeForDeclarator always produces a function type for a block 12912 // literal signature. Furthermore, it is always a FunctionProtoType 12913 // unless the function was written with a typedef. 12914 assert(T->isFunctionType() && 12915 "GetTypeForDeclarator made a non-function block signature"); 12916 12917 // Look for an explicit signature in that function type. 12918 FunctionProtoTypeLoc ExplicitSignature; 12919 12920 if ((ExplicitSignature = 12921 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 12922 12923 // Check whether that explicit signature was synthesized by 12924 // GetTypeForDeclarator. If so, don't save that as part of the 12925 // written signature. 12926 if (ExplicitSignature.getLocalRangeBegin() == 12927 ExplicitSignature.getLocalRangeEnd()) { 12928 // This would be much cheaper if we stored TypeLocs instead of 12929 // TypeSourceInfos. 12930 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12931 unsigned Size = Result.getFullDataSize(); 12932 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12933 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12934 12935 ExplicitSignature = FunctionProtoTypeLoc(); 12936 } 12937 } 12938 12939 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12940 CurBlock->FunctionType = T; 12941 12942 const FunctionType *Fn = T->getAs<FunctionType>(); 12943 QualType RetTy = Fn->getReturnType(); 12944 bool isVariadic = 12945 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12946 12947 CurBlock->TheDecl->setIsVariadic(isVariadic); 12948 12949 // Context.DependentTy is used as a placeholder for a missing block 12950 // return type. TODO: what should we do with declarators like: 12951 // ^ * { ... } 12952 // If the answer is "apply template argument deduction".... 12953 if (RetTy != Context.DependentTy) { 12954 CurBlock->ReturnType = RetTy; 12955 CurBlock->TheDecl->setBlockMissingReturnType(false); 12956 CurBlock->HasImplicitReturnType = false; 12957 } 12958 12959 // Push block parameters from the declarator if we had them. 12960 SmallVector<ParmVarDecl*, 8> Params; 12961 if (ExplicitSignature) { 12962 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12963 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12964 if (Param->getIdentifier() == nullptr && 12965 !Param->isImplicit() && 12966 !Param->isInvalidDecl() && 12967 !getLangOpts().CPlusPlus) 12968 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12969 Params.push_back(Param); 12970 } 12971 12972 // Fake up parameter variables if we have a typedef, like 12973 // ^ fntype { ... } 12974 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12975 for (const auto &I : Fn->param_types()) { 12976 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12977 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12978 Params.push_back(Param); 12979 } 12980 } 12981 12982 // Set the parameters on the block decl. 12983 if (!Params.empty()) { 12984 CurBlock->TheDecl->setParams(Params); 12985 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12986 /*CheckParameterNames=*/false); 12987 } 12988 12989 // Finally we can process decl attributes. 12990 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12991 12992 // Put the parameter variables in scope. 12993 for (auto AI : CurBlock->TheDecl->parameters()) { 12994 AI->setOwningFunction(CurBlock->TheDecl); 12995 12996 // If this has an identifier, add it to the scope stack. 12997 if (AI->getIdentifier()) { 12998 CheckShadow(CurBlock->TheScope, AI); 12999 13000 PushOnScopeChains(AI, CurBlock->TheScope); 13001 } 13002 } 13003 } 13004 13005 /// ActOnBlockError - If there is an error parsing a block, this callback 13006 /// is invoked to pop the information about the block from the action impl. 13007 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13008 // Leave the expression-evaluation context. 13009 DiscardCleanupsInEvaluationContext(); 13010 PopExpressionEvaluationContext(); 13011 13012 // Pop off CurBlock, handle nested blocks. 13013 PopDeclContext(); 13014 PopFunctionScopeInfo(); 13015 } 13016 13017 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13018 /// literal was successfully completed. ^(int x){...} 13019 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13020 Stmt *Body, Scope *CurScope) { 13021 // If blocks are disabled, emit an error. 13022 if (!LangOpts.Blocks) 13023 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13024 13025 // Leave the expression-evaluation context. 13026 if (hasAnyUnrecoverableErrorsInThisFunction()) 13027 DiscardCleanupsInEvaluationContext(); 13028 assert(!Cleanup.exprNeedsCleanups() && 13029 "cleanups within block not correctly bound!"); 13030 PopExpressionEvaluationContext(); 13031 13032 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13033 13034 if (BSI->HasImplicitReturnType) 13035 deduceClosureReturnType(*BSI); 13036 13037 PopDeclContext(); 13038 13039 QualType RetTy = Context.VoidTy; 13040 if (!BSI->ReturnType.isNull()) 13041 RetTy = BSI->ReturnType; 13042 13043 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 13044 QualType BlockTy; 13045 13046 // Set the captured variables on the block. 13047 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13048 SmallVector<BlockDecl::Capture, 4> Captures; 13049 for (Capture &Cap : BSI->Captures) { 13050 if (Cap.isThisCapture()) 13051 continue; 13052 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13053 Cap.isNested(), Cap.getInitExpr()); 13054 Captures.push_back(NewCap); 13055 } 13056 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13057 13058 // If the user wrote a function type in some form, try to use that. 13059 if (!BSI->FunctionType.isNull()) { 13060 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13061 13062 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13063 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13064 13065 // Turn protoless block types into nullary block types. 13066 if (isa<FunctionNoProtoType>(FTy)) { 13067 FunctionProtoType::ExtProtoInfo EPI; 13068 EPI.ExtInfo = Ext; 13069 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13070 13071 // Otherwise, if we don't need to change anything about the function type, 13072 // preserve its sugar structure. 13073 } else if (FTy->getReturnType() == RetTy && 13074 (!NoReturn || FTy->getNoReturnAttr())) { 13075 BlockTy = BSI->FunctionType; 13076 13077 // Otherwise, make the minimal modifications to the function type. 13078 } else { 13079 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13080 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13081 EPI.TypeQuals = 0; // FIXME: silently? 13082 EPI.ExtInfo = Ext; 13083 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13084 } 13085 13086 // If we don't have a function type, just build one from nothing. 13087 } else { 13088 FunctionProtoType::ExtProtoInfo EPI; 13089 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13090 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13091 } 13092 13093 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13094 BlockTy = Context.getBlockPointerType(BlockTy); 13095 13096 // If needed, diagnose invalid gotos and switches in the block. 13097 if (getCurFunction()->NeedsScopeChecking() && 13098 !PP.isCodeCompletionEnabled()) 13099 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13100 13101 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13102 13103 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13104 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13105 13106 // Try to apply the named return value optimization. We have to check again 13107 // if we can do this, though, because blocks keep return statements around 13108 // to deduce an implicit return type. 13109 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13110 !BSI->TheDecl->isDependentContext()) 13111 computeNRVO(Body, BSI); 13112 13113 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13114 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13115 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13116 13117 // If the block isn't obviously global, i.e. it captures anything at 13118 // all, then we need to do a few things in the surrounding context: 13119 if (Result->getBlockDecl()->hasCaptures()) { 13120 // First, this expression has a new cleanup object. 13121 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13122 Cleanup.setExprNeedsCleanups(true); 13123 13124 // It also gets a branch-protected scope if any of the captured 13125 // variables needs destruction. 13126 for (const auto &CI : Result->getBlockDecl()->captures()) { 13127 const VarDecl *var = CI.getVariable(); 13128 if (var->getType().isDestructedType() != QualType::DK_none) { 13129 setFunctionHasBranchProtectedScope(); 13130 break; 13131 } 13132 } 13133 } 13134 13135 return Result; 13136 } 13137 13138 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13139 SourceLocation RPLoc) { 13140 TypeSourceInfo *TInfo; 13141 GetTypeFromParser(Ty, &TInfo); 13142 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13143 } 13144 13145 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13146 Expr *E, TypeSourceInfo *TInfo, 13147 SourceLocation RPLoc) { 13148 Expr *OrigExpr = E; 13149 bool IsMS = false; 13150 13151 // CUDA device code does not support varargs. 13152 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13153 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13154 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13155 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13156 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13157 } 13158 } 13159 13160 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13161 // as Microsoft ABI on an actual Microsoft platform, where 13162 // __builtin_ms_va_list and __builtin_va_list are the same.) 13163 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13164 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13165 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13166 if (Context.hasSameType(MSVaListType, E->getType())) { 13167 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13168 return ExprError(); 13169 IsMS = true; 13170 } 13171 } 13172 13173 // Get the va_list type 13174 QualType VaListType = Context.getBuiltinVaListType(); 13175 if (!IsMS) { 13176 if (VaListType->isArrayType()) { 13177 // Deal with implicit array decay; for example, on x86-64, 13178 // va_list is an array, but it's supposed to decay to 13179 // a pointer for va_arg. 13180 VaListType = Context.getArrayDecayedType(VaListType); 13181 // Make sure the input expression also decays appropriately. 13182 ExprResult Result = UsualUnaryConversions(E); 13183 if (Result.isInvalid()) 13184 return ExprError(); 13185 E = Result.get(); 13186 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13187 // If va_list is a record type and we are compiling in C++ mode, 13188 // check the argument using reference binding. 13189 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13190 Context, Context.getLValueReferenceType(VaListType), false); 13191 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13192 if (Init.isInvalid()) 13193 return ExprError(); 13194 E = Init.getAs<Expr>(); 13195 } else { 13196 // Otherwise, the va_list argument must be an l-value because 13197 // it is modified by va_arg. 13198 if (!E->isTypeDependent() && 13199 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13200 return ExprError(); 13201 } 13202 } 13203 13204 if (!IsMS && !E->isTypeDependent() && 13205 !Context.hasSameType(VaListType, E->getType())) 13206 return ExprError(Diag(E->getLocStart(), 13207 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13208 << OrigExpr->getType() << E->getSourceRange()); 13209 13210 if (!TInfo->getType()->isDependentType()) { 13211 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13212 diag::err_second_parameter_to_va_arg_incomplete, 13213 TInfo->getTypeLoc())) 13214 return ExprError(); 13215 13216 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13217 TInfo->getType(), 13218 diag::err_second_parameter_to_va_arg_abstract, 13219 TInfo->getTypeLoc())) 13220 return ExprError(); 13221 13222 if (!TInfo->getType().isPODType(Context)) { 13223 Diag(TInfo->getTypeLoc().getBeginLoc(), 13224 TInfo->getType()->isObjCLifetimeType() 13225 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13226 : diag::warn_second_parameter_to_va_arg_not_pod) 13227 << TInfo->getType() 13228 << TInfo->getTypeLoc().getSourceRange(); 13229 } 13230 13231 // Check for va_arg where arguments of the given type will be promoted 13232 // (i.e. this va_arg is guaranteed to have undefined behavior). 13233 QualType PromoteType; 13234 if (TInfo->getType()->isPromotableIntegerType()) { 13235 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13236 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13237 PromoteType = QualType(); 13238 } 13239 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13240 PromoteType = Context.DoubleTy; 13241 if (!PromoteType.isNull()) 13242 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13243 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13244 << TInfo->getType() 13245 << PromoteType 13246 << TInfo->getTypeLoc().getSourceRange()); 13247 } 13248 13249 QualType T = TInfo->getType().getNonLValueExprType(Context); 13250 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13251 } 13252 13253 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13254 // The type of __null will be int or long, depending on the size of 13255 // pointers on the target. 13256 QualType Ty; 13257 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13258 if (pw == Context.getTargetInfo().getIntWidth()) 13259 Ty = Context.IntTy; 13260 else if (pw == Context.getTargetInfo().getLongWidth()) 13261 Ty = Context.LongTy; 13262 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13263 Ty = Context.LongLongTy; 13264 else { 13265 llvm_unreachable("I don't know size of pointer!"); 13266 } 13267 13268 return new (Context) GNUNullExpr(Ty, TokenLoc); 13269 } 13270 13271 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13272 bool Diagnose) { 13273 if (!getLangOpts().ObjC1) 13274 return false; 13275 13276 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13277 if (!PT) 13278 return false; 13279 13280 if (!PT->isObjCIdType()) { 13281 // Check if the destination is the 'NSString' interface. 13282 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13283 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13284 return false; 13285 } 13286 13287 // Ignore any parens, implicit casts (should only be 13288 // array-to-pointer decays), and not-so-opaque values. The last is 13289 // important for making this trigger for property assignments. 13290 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13291 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13292 if (OV->getSourceExpr()) 13293 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13294 13295 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13296 if (!SL || !SL->isAscii()) 13297 return false; 13298 if (Diagnose) { 13299 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13300 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13301 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13302 } 13303 return true; 13304 } 13305 13306 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13307 const Expr *SrcExpr) { 13308 if (!DstType->isFunctionPointerType() || 13309 !SrcExpr->getType()->isFunctionType()) 13310 return false; 13311 13312 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13313 if (!DRE) 13314 return false; 13315 13316 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13317 if (!FD) 13318 return false; 13319 13320 return !S.checkAddressOfFunctionIsAvailable(FD, 13321 /*Complain=*/true, 13322 SrcExpr->getLocStart()); 13323 } 13324 13325 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13326 SourceLocation Loc, 13327 QualType DstType, QualType SrcType, 13328 Expr *SrcExpr, AssignmentAction Action, 13329 bool *Complained) { 13330 if (Complained) 13331 *Complained = false; 13332 13333 // Decode the result (notice that AST's are still created for extensions). 13334 bool CheckInferredResultType = false; 13335 bool isInvalid = false; 13336 unsigned DiagKind = 0; 13337 FixItHint Hint; 13338 ConversionFixItGenerator ConvHints; 13339 bool MayHaveConvFixit = false; 13340 bool MayHaveFunctionDiff = false; 13341 const ObjCInterfaceDecl *IFace = nullptr; 13342 const ObjCProtocolDecl *PDecl = nullptr; 13343 13344 switch (ConvTy) { 13345 case Compatible: 13346 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13347 return false; 13348 13349 case PointerToInt: 13350 DiagKind = diag::ext_typecheck_convert_pointer_int; 13351 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13352 MayHaveConvFixit = true; 13353 break; 13354 case IntToPointer: 13355 DiagKind = diag::ext_typecheck_convert_int_pointer; 13356 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13357 MayHaveConvFixit = true; 13358 break; 13359 case IncompatiblePointer: 13360 if (Action == AA_Passing_CFAudited) 13361 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13362 else if (SrcType->isFunctionPointerType() && 13363 DstType->isFunctionPointerType()) 13364 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13365 else 13366 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13367 13368 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13369 SrcType->isObjCObjectPointerType(); 13370 if (Hint.isNull() && !CheckInferredResultType) { 13371 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13372 } 13373 else if (CheckInferredResultType) { 13374 SrcType = SrcType.getUnqualifiedType(); 13375 DstType = DstType.getUnqualifiedType(); 13376 } 13377 MayHaveConvFixit = true; 13378 break; 13379 case IncompatiblePointerSign: 13380 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13381 break; 13382 case FunctionVoidPointer: 13383 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13384 break; 13385 case IncompatiblePointerDiscardsQualifiers: { 13386 // Perform array-to-pointer decay if necessary. 13387 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13388 13389 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13390 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13391 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13392 DiagKind = diag::err_typecheck_incompatible_address_space; 13393 break; 13394 13395 13396 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13397 DiagKind = diag::err_typecheck_incompatible_ownership; 13398 break; 13399 } 13400 13401 llvm_unreachable("unknown error case for discarding qualifiers!"); 13402 // fallthrough 13403 } 13404 case CompatiblePointerDiscardsQualifiers: 13405 // If the qualifiers lost were because we were applying the 13406 // (deprecated) C++ conversion from a string literal to a char* 13407 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13408 // Ideally, this check would be performed in 13409 // checkPointerTypesForAssignment. However, that would require a 13410 // bit of refactoring (so that the second argument is an 13411 // expression, rather than a type), which should be done as part 13412 // of a larger effort to fix checkPointerTypesForAssignment for 13413 // C++ semantics. 13414 if (getLangOpts().CPlusPlus && 13415 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13416 return false; 13417 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13418 break; 13419 case IncompatibleNestedPointerQualifiers: 13420 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13421 break; 13422 case IntToBlockPointer: 13423 DiagKind = diag::err_int_to_block_pointer; 13424 break; 13425 case IncompatibleBlockPointer: 13426 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13427 break; 13428 case IncompatibleObjCQualifiedId: { 13429 if (SrcType->isObjCQualifiedIdType()) { 13430 const ObjCObjectPointerType *srcOPT = 13431 SrcType->getAs<ObjCObjectPointerType>(); 13432 for (auto *srcProto : srcOPT->quals()) { 13433 PDecl = srcProto; 13434 break; 13435 } 13436 if (const ObjCInterfaceType *IFaceT = 13437 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13438 IFace = IFaceT->getDecl(); 13439 } 13440 else if (DstType->isObjCQualifiedIdType()) { 13441 const ObjCObjectPointerType *dstOPT = 13442 DstType->getAs<ObjCObjectPointerType>(); 13443 for (auto *dstProto : dstOPT->quals()) { 13444 PDecl = dstProto; 13445 break; 13446 } 13447 if (const ObjCInterfaceType *IFaceT = 13448 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13449 IFace = IFaceT->getDecl(); 13450 } 13451 DiagKind = diag::warn_incompatible_qualified_id; 13452 break; 13453 } 13454 case IncompatibleVectors: 13455 DiagKind = diag::warn_incompatible_vectors; 13456 break; 13457 case IncompatibleObjCWeakRef: 13458 DiagKind = diag::err_arc_weak_unavailable_assign; 13459 break; 13460 case Incompatible: 13461 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13462 if (Complained) 13463 *Complained = true; 13464 return true; 13465 } 13466 13467 DiagKind = diag::err_typecheck_convert_incompatible; 13468 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13469 MayHaveConvFixit = true; 13470 isInvalid = true; 13471 MayHaveFunctionDiff = true; 13472 break; 13473 } 13474 13475 QualType FirstType, SecondType; 13476 switch (Action) { 13477 case AA_Assigning: 13478 case AA_Initializing: 13479 // The destination type comes first. 13480 FirstType = DstType; 13481 SecondType = SrcType; 13482 break; 13483 13484 case AA_Returning: 13485 case AA_Passing: 13486 case AA_Passing_CFAudited: 13487 case AA_Converting: 13488 case AA_Sending: 13489 case AA_Casting: 13490 // The source type comes first. 13491 FirstType = SrcType; 13492 SecondType = DstType; 13493 break; 13494 } 13495 13496 PartialDiagnostic FDiag = PDiag(DiagKind); 13497 if (Action == AA_Passing_CFAudited) 13498 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13499 else 13500 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13501 13502 // If we can fix the conversion, suggest the FixIts. 13503 assert(ConvHints.isNull() || Hint.isNull()); 13504 if (!ConvHints.isNull()) { 13505 for (FixItHint &H : ConvHints.Hints) 13506 FDiag << H; 13507 } else { 13508 FDiag << Hint; 13509 } 13510 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13511 13512 if (MayHaveFunctionDiff) 13513 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13514 13515 Diag(Loc, FDiag); 13516 if (DiagKind == diag::warn_incompatible_qualified_id && 13517 PDecl && IFace && !IFace->hasDefinition()) 13518 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13519 << IFace->getName() << PDecl->getName(); 13520 13521 if (SecondType == Context.OverloadTy) 13522 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13523 FirstType, /*TakingAddress=*/true); 13524 13525 if (CheckInferredResultType) 13526 EmitRelatedResultTypeNote(SrcExpr); 13527 13528 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13529 EmitRelatedResultTypeNoteForReturn(DstType); 13530 13531 if (Complained) 13532 *Complained = true; 13533 return isInvalid; 13534 } 13535 13536 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13537 llvm::APSInt *Result) { 13538 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13539 public: 13540 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13541 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13542 } 13543 } Diagnoser; 13544 13545 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13546 } 13547 13548 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13549 llvm::APSInt *Result, 13550 unsigned DiagID, 13551 bool AllowFold) { 13552 class IDDiagnoser : public VerifyICEDiagnoser { 13553 unsigned DiagID; 13554 13555 public: 13556 IDDiagnoser(unsigned DiagID) 13557 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13558 13559 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13560 S.Diag(Loc, DiagID) << SR; 13561 } 13562 } Diagnoser(DiagID); 13563 13564 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13565 } 13566 13567 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13568 SourceRange SR) { 13569 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13570 } 13571 13572 ExprResult 13573 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13574 VerifyICEDiagnoser &Diagnoser, 13575 bool AllowFold) { 13576 SourceLocation DiagLoc = E->getLocStart(); 13577 13578 if (getLangOpts().CPlusPlus11) { 13579 // C++11 [expr.const]p5: 13580 // If an expression of literal class type is used in a context where an 13581 // integral constant expression is required, then that class type shall 13582 // have a single non-explicit conversion function to an integral or 13583 // unscoped enumeration type 13584 ExprResult Converted; 13585 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13586 public: 13587 CXX11ConvertDiagnoser(bool Silent) 13588 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13589 Silent, true) {} 13590 13591 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13592 QualType T) override { 13593 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13594 } 13595 13596 SemaDiagnosticBuilder diagnoseIncomplete( 13597 Sema &S, SourceLocation Loc, QualType T) override { 13598 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13599 } 13600 13601 SemaDiagnosticBuilder diagnoseExplicitConv( 13602 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13603 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13604 } 13605 13606 SemaDiagnosticBuilder noteExplicitConv( 13607 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13608 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13609 << ConvTy->isEnumeralType() << ConvTy; 13610 } 13611 13612 SemaDiagnosticBuilder diagnoseAmbiguous( 13613 Sema &S, SourceLocation Loc, QualType T) override { 13614 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13615 } 13616 13617 SemaDiagnosticBuilder noteAmbiguous( 13618 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13619 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13620 << ConvTy->isEnumeralType() << ConvTy; 13621 } 13622 13623 SemaDiagnosticBuilder diagnoseConversion( 13624 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13625 llvm_unreachable("conversion functions are permitted"); 13626 } 13627 } ConvertDiagnoser(Diagnoser.Suppress); 13628 13629 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13630 ConvertDiagnoser); 13631 if (Converted.isInvalid()) 13632 return Converted; 13633 E = Converted.get(); 13634 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13635 return ExprError(); 13636 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13637 // An ICE must be of integral or unscoped enumeration type. 13638 if (!Diagnoser.Suppress) 13639 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13640 return ExprError(); 13641 } 13642 13643 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13644 // in the non-ICE case. 13645 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13646 if (Result) 13647 *Result = E->EvaluateKnownConstInt(Context); 13648 return E; 13649 } 13650 13651 Expr::EvalResult EvalResult; 13652 SmallVector<PartialDiagnosticAt, 8> Notes; 13653 EvalResult.Diag = &Notes; 13654 13655 // Try to evaluate the expression, and produce diagnostics explaining why it's 13656 // not a constant expression as a side-effect. 13657 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13658 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13659 13660 // In C++11, we can rely on diagnostics being produced for any expression 13661 // which is not a constant expression. If no diagnostics were produced, then 13662 // this is a constant expression. 13663 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13664 if (Result) 13665 *Result = EvalResult.Val.getInt(); 13666 return E; 13667 } 13668 13669 // If our only note is the usual "invalid subexpression" note, just point 13670 // the caret at its location rather than producing an essentially 13671 // redundant note. 13672 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13673 diag::note_invalid_subexpr_in_const_expr) { 13674 DiagLoc = Notes[0].first; 13675 Notes.clear(); 13676 } 13677 13678 if (!Folded || !AllowFold) { 13679 if (!Diagnoser.Suppress) { 13680 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13681 for (const PartialDiagnosticAt &Note : Notes) 13682 Diag(Note.first, Note.second); 13683 } 13684 13685 return ExprError(); 13686 } 13687 13688 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13689 for (const PartialDiagnosticAt &Note : Notes) 13690 Diag(Note.first, Note.second); 13691 13692 if (Result) 13693 *Result = EvalResult.Val.getInt(); 13694 return E; 13695 } 13696 13697 namespace { 13698 // Handle the case where we conclude a expression which we speculatively 13699 // considered to be unevaluated is actually evaluated. 13700 class TransformToPE : public TreeTransform<TransformToPE> { 13701 typedef TreeTransform<TransformToPE> BaseTransform; 13702 13703 public: 13704 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13705 13706 // Make sure we redo semantic analysis 13707 bool AlwaysRebuild() { return true; } 13708 13709 // Make sure we handle LabelStmts correctly. 13710 // FIXME: This does the right thing, but maybe we need a more general 13711 // fix to TreeTransform? 13712 StmtResult TransformLabelStmt(LabelStmt *S) { 13713 S->getDecl()->setStmt(nullptr); 13714 return BaseTransform::TransformLabelStmt(S); 13715 } 13716 13717 // We need to special-case DeclRefExprs referring to FieldDecls which 13718 // are not part of a member pointer formation; normal TreeTransforming 13719 // doesn't catch this case because of the way we represent them in the AST. 13720 // FIXME: This is a bit ugly; is it really the best way to handle this 13721 // case? 13722 // 13723 // Error on DeclRefExprs referring to FieldDecls. 13724 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13725 if (isa<FieldDecl>(E->getDecl()) && 13726 !SemaRef.isUnevaluatedContext()) 13727 return SemaRef.Diag(E->getLocation(), 13728 diag::err_invalid_non_static_member_use) 13729 << E->getDecl() << E->getSourceRange(); 13730 13731 return BaseTransform::TransformDeclRefExpr(E); 13732 } 13733 13734 // Exception: filter out member pointer formation 13735 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13736 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13737 return E; 13738 13739 return BaseTransform::TransformUnaryOperator(E); 13740 } 13741 13742 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13743 // Lambdas never need to be transformed. 13744 return E; 13745 } 13746 }; 13747 } 13748 13749 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13750 assert(isUnevaluatedContext() && 13751 "Should only transform unevaluated expressions"); 13752 ExprEvalContexts.back().Context = 13753 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13754 if (isUnevaluatedContext()) 13755 return E; 13756 return TransformToPE(*this).TransformExpr(E); 13757 } 13758 13759 void 13760 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13761 Decl *LambdaContextDecl, 13762 bool IsDecltype) { 13763 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13764 LambdaContextDecl, IsDecltype); 13765 Cleanup.reset(); 13766 if (!MaybeODRUseExprs.empty()) 13767 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13768 } 13769 13770 void 13771 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13772 ReuseLambdaContextDecl_t, 13773 bool IsDecltype) { 13774 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13775 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13776 } 13777 13778 void Sema::PopExpressionEvaluationContext() { 13779 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13780 unsigned NumTypos = Rec.NumTypos; 13781 13782 if (!Rec.Lambdas.empty()) { 13783 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13784 unsigned D; 13785 if (Rec.isUnevaluated()) { 13786 // C++11 [expr.prim.lambda]p2: 13787 // A lambda-expression shall not appear in an unevaluated operand 13788 // (Clause 5). 13789 D = diag::err_lambda_unevaluated_operand; 13790 } else { 13791 // C++1y [expr.const]p2: 13792 // A conditional-expression e is a core constant expression unless the 13793 // evaluation of e, following the rules of the abstract machine, would 13794 // evaluate [...] a lambda-expression. 13795 D = diag::err_lambda_in_constant_expression; 13796 } 13797 13798 // C++1z allows lambda expressions as core constant expressions. 13799 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13800 // 1607) from appearing within template-arguments and array-bounds that 13801 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13802 // unevaluated contexts) might lift some of these restrictions in a 13803 // future version. 13804 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17) 13805 for (const auto *L : Rec.Lambdas) 13806 Diag(L->getLocStart(), D); 13807 } else { 13808 // Mark the capture expressions odr-used. This was deferred 13809 // during lambda expression creation. 13810 for (auto *Lambda : Rec.Lambdas) { 13811 for (auto *C : Lambda->capture_inits()) 13812 MarkDeclarationsReferencedInExpr(C); 13813 } 13814 } 13815 } 13816 13817 // When are coming out of an unevaluated context, clear out any 13818 // temporaries that we may have created as part of the evaluation of 13819 // the expression in that context: they aren't relevant because they 13820 // will never be constructed. 13821 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13822 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13823 ExprCleanupObjects.end()); 13824 Cleanup = Rec.ParentCleanup; 13825 CleanupVarDeclMarking(); 13826 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13827 // Otherwise, merge the contexts together. 13828 } else { 13829 Cleanup.mergeFrom(Rec.ParentCleanup); 13830 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13831 Rec.SavedMaybeODRUseExprs.end()); 13832 } 13833 13834 // Pop the current expression evaluation context off the stack. 13835 ExprEvalContexts.pop_back(); 13836 13837 if (!ExprEvalContexts.empty()) 13838 ExprEvalContexts.back().NumTypos += NumTypos; 13839 else 13840 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13841 "last ExpressionEvaluationContextRecord"); 13842 } 13843 13844 void Sema::DiscardCleanupsInEvaluationContext() { 13845 ExprCleanupObjects.erase( 13846 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13847 ExprCleanupObjects.end()); 13848 Cleanup.reset(); 13849 MaybeODRUseExprs.clear(); 13850 } 13851 13852 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13853 if (!E->getType()->isVariablyModifiedType()) 13854 return E; 13855 return TransformToPotentiallyEvaluated(E); 13856 } 13857 13858 /// Are we within a context in which some evaluation could be performed (be it 13859 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13860 /// captured by C++'s idea of an "unevaluated context". 13861 static bool isEvaluatableContext(Sema &SemaRef) { 13862 switch (SemaRef.ExprEvalContexts.back().Context) { 13863 case Sema::ExpressionEvaluationContext::Unevaluated: 13864 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13865 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13866 // Expressions in this context are never evaluated. 13867 return false; 13868 13869 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13870 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13871 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13872 // Expressions in this context could be evaluated. 13873 return true; 13874 13875 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13876 // Referenced declarations will only be used if the construct in the 13877 // containing expression is used, at which point we'll be given another 13878 // turn to mark them. 13879 return false; 13880 } 13881 llvm_unreachable("Invalid context"); 13882 } 13883 13884 /// Are we within a context in which references to resolved functions or to 13885 /// variables result in odr-use? 13886 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13887 // An expression in a template is not really an expression until it's been 13888 // instantiated, so it doesn't trigger odr-use. 13889 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13890 return false; 13891 13892 switch (SemaRef.ExprEvalContexts.back().Context) { 13893 case Sema::ExpressionEvaluationContext::Unevaluated: 13894 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13895 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13896 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13897 return false; 13898 13899 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13900 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13901 return true; 13902 13903 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13904 return false; 13905 } 13906 llvm_unreachable("Invalid context"); 13907 } 13908 13909 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13910 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13911 return Func->isConstexpr() && 13912 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13913 } 13914 13915 /// \brief Mark a function referenced, and check whether it is odr-used 13916 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13917 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13918 bool MightBeOdrUse) { 13919 assert(Func && "No function?"); 13920 13921 Func->setReferenced(); 13922 13923 // C++11 [basic.def.odr]p3: 13924 // A function whose name appears as a potentially-evaluated expression is 13925 // odr-used if it is the unique lookup result or the selected member of a 13926 // set of overloaded functions [...]. 13927 // 13928 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13929 // can just check that here. 13930 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13931 13932 // Determine whether we require a function definition to exist, per 13933 // C++11 [temp.inst]p3: 13934 // Unless a function template specialization has been explicitly 13935 // instantiated or explicitly specialized, the function template 13936 // specialization is implicitly instantiated when the specialization is 13937 // referenced in a context that requires a function definition to exist. 13938 // 13939 // That is either when this is an odr-use, or when a usage of a constexpr 13940 // function occurs within an evaluatable context. 13941 bool NeedDefinition = 13942 OdrUse || (isEvaluatableContext(*this) && 13943 isImplicitlyDefinableConstexprFunction(Func)); 13944 13945 // C++14 [temp.expl.spec]p6: 13946 // If a template [...] is explicitly specialized then that specialization 13947 // shall be declared before the first use of that specialization that would 13948 // cause an implicit instantiation to take place, in every translation unit 13949 // in which such a use occurs 13950 if (NeedDefinition && 13951 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13952 Func->getMemberSpecializationInfo())) 13953 checkSpecializationVisibility(Loc, Func); 13954 13955 // C++14 [except.spec]p17: 13956 // An exception-specification is considered to be needed when: 13957 // - the function is odr-used or, if it appears in an unevaluated operand, 13958 // would be odr-used if the expression were potentially-evaluated; 13959 // 13960 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13961 // function is a pure virtual function we're calling, and in that case the 13962 // function was selected by overload resolution and we need to resolve its 13963 // exception specification for a different reason. 13964 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13965 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13966 ResolveExceptionSpec(Loc, FPT); 13967 13968 // If we don't need to mark the function as used, and we don't need to 13969 // try to provide a definition, there's nothing more to do. 13970 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13971 (!NeedDefinition || Func->getBody())) 13972 return; 13973 13974 // Note that this declaration has been used. 13975 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13976 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13977 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13978 if (Constructor->isDefaultConstructor()) { 13979 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13980 return; 13981 DefineImplicitDefaultConstructor(Loc, Constructor); 13982 } else if (Constructor->isCopyConstructor()) { 13983 DefineImplicitCopyConstructor(Loc, Constructor); 13984 } else if (Constructor->isMoveConstructor()) { 13985 DefineImplicitMoveConstructor(Loc, Constructor); 13986 } 13987 } else if (Constructor->getInheritedConstructor()) { 13988 DefineInheritingConstructor(Loc, Constructor); 13989 } 13990 } else if (CXXDestructorDecl *Destructor = 13991 dyn_cast<CXXDestructorDecl>(Func)) { 13992 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13993 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13994 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13995 return; 13996 DefineImplicitDestructor(Loc, Destructor); 13997 } 13998 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13999 MarkVTableUsed(Loc, Destructor->getParent()); 14000 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14001 if (MethodDecl->isOverloadedOperator() && 14002 MethodDecl->getOverloadedOperator() == OO_Equal) { 14003 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14004 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14005 if (MethodDecl->isCopyAssignmentOperator()) 14006 DefineImplicitCopyAssignment(Loc, MethodDecl); 14007 else if (MethodDecl->isMoveAssignmentOperator()) 14008 DefineImplicitMoveAssignment(Loc, MethodDecl); 14009 } 14010 } else if (isa<CXXConversionDecl>(MethodDecl) && 14011 MethodDecl->getParent()->isLambda()) { 14012 CXXConversionDecl *Conversion = 14013 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14014 if (Conversion->isLambdaToBlockPointerConversion()) 14015 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14016 else 14017 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14018 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14019 MarkVTableUsed(Loc, MethodDecl->getParent()); 14020 } 14021 14022 // Recursive functions should be marked when used from another function. 14023 // FIXME: Is this really right? 14024 if (CurContext == Func) return; 14025 14026 // Implicit instantiation of function templates and member functions of 14027 // class templates. 14028 if (Func->isImplicitlyInstantiable()) { 14029 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14030 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14031 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14032 if (FirstInstantiation) { 14033 PointOfInstantiation = Loc; 14034 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14035 } else if (TSK != TSK_ImplicitInstantiation) { 14036 // Use the point of use as the point of instantiation, instead of the 14037 // point of explicit instantiation (which we track as the actual point of 14038 // instantiation). This gives better backtraces in diagnostics. 14039 PointOfInstantiation = Loc; 14040 } 14041 14042 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14043 Func->isConstexpr()) { 14044 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14045 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14046 CodeSynthesisContexts.size()) 14047 PendingLocalImplicitInstantiations.push_back( 14048 std::make_pair(Func, PointOfInstantiation)); 14049 else if (Func->isConstexpr()) 14050 // Do not defer instantiations of constexpr functions, to avoid the 14051 // expression evaluator needing to call back into Sema if it sees a 14052 // call to such a function. 14053 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14054 else { 14055 Func->setInstantiationIsPending(true); 14056 PendingInstantiations.push_back(std::make_pair(Func, 14057 PointOfInstantiation)); 14058 // Notify the consumer that a function was implicitly instantiated. 14059 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14060 } 14061 } 14062 } else { 14063 // Walk redefinitions, as some of them may be instantiable. 14064 for (auto i : Func->redecls()) { 14065 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14066 MarkFunctionReferenced(Loc, i, OdrUse); 14067 } 14068 } 14069 14070 if (!OdrUse) return; 14071 14072 // Keep track of used but undefined functions. 14073 if (!Func->isDefined()) { 14074 if (mightHaveNonExternalLinkage(Func)) 14075 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14076 else if (Func->getMostRecentDecl()->isInlined() && 14077 !LangOpts.GNUInline && 14078 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14079 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14080 else if (isExternalWithNoLinkageType(Func)) 14081 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14082 } 14083 14084 Func->markUsed(Context); 14085 } 14086 14087 static void 14088 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14089 ValueDecl *var, DeclContext *DC) { 14090 DeclContext *VarDC = var->getDeclContext(); 14091 14092 // If the parameter still belongs to the translation unit, then 14093 // we're actually just using one parameter in the declaration of 14094 // the next. 14095 if (isa<ParmVarDecl>(var) && 14096 isa<TranslationUnitDecl>(VarDC)) 14097 return; 14098 14099 // For C code, don't diagnose about capture if we're not actually in code 14100 // right now; it's impossible to write a non-constant expression outside of 14101 // function context, so we'll get other (more useful) diagnostics later. 14102 // 14103 // For C++, things get a bit more nasty... it would be nice to suppress this 14104 // diagnostic for certain cases like using a local variable in an array bound 14105 // for a member of a local class, but the correct predicate is not obvious. 14106 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14107 return; 14108 14109 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14110 unsigned ContextKind = 3; // unknown 14111 if (isa<CXXMethodDecl>(VarDC) && 14112 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14113 ContextKind = 2; 14114 } else if (isa<FunctionDecl>(VarDC)) { 14115 ContextKind = 0; 14116 } else if (isa<BlockDecl>(VarDC)) { 14117 ContextKind = 1; 14118 } 14119 14120 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14121 << var << ValueKind << ContextKind << VarDC; 14122 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14123 << var; 14124 14125 // FIXME: Add additional diagnostic info about class etc. which prevents 14126 // capture. 14127 } 14128 14129 14130 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14131 bool &SubCapturesAreNested, 14132 QualType &CaptureType, 14133 QualType &DeclRefType) { 14134 // Check whether we've already captured it. 14135 if (CSI->CaptureMap.count(Var)) { 14136 // If we found a capture, any subcaptures are nested. 14137 SubCapturesAreNested = true; 14138 14139 // Retrieve the capture type for this variable. 14140 CaptureType = CSI->getCapture(Var).getCaptureType(); 14141 14142 // Compute the type of an expression that refers to this variable. 14143 DeclRefType = CaptureType.getNonReferenceType(); 14144 14145 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14146 // are mutable in the sense that user can change their value - they are 14147 // private instances of the captured declarations. 14148 const Capture &Cap = CSI->getCapture(Var); 14149 if (Cap.isCopyCapture() && 14150 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14151 !(isa<CapturedRegionScopeInfo>(CSI) && 14152 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14153 DeclRefType.addConst(); 14154 return true; 14155 } 14156 return false; 14157 } 14158 14159 // Only block literals, captured statements, and lambda expressions can 14160 // capture; other scopes don't work. 14161 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14162 SourceLocation Loc, 14163 const bool Diagnose, Sema &S) { 14164 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14165 return getLambdaAwareParentOfDeclContext(DC); 14166 else if (Var->hasLocalStorage()) { 14167 if (Diagnose) 14168 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14169 } 14170 return nullptr; 14171 } 14172 14173 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14174 // certain types of variables (unnamed, variably modified types etc.) 14175 // so check for eligibility. 14176 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14177 SourceLocation Loc, 14178 const bool Diagnose, Sema &S) { 14179 14180 bool IsBlock = isa<BlockScopeInfo>(CSI); 14181 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14182 14183 // Lambdas are not allowed to capture unnamed variables 14184 // (e.g. anonymous unions). 14185 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14186 // assuming that's the intent. 14187 if (IsLambda && !Var->getDeclName()) { 14188 if (Diagnose) { 14189 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14190 S.Diag(Var->getLocation(), diag::note_declared_at); 14191 } 14192 return false; 14193 } 14194 14195 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14196 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14197 if (Diagnose) { 14198 S.Diag(Loc, diag::err_ref_vm_type); 14199 S.Diag(Var->getLocation(), diag::note_previous_decl) 14200 << Var->getDeclName(); 14201 } 14202 return false; 14203 } 14204 // Prohibit structs with flexible array members too. 14205 // We cannot capture what is in the tail end of the struct. 14206 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14207 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14208 if (Diagnose) { 14209 if (IsBlock) 14210 S.Diag(Loc, diag::err_ref_flexarray_type); 14211 else 14212 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14213 << Var->getDeclName(); 14214 S.Diag(Var->getLocation(), diag::note_previous_decl) 14215 << Var->getDeclName(); 14216 } 14217 return false; 14218 } 14219 } 14220 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14221 // Lambdas and captured statements are not allowed to capture __block 14222 // variables; they don't support the expected semantics. 14223 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14224 if (Diagnose) { 14225 S.Diag(Loc, diag::err_capture_block_variable) 14226 << Var->getDeclName() << !IsLambda; 14227 S.Diag(Var->getLocation(), diag::note_previous_decl) 14228 << Var->getDeclName(); 14229 } 14230 return false; 14231 } 14232 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14233 if (S.getLangOpts().OpenCL && IsBlock && 14234 Var->getType()->isBlockPointerType()) { 14235 if (Diagnose) 14236 S.Diag(Loc, diag::err_opencl_block_ref_block); 14237 return false; 14238 } 14239 14240 return true; 14241 } 14242 14243 // Returns true if the capture by block was successful. 14244 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14245 SourceLocation Loc, 14246 const bool BuildAndDiagnose, 14247 QualType &CaptureType, 14248 QualType &DeclRefType, 14249 const bool Nested, 14250 Sema &S) { 14251 Expr *CopyExpr = nullptr; 14252 bool ByRef = false; 14253 14254 // Blocks are not allowed to capture arrays. 14255 if (CaptureType->isArrayType()) { 14256 if (BuildAndDiagnose) { 14257 S.Diag(Loc, diag::err_ref_array_type); 14258 S.Diag(Var->getLocation(), diag::note_previous_decl) 14259 << Var->getDeclName(); 14260 } 14261 return false; 14262 } 14263 14264 // Forbid the block-capture of autoreleasing variables. 14265 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14266 if (BuildAndDiagnose) { 14267 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14268 << /*block*/ 0; 14269 S.Diag(Var->getLocation(), diag::note_previous_decl) 14270 << Var->getDeclName(); 14271 } 14272 return false; 14273 } 14274 14275 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14276 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14277 // This function finds out whether there is an AttributedType of kind 14278 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14279 // attr_objc_ownership implies __autoreleasing was explicitly specified 14280 // rather than being added implicitly by the compiler. 14281 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14282 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14283 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14284 return true; 14285 14286 // Peel off AttributedTypes that are not of kind objc_ownership. 14287 Ty = AttrTy->getModifiedType(); 14288 } 14289 14290 return false; 14291 }; 14292 14293 QualType PointeeTy = PT->getPointeeType(); 14294 14295 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14296 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14297 !IsObjCOwnershipAttributedType(PointeeTy)) { 14298 if (BuildAndDiagnose) { 14299 SourceLocation VarLoc = Var->getLocation(); 14300 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14301 { 14302 auto AddAutoreleaseNote = 14303 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14304 // Provide a fix-it for the '__autoreleasing' keyword at the 14305 // appropriate location in the variable's type. 14306 if (const auto *TSI = Var->getTypeSourceInfo()) { 14307 PointerTypeLoc PTL = 14308 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14309 if (PTL) { 14310 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14311 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14312 S.getLangOpts()); 14313 if (Loc.isValid()) { 14314 StringRef CharAtLoc = Lexer::getSourceText( 14315 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14316 S.getSourceManager(), S.getLangOpts()); 14317 AddAutoreleaseNote << FixItHint::CreateInsertion( 14318 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14319 ? " __autoreleasing " 14320 : " __autoreleasing"); 14321 } 14322 } 14323 } 14324 } 14325 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14326 } 14327 } 14328 } 14329 14330 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14331 if (HasBlocksAttr || CaptureType->isReferenceType() || 14332 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 14333 // Block capture by reference does not change the capture or 14334 // declaration reference types. 14335 ByRef = true; 14336 } else { 14337 // Block capture by copy introduces 'const'. 14338 CaptureType = CaptureType.getNonReferenceType().withConst(); 14339 DeclRefType = CaptureType; 14340 14341 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14342 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14343 // The capture logic needs the destructor, so make sure we mark it. 14344 // Usually this is unnecessary because most local variables have 14345 // their destructors marked at declaration time, but parameters are 14346 // an exception because it's technically only the call site that 14347 // actually requires the destructor. 14348 if (isa<ParmVarDecl>(Var)) 14349 S.FinalizeVarWithDestructor(Var, Record); 14350 14351 // Enter a new evaluation context to insulate the copy 14352 // full-expression. 14353 EnterExpressionEvaluationContext scope( 14354 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14355 14356 // According to the blocks spec, the capture of a variable from 14357 // the stack requires a const copy constructor. This is not true 14358 // of the copy/move done to move a __block variable to the heap. 14359 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14360 DeclRefType.withConst(), 14361 VK_LValue, Loc); 14362 14363 ExprResult Result 14364 = S.PerformCopyInitialization( 14365 InitializedEntity::InitializeBlock(Var->getLocation(), 14366 CaptureType, false), 14367 Loc, DeclRef); 14368 14369 // Build a full-expression copy expression if initialization 14370 // succeeded and used a non-trivial constructor. Recover from 14371 // errors by pretending that the copy isn't necessary. 14372 if (!Result.isInvalid() && 14373 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14374 ->isTrivial()) { 14375 Result = S.MaybeCreateExprWithCleanups(Result); 14376 CopyExpr = Result.get(); 14377 } 14378 } 14379 } 14380 } 14381 14382 // Actually capture the variable. 14383 if (BuildAndDiagnose) 14384 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14385 SourceLocation(), CaptureType, CopyExpr); 14386 14387 return true; 14388 14389 } 14390 14391 14392 /// \brief Capture the given variable in the captured region. 14393 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14394 VarDecl *Var, 14395 SourceLocation Loc, 14396 const bool BuildAndDiagnose, 14397 QualType &CaptureType, 14398 QualType &DeclRefType, 14399 const bool RefersToCapturedVariable, 14400 Sema &S) { 14401 // By default, capture variables by reference. 14402 bool ByRef = true; 14403 // Using an LValue reference type is consistent with Lambdas (see below). 14404 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14405 if (S.IsOpenMPCapturedDecl(Var)) { 14406 bool HasConst = DeclRefType.isConstQualified(); 14407 DeclRefType = DeclRefType.getUnqualifiedType(); 14408 // Don't lose diagnostics about assignments to const. 14409 if (HasConst) 14410 DeclRefType.addConst(); 14411 } 14412 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14413 } 14414 14415 if (ByRef) 14416 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14417 else 14418 CaptureType = DeclRefType; 14419 14420 Expr *CopyExpr = nullptr; 14421 if (BuildAndDiagnose) { 14422 // The current implementation assumes that all variables are captured 14423 // by references. Since there is no capture by copy, no expression 14424 // evaluation will be needed. 14425 RecordDecl *RD = RSI->TheRecordDecl; 14426 14427 FieldDecl *Field 14428 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14429 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14430 nullptr, false, ICIS_NoInit); 14431 Field->setImplicit(true); 14432 Field->setAccess(AS_private); 14433 RD->addDecl(Field); 14434 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14435 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14436 14437 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14438 DeclRefType, VK_LValue, Loc); 14439 Var->setReferenced(true); 14440 Var->markUsed(S.Context); 14441 } 14442 14443 // Actually capture the variable. 14444 if (BuildAndDiagnose) 14445 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14446 SourceLocation(), CaptureType, CopyExpr); 14447 14448 14449 return true; 14450 } 14451 14452 /// \brief Create a field within the lambda class for the variable 14453 /// being captured. 14454 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14455 QualType FieldType, QualType DeclRefType, 14456 SourceLocation Loc, 14457 bool RefersToCapturedVariable) { 14458 CXXRecordDecl *Lambda = LSI->Lambda; 14459 14460 // Build the non-static data member. 14461 FieldDecl *Field 14462 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14463 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14464 nullptr, false, ICIS_NoInit); 14465 Field->setImplicit(true); 14466 Field->setAccess(AS_private); 14467 Lambda->addDecl(Field); 14468 } 14469 14470 /// \brief Capture the given variable in the lambda. 14471 static bool captureInLambda(LambdaScopeInfo *LSI, 14472 VarDecl *Var, 14473 SourceLocation Loc, 14474 const bool BuildAndDiagnose, 14475 QualType &CaptureType, 14476 QualType &DeclRefType, 14477 const bool RefersToCapturedVariable, 14478 const Sema::TryCaptureKind Kind, 14479 SourceLocation EllipsisLoc, 14480 const bool IsTopScope, 14481 Sema &S) { 14482 14483 // Determine whether we are capturing by reference or by value. 14484 bool ByRef = false; 14485 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14486 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14487 } else { 14488 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14489 } 14490 14491 // Compute the type of the field that will capture this variable. 14492 if (ByRef) { 14493 // C++11 [expr.prim.lambda]p15: 14494 // An entity is captured by reference if it is implicitly or 14495 // explicitly captured but not captured by copy. It is 14496 // unspecified whether additional unnamed non-static data 14497 // members are declared in the closure type for entities 14498 // captured by reference. 14499 // 14500 // FIXME: It is not clear whether we want to build an lvalue reference 14501 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14502 // to do the former, while EDG does the latter. Core issue 1249 will 14503 // clarify, but for now we follow GCC because it's a more permissive and 14504 // easily defensible position. 14505 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14506 } else { 14507 // C++11 [expr.prim.lambda]p14: 14508 // For each entity captured by copy, an unnamed non-static 14509 // data member is declared in the closure type. The 14510 // declaration order of these members is unspecified. The type 14511 // of such a data member is the type of the corresponding 14512 // captured entity if the entity is not a reference to an 14513 // object, or the referenced type otherwise. [Note: If the 14514 // captured entity is a reference to a function, the 14515 // corresponding data member is also a reference to a 14516 // function. - end note ] 14517 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14518 if (!RefType->getPointeeType()->isFunctionType()) 14519 CaptureType = RefType->getPointeeType(); 14520 } 14521 14522 // Forbid the lambda copy-capture of autoreleasing variables. 14523 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14524 if (BuildAndDiagnose) { 14525 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14526 S.Diag(Var->getLocation(), diag::note_previous_decl) 14527 << Var->getDeclName(); 14528 } 14529 return false; 14530 } 14531 14532 // Make sure that by-copy captures are of a complete and non-abstract type. 14533 if (BuildAndDiagnose) { 14534 if (!CaptureType->isDependentType() && 14535 S.RequireCompleteType(Loc, CaptureType, 14536 diag::err_capture_of_incomplete_type, 14537 Var->getDeclName())) 14538 return false; 14539 14540 if (S.RequireNonAbstractType(Loc, CaptureType, 14541 diag::err_capture_of_abstract_type)) 14542 return false; 14543 } 14544 } 14545 14546 // Capture this variable in the lambda. 14547 if (BuildAndDiagnose) 14548 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14549 RefersToCapturedVariable); 14550 14551 // Compute the type of a reference to this captured variable. 14552 if (ByRef) 14553 DeclRefType = CaptureType.getNonReferenceType(); 14554 else { 14555 // C++ [expr.prim.lambda]p5: 14556 // The closure type for a lambda-expression has a public inline 14557 // function call operator [...]. This function call operator is 14558 // declared const (9.3.1) if and only if the lambda-expression's 14559 // parameter-declaration-clause is not followed by mutable. 14560 DeclRefType = CaptureType.getNonReferenceType(); 14561 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14562 DeclRefType.addConst(); 14563 } 14564 14565 // Add the capture. 14566 if (BuildAndDiagnose) 14567 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14568 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14569 14570 return true; 14571 } 14572 14573 bool Sema::tryCaptureVariable( 14574 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14575 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14576 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14577 // An init-capture is notionally from the context surrounding its 14578 // declaration, but its parent DC is the lambda class. 14579 DeclContext *VarDC = Var->getDeclContext(); 14580 if (Var->isInitCapture()) 14581 VarDC = VarDC->getParent(); 14582 14583 DeclContext *DC = CurContext; 14584 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14585 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14586 // We need to sync up the Declaration Context with the 14587 // FunctionScopeIndexToStopAt 14588 if (FunctionScopeIndexToStopAt) { 14589 unsigned FSIndex = FunctionScopes.size() - 1; 14590 while (FSIndex != MaxFunctionScopesIndex) { 14591 DC = getLambdaAwareParentOfDeclContext(DC); 14592 --FSIndex; 14593 } 14594 } 14595 14596 14597 // If the variable is declared in the current context, there is no need to 14598 // capture it. 14599 if (VarDC == DC) return true; 14600 14601 // Capture global variables if it is required to use private copy of this 14602 // variable. 14603 bool IsGlobal = !Var->hasLocalStorage(); 14604 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14605 return true; 14606 Var = Var->getCanonicalDecl(); 14607 14608 // Walk up the stack to determine whether we can capture the variable, 14609 // performing the "simple" checks that don't depend on type. We stop when 14610 // we've either hit the declared scope of the variable or find an existing 14611 // capture of that variable. We start from the innermost capturing-entity 14612 // (the DC) and ensure that all intervening capturing-entities 14613 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14614 // declcontext can either capture the variable or have already captured 14615 // the variable. 14616 CaptureType = Var->getType(); 14617 DeclRefType = CaptureType.getNonReferenceType(); 14618 bool Nested = false; 14619 bool Explicit = (Kind != TryCapture_Implicit); 14620 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14621 do { 14622 // Only block literals, captured statements, and lambda expressions can 14623 // capture; other scopes don't work. 14624 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14625 ExprLoc, 14626 BuildAndDiagnose, 14627 *this); 14628 // We need to check for the parent *first* because, if we *have* 14629 // private-captured a global variable, we need to recursively capture it in 14630 // intermediate blocks, lambdas, etc. 14631 if (!ParentDC) { 14632 if (IsGlobal) { 14633 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14634 break; 14635 } 14636 return true; 14637 } 14638 14639 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14640 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14641 14642 14643 // Check whether we've already captured it. 14644 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14645 DeclRefType)) { 14646 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14647 break; 14648 } 14649 // If we are instantiating a generic lambda call operator body, 14650 // we do not want to capture new variables. What was captured 14651 // during either a lambdas transformation or initial parsing 14652 // should be used. 14653 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14654 if (BuildAndDiagnose) { 14655 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14656 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14657 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14658 Diag(Var->getLocation(), diag::note_previous_decl) 14659 << Var->getDeclName(); 14660 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14661 } else 14662 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14663 } 14664 return true; 14665 } 14666 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14667 // certain types of variables (unnamed, variably modified types etc.) 14668 // so check for eligibility. 14669 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14670 return true; 14671 14672 // Try to capture variable-length arrays types. 14673 if (Var->getType()->isVariablyModifiedType()) { 14674 // We're going to walk down into the type and look for VLA 14675 // expressions. 14676 QualType QTy = Var->getType(); 14677 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14678 QTy = PVD->getOriginalType(); 14679 captureVariablyModifiedType(Context, QTy, CSI); 14680 } 14681 14682 if (getLangOpts().OpenMP) { 14683 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14684 // OpenMP private variables should not be captured in outer scope, so 14685 // just break here. Similarly, global variables that are captured in a 14686 // target region should not be captured outside the scope of the region. 14687 if (RSI->CapRegionKind == CR_OpenMP) { 14688 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 14689 auto IsTargetCap = !IsOpenMPPrivateDecl && 14690 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14691 // When we detect target captures we are looking from inside the 14692 // target region, therefore we need to propagate the capture from the 14693 // enclosing region. Therefore, the capture is not initially nested. 14694 if (IsTargetCap) 14695 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 14696 14697 if (IsTargetCap || IsOpenMPPrivateDecl) { 14698 Nested = !IsTargetCap; 14699 DeclRefType = DeclRefType.getUnqualifiedType(); 14700 CaptureType = Context.getLValueReferenceType(DeclRefType); 14701 break; 14702 } 14703 } 14704 } 14705 } 14706 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14707 // No capture-default, and this is not an explicit capture 14708 // so cannot capture this variable. 14709 if (BuildAndDiagnose) { 14710 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14711 Diag(Var->getLocation(), diag::note_previous_decl) 14712 << Var->getDeclName(); 14713 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14714 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14715 diag::note_lambda_decl); 14716 // FIXME: If we error out because an outer lambda can not implicitly 14717 // capture a variable that an inner lambda explicitly captures, we 14718 // should have the inner lambda do the explicit capture - because 14719 // it makes for cleaner diagnostics later. This would purely be done 14720 // so that the diagnostic does not misleadingly claim that a variable 14721 // can not be captured by a lambda implicitly even though it is captured 14722 // explicitly. Suggestion: 14723 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14724 // at the function head 14725 // - cache the StartingDeclContext - this must be a lambda 14726 // - captureInLambda in the innermost lambda the variable. 14727 } 14728 return true; 14729 } 14730 14731 FunctionScopesIndex--; 14732 DC = ParentDC; 14733 Explicit = false; 14734 } while (!VarDC->Equals(DC)); 14735 14736 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14737 // computing the type of the capture at each step, checking type-specific 14738 // requirements, and adding captures if requested. 14739 // If the variable had already been captured previously, we start capturing 14740 // at the lambda nested within that one. 14741 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14742 ++I) { 14743 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14744 14745 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14746 if (!captureInBlock(BSI, Var, ExprLoc, 14747 BuildAndDiagnose, CaptureType, 14748 DeclRefType, Nested, *this)) 14749 return true; 14750 Nested = true; 14751 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14752 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14753 BuildAndDiagnose, CaptureType, 14754 DeclRefType, Nested, *this)) 14755 return true; 14756 Nested = true; 14757 } else { 14758 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14759 if (!captureInLambda(LSI, Var, ExprLoc, 14760 BuildAndDiagnose, CaptureType, 14761 DeclRefType, Nested, Kind, EllipsisLoc, 14762 /*IsTopScope*/I == N - 1, *this)) 14763 return true; 14764 Nested = true; 14765 } 14766 } 14767 return false; 14768 } 14769 14770 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14771 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14772 QualType CaptureType; 14773 QualType DeclRefType; 14774 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14775 /*BuildAndDiagnose=*/true, CaptureType, 14776 DeclRefType, nullptr); 14777 } 14778 14779 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14780 QualType CaptureType; 14781 QualType DeclRefType; 14782 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14783 /*BuildAndDiagnose=*/false, CaptureType, 14784 DeclRefType, nullptr); 14785 } 14786 14787 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14788 QualType CaptureType; 14789 QualType DeclRefType; 14790 14791 // Determine whether we can capture this variable. 14792 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14793 /*BuildAndDiagnose=*/false, CaptureType, 14794 DeclRefType, nullptr)) 14795 return QualType(); 14796 14797 return DeclRefType; 14798 } 14799 14800 14801 14802 // If either the type of the variable or the initializer is dependent, 14803 // return false. Otherwise, determine whether the variable is a constant 14804 // expression. Use this if you need to know if a variable that might or 14805 // might not be dependent is truly a constant expression. 14806 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14807 ASTContext &Context) { 14808 14809 if (Var->getType()->isDependentType()) 14810 return false; 14811 const VarDecl *DefVD = nullptr; 14812 Var->getAnyInitializer(DefVD); 14813 if (!DefVD) 14814 return false; 14815 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14816 Expr *Init = cast<Expr>(Eval->Value); 14817 if (Init->isValueDependent()) 14818 return false; 14819 return IsVariableAConstantExpression(Var, Context); 14820 } 14821 14822 14823 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14824 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14825 // an object that satisfies the requirements for appearing in a 14826 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14827 // is immediately applied." This function handles the lvalue-to-rvalue 14828 // conversion part. 14829 MaybeODRUseExprs.erase(E->IgnoreParens()); 14830 14831 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14832 // to a variable that is a constant expression, and if so, identify it as 14833 // a reference to a variable that does not involve an odr-use of that 14834 // variable. 14835 if (LambdaScopeInfo *LSI = getCurLambda()) { 14836 Expr *SansParensExpr = E->IgnoreParens(); 14837 VarDecl *Var = nullptr; 14838 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14839 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14840 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14841 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14842 14843 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14844 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14845 } 14846 } 14847 14848 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14849 Res = CorrectDelayedTyposInExpr(Res); 14850 14851 if (!Res.isUsable()) 14852 return Res; 14853 14854 // If a constant-expression is a reference to a variable where we delay 14855 // deciding whether it is an odr-use, just assume we will apply the 14856 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14857 // (a non-type template argument), we have special handling anyway. 14858 UpdateMarkingForLValueToRValue(Res.get()); 14859 return Res; 14860 } 14861 14862 void Sema::CleanupVarDeclMarking() { 14863 for (Expr *E : MaybeODRUseExprs) { 14864 VarDecl *Var; 14865 SourceLocation Loc; 14866 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14867 Var = cast<VarDecl>(DRE->getDecl()); 14868 Loc = DRE->getLocation(); 14869 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14870 Var = cast<VarDecl>(ME->getMemberDecl()); 14871 Loc = ME->getMemberLoc(); 14872 } else { 14873 llvm_unreachable("Unexpected expression"); 14874 } 14875 14876 MarkVarDeclODRUsed(Var, Loc, *this, 14877 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14878 } 14879 14880 MaybeODRUseExprs.clear(); 14881 } 14882 14883 14884 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14885 VarDecl *Var, Expr *E) { 14886 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14887 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14888 Var->setReferenced(); 14889 14890 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14891 14892 bool OdrUseContext = isOdrUseContext(SemaRef); 14893 bool UsableInConstantExpr = 14894 Var->isUsableInConstantExpressions(SemaRef.Context); 14895 bool NeedDefinition = 14896 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 14897 14898 VarTemplateSpecializationDecl *VarSpec = 14899 dyn_cast<VarTemplateSpecializationDecl>(Var); 14900 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14901 "Can't instantiate a partial template specialization."); 14902 14903 // If this might be a member specialization of a static data member, check 14904 // the specialization is visible. We already did the checks for variable 14905 // template specializations when we created them. 14906 if (NeedDefinition && TSK != TSK_Undeclared && 14907 !isa<VarTemplateSpecializationDecl>(Var)) 14908 SemaRef.checkSpecializationVisibility(Loc, Var); 14909 14910 // Perform implicit instantiation of static data members, static data member 14911 // templates of class templates, and variable template specializations. Delay 14912 // instantiations of variable templates, except for those that could be used 14913 // in a constant expression. 14914 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14915 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 14916 // instantiation declaration if a variable is usable in a constant 14917 // expression (among other cases). 14918 bool TryInstantiating = 14919 TSK == TSK_ImplicitInstantiation || 14920 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 14921 14922 if (TryInstantiating) { 14923 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14924 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14925 if (FirstInstantiation) { 14926 PointOfInstantiation = Loc; 14927 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14928 } 14929 14930 bool InstantiationDependent = false; 14931 bool IsNonDependent = 14932 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14933 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14934 : true; 14935 14936 // Do not instantiate specializations that are still type-dependent. 14937 if (IsNonDependent) { 14938 if (UsableInConstantExpr) { 14939 // Do not defer instantiations of variables that could be used in a 14940 // constant expression. 14941 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14942 } else if (FirstInstantiation || 14943 isa<VarTemplateSpecializationDecl>(Var)) { 14944 // FIXME: For a specialization of a variable template, we don't 14945 // distinguish between "declaration and type implicitly instantiated" 14946 // and "implicit instantiation of definition requested", so we have 14947 // no direct way to avoid enqueueing the pending instantiation 14948 // multiple times. 14949 SemaRef.PendingInstantiations 14950 .push_back(std::make_pair(Var, PointOfInstantiation)); 14951 } 14952 } 14953 } 14954 } 14955 14956 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14957 // the requirements for appearing in a constant expression (5.19) and, if 14958 // it is an object, the lvalue-to-rvalue conversion (4.1) 14959 // is immediately applied." We check the first part here, and 14960 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14961 // Note that we use the C++11 definition everywhere because nothing in 14962 // C++03 depends on whether we get the C++03 version correct. The second 14963 // part does not apply to references, since they are not objects. 14964 if (OdrUseContext && E && 14965 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14966 // A reference initialized by a constant expression can never be 14967 // odr-used, so simply ignore it. 14968 if (!Var->getType()->isReferenceType() || 14969 (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var))) 14970 SemaRef.MaybeODRUseExprs.insert(E); 14971 } else if (OdrUseContext) { 14972 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14973 /*MaxFunctionScopeIndex ptr*/ nullptr); 14974 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14975 // If this is a dependent context, we don't need to mark variables as 14976 // odr-used, but we may still need to track them for lambda capture. 14977 // FIXME: Do we also need to do this inside dependent typeid expressions 14978 // (which are modeled as unevaluated at this point)? 14979 const bool RefersToEnclosingScope = 14980 (SemaRef.CurContext != Var->getDeclContext() && 14981 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14982 if (RefersToEnclosingScope) { 14983 LambdaScopeInfo *const LSI = 14984 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14985 if (LSI && (!LSI->CallOperator || 14986 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 14987 // If a variable could potentially be odr-used, defer marking it so 14988 // until we finish analyzing the full expression for any 14989 // lvalue-to-rvalue 14990 // or discarded value conversions that would obviate odr-use. 14991 // Add it to the list of potential captures that will be analyzed 14992 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14993 // unless the variable is a reference that was initialized by a constant 14994 // expression (this will never need to be captured or odr-used). 14995 assert(E && "Capture variable should be used in an expression."); 14996 if (!Var->getType()->isReferenceType() || 14997 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14998 LSI->addPotentialCapture(E->IgnoreParens()); 14999 } 15000 } 15001 } 15002 } 15003 15004 /// \brief Mark a variable referenced, and check whether it is odr-used 15005 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15006 /// used directly for normal expressions referring to VarDecl. 15007 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15008 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15009 } 15010 15011 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15012 Decl *D, Expr *E, bool MightBeOdrUse) { 15013 if (SemaRef.isInOpenMPDeclareTargetContext()) 15014 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15015 15016 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15017 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15018 return; 15019 } 15020 15021 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15022 15023 // If this is a call to a method via a cast, also mark the method in the 15024 // derived class used in case codegen can devirtualize the call. 15025 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15026 if (!ME) 15027 return; 15028 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15029 if (!MD) 15030 return; 15031 // Only attempt to devirtualize if this is truly a virtual call. 15032 bool IsVirtualCall = MD->isVirtual() && 15033 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15034 if (!IsVirtualCall) 15035 return; 15036 15037 // If it's possible to devirtualize the call, mark the called function 15038 // referenced. 15039 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15040 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15041 if (DM) 15042 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15043 } 15044 15045 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 15046 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15047 // TODO: update this with DR# once a defect report is filed. 15048 // C++11 defect. The address of a pure member should not be an ODR use, even 15049 // if it's a qualified reference. 15050 bool OdrUse = true; 15051 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15052 if (Method->isVirtual() && 15053 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15054 OdrUse = false; 15055 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15056 } 15057 15058 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 15059 void Sema::MarkMemberReferenced(MemberExpr *E) { 15060 // C++11 [basic.def.odr]p2: 15061 // A non-overloaded function whose name appears as a potentially-evaluated 15062 // expression or a member of a set of candidate functions, if selected by 15063 // overload resolution when referred to from a potentially-evaluated 15064 // expression, is odr-used, unless it is a pure virtual function and its 15065 // name is not explicitly qualified. 15066 bool MightBeOdrUse = true; 15067 if (E->performsVirtualDispatch(getLangOpts())) { 15068 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15069 if (Method->isPure()) 15070 MightBeOdrUse = false; 15071 } 15072 SourceLocation Loc = E->getMemberLoc().isValid() ? 15073 E->getMemberLoc() : E->getLocStart(); 15074 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15075 } 15076 15077 /// \brief Perform marking for a reference to an arbitrary declaration. It 15078 /// marks the declaration referenced, and performs odr-use checking for 15079 /// functions and variables. This method should not be used when building a 15080 /// normal expression which refers to a variable. 15081 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15082 bool MightBeOdrUse) { 15083 if (MightBeOdrUse) { 15084 if (auto *VD = dyn_cast<VarDecl>(D)) { 15085 MarkVariableReferenced(Loc, VD); 15086 return; 15087 } 15088 } 15089 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15090 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15091 return; 15092 } 15093 D->setReferenced(); 15094 } 15095 15096 namespace { 15097 // Mark all of the declarations used by a type as referenced. 15098 // FIXME: Not fully implemented yet! We need to have a better understanding 15099 // of when we're entering a context we should not recurse into. 15100 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15101 // TreeTransforms rebuilding the type in a new context. Rather than 15102 // duplicating the TreeTransform logic, we should consider reusing it here. 15103 // Currently that causes problems when rebuilding LambdaExprs. 15104 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15105 Sema &S; 15106 SourceLocation Loc; 15107 15108 public: 15109 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15110 15111 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15112 15113 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15114 }; 15115 } 15116 15117 bool MarkReferencedDecls::TraverseTemplateArgument( 15118 const TemplateArgument &Arg) { 15119 { 15120 // A non-type template argument is a constant-evaluated context. 15121 EnterExpressionEvaluationContext Evaluated( 15122 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15123 if (Arg.getKind() == TemplateArgument::Declaration) { 15124 if (Decl *D = Arg.getAsDecl()) 15125 S.MarkAnyDeclReferenced(Loc, D, true); 15126 } else if (Arg.getKind() == TemplateArgument::Expression) { 15127 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15128 } 15129 } 15130 15131 return Inherited::TraverseTemplateArgument(Arg); 15132 } 15133 15134 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15135 MarkReferencedDecls Marker(*this, Loc); 15136 Marker.TraverseType(T); 15137 } 15138 15139 namespace { 15140 /// \brief Helper class that marks all of the declarations referenced by 15141 /// potentially-evaluated subexpressions as "referenced". 15142 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15143 Sema &S; 15144 bool SkipLocalVariables; 15145 15146 public: 15147 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15148 15149 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15150 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15151 15152 void VisitDeclRefExpr(DeclRefExpr *E) { 15153 // If we were asked not to visit local variables, don't. 15154 if (SkipLocalVariables) { 15155 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15156 if (VD->hasLocalStorage()) 15157 return; 15158 } 15159 15160 S.MarkDeclRefReferenced(E); 15161 } 15162 15163 void VisitMemberExpr(MemberExpr *E) { 15164 S.MarkMemberReferenced(E); 15165 Inherited::VisitMemberExpr(E); 15166 } 15167 15168 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15169 S.MarkFunctionReferenced(E->getLocStart(), 15170 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15171 Visit(E->getSubExpr()); 15172 } 15173 15174 void VisitCXXNewExpr(CXXNewExpr *E) { 15175 if (E->getOperatorNew()) 15176 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15177 if (E->getOperatorDelete()) 15178 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15179 Inherited::VisitCXXNewExpr(E); 15180 } 15181 15182 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15183 if (E->getOperatorDelete()) 15184 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15185 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15186 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15187 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15188 S.MarkFunctionReferenced(E->getLocStart(), 15189 S.LookupDestructor(Record)); 15190 } 15191 15192 Inherited::VisitCXXDeleteExpr(E); 15193 } 15194 15195 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15196 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15197 Inherited::VisitCXXConstructExpr(E); 15198 } 15199 15200 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15201 Visit(E->getExpr()); 15202 } 15203 15204 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15205 Inherited::VisitImplicitCastExpr(E); 15206 15207 if (E->getCastKind() == CK_LValueToRValue) 15208 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15209 } 15210 }; 15211 } 15212 15213 /// \brief Mark any declarations that appear within this expression or any 15214 /// potentially-evaluated subexpressions as "referenced". 15215 /// 15216 /// \param SkipLocalVariables If true, don't mark local variables as 15217 /// 'referenced'. 15218 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15219 bool SkipLocalVariables) { 15220 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15221 } 15222 15223 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15224 /// of the program being compiled. 15225 /// 15226 /// This routine emits the given diagnostic when the code currently being 15227 /// type-checked is "potentially evaluated", meaning that there is a 15228 /// possibility that the code will actually be executable. Code in sizeof() 15229 /// expressions, code used only during overload resolution, etc., are not 15230 /// potentially evaluated. This routine will suppress such diagnostics or, 15231 /// in the absolutely nutty case of potentially potentially evaluated 15232 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15233 /// later. 15234 /// 15235 /// This routine should be used for all diagnostics that describe the run-time 15236 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15237 /// Failure to do so will likely result in spurious diagnostics or failures 15238 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15239 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15240 const PartialDiagnostic &PD) { 15241 switch (ExprEvalContexts.back().Context) { 15242 case ExpressionEvaluationContext::Unevaluated: 15243 case ExpressionEvaluationContext::UnevaluatedList: 15244 case ExpressionEvaluationContext::UnevaluatedAbstract: 15245 case ExpressionEvaluationContext::DiscardedStatement: 15246 // The argument will never be evaluated, so don't complain. 15247 break; 15248 15249 case ExpressionEvaluationContext::ConstantEvaluated: 15250 // Relevant diagnostics should be produced by constant evaluation. 15251 break; 15252 15253 case ExpressionEvaluationContext::PotentiallyEvaluated: 15254 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15255 if (Statement && getCurFunctionOrMethodDecl()) { 15256 FunctionScopes.back()->PossiblyUnreachableDiags. 15257 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15258 return true; 15259 } 15260 15261 // The initializer of a constexpr variable or of the first declaration of a 15262 // static data member is not syntactically a constant evaluated constant, 15263 // but nonetheless is always required to be a constant expression, so we 15264 // can skip diagnosing. 15265 // FIXME: Using the mangling context here is a hack. 15266 if (auto *VD = dyn_cast_or_null<VarDecl>( 15267 ExprEvalContexts.back().ManglingContextDecl)) { 15268 if (VD->isConstexpr() || 15269 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15270 break; 15271 // FIXME: For any other kind of variable, we should build a CFG for its 15272 // initializer and check whether the context in question is reachable. 15273 } 15274 15275 Diag(Loc, PD); 15276 return true; 15277 } 15278 15279 return false; 15280 } 15281 15282 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15283 CallExpr *CE, FunctionDecl *FD) { 15284 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15285 return false; 15286 15287 // If we're inside a decltype's expression, don't check for a valid return 15288 // type or construct temporaries until we know whether this is the last call. 15289 if (ExprEvalContexts.back().IsDecltype) { 15290 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15291 return false; 15292 } 15293 15294 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15295 FunctionDecl *FD; 15296 CallExpr *CE; 15297 15298 public: 15299 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15300 : FD(FD), CE(CE) { } 15301 15302 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15303 if (!FD) { 15304 S.Diag(Loc, diag::err_call_incomplete_return) 15305 << T << CE->getSourceRange(); 15306 return; 15307 } 15308 15309 S.Diag(Loc, diag::err_call_function_incomplete_return) 15310 << CE->getSourceRange() << FD->getDeclName() << T; 15311 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15312 << FD->getDeclName(); 15313 } 15314 } Diagnoser(FD, CE); 15315 15316 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15317 return true; 15318 15319 return false; 15320 } 15321 15322 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15323 // will prevent this condition from triggering, which is what we want. 15324 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15325 SourceLocation Loc; 15326 15327 unsigned diagnostic = diag::warn_condition_is_assignment; 15328 bool IsOrAssign = false; 15329 15330 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15331 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15332 return; 15333 15334 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15335 15336 // Greylist some idioms by putting them into a warning subcategory. 15337 if (ObjCMessageExpr *ME 15338 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15339 Selector Sel = ME->getSelector(); 15340 15341 // self = [<foo> init...] 15342 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15343 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15344 15345 // <foo> = [<bar> nextObject] 15346 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15347 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15348 } 15349 15350 Loc = Op->getOperatorLoc(); 15351 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15352 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15353 return; 15354 15355 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15356 Loc = Op->getOperatorLoc(); 15357 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15358 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15359 else { 15360 // Not an assignment. 15361 return; 15362 } 15363 15364 Diag(Loc, diagnostic) << E->getSourceRange(); 15365 15366 SourceLocation Open = E->getLocStart(); 15367 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15368 Diag(Loc, diag::note_condition_assign_silence) 15369 << FixItHint::CreateInsertion(Open, "(") 15370 << FixItHint::CreateInsertion(Close, ")"); 15371 15372 if (IsOrAssign) 15373 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15374 << FixItHint::CreateReplacement(Loc, "!="); 15375 else 15376 Diag(Loc, diag::note_condition_assign_to_comparison) 15377 << FixItHint::CreateReplacement(Loc, "=="); 15378 } 15379 15380 /// \brief Redundant parentheses over an equality comparison can indicate 15381 /// that the user intended an assignment used as condition. 15382 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15383 // Don't warn if the parens came from a macro. 15384 SourceLocation parenLoc = ParenE->getLocStart(); 15385 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15386 return; 15387 // Don't warn for dependent expressions. 15388 if (ParenE->isTypeDependent()) 15389 return; 15390 15391 Expr *E = ParenE->IgnoreParens(); 15392 15393 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15394 if (opE->getOpcode() == BO_EQ && 15395 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15396 == Expr::MLV_Valid) { 15397 SourceLocation Loc = opE->getOperatorLoc(); 15398 15399 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15400 SourceRange ParenERange = ParenE->getSourceRange(); 15401 Diag(Loc, diag::note_equality_comparison_silence) 15402 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15403 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15404 Diag(Loc, diag::note_equality_comparison_to_assign) 15405 << FixItHint::CreateReplacement(Loc, "="); 15406 } 15407 } 15408 15409 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15410 bool IsConstexpr) { 15411 DiagnoseAssignmentAsCondition(E); 15412 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15413 DiagnoseEqualityWithExtraParens(parenE); 15414 15415 ExprResult result = CheckPlaceholderExpr(E); 15416 if (result.isInvalid()) return ExprError(); 15417 E = result.get(); 15418 15419 if (!E->isTypeDependent()) { 15420 if (getLangOpts().CPlusPlus) 15421 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15422 15423 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15424 if (ERes.isInvalid()) 15425 return ExprError(); 15426 E = ERes.get(); 15427 15428 QualType T = E->getType(); 15429 if (!T->isScalarType()) { // C99 6.8.4.1p1 15430 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15431 << T << E->getSourceRange(); 15432 return ExprError(); 15433 } 15434 CheckBoolLikeConversion(E, Loc); 15435 } 15436 15437 return E; 15438 } 15439 15440 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15441 Expr *SubExpr, ConditionKind CK) { 15442 // Empty conditions are valid in for-statements. 15443 if (!SubExpr) 15444 return ConditionResult(); 15445 15446 ExprResult Cond; 15447 switch (CK) { 15448 case ConditionKind::Boolean: 15449 Cond = CheckBooleanCondition(Loc, SubExpr); 15450 break; 15451 15452 case ConditionKind::ConstexprIf: 15453 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15454 break; 15455 15456 case ConditionKind::Switch: 15457 Cond = CheckSwitchCondition(Loc, SubExpr); 15458 break; 15459 } 15460 if (Cond.isInvalid()) 15461 return ConditionError(); 15462 15463 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15464 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15465 if (!FullExpr.get()) 15466 return ConditionError(); 15467 15468 return ConditionResult(*this, nullptr, FullExpr, 15469 CK == ConditionKind::ConstexprIf); 15470 } 15471 15472 namespace { 15473 /// A visitor for rebuilding a call to an __unknown_any expression 15474 /// to have an appropriate type. 15475 struct RebuildUnknownAnyFunction 15476 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15477 15478 Sema &S; 15479 15480 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15481 15482 ExprResult VisitStmt(Stmt *S) { 15483 llvm_unreachable("unexpected statement!"); 15484 } 15485 15486 ExprResult VisitExpr(Expr *E) { 15487 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15488 << E->getSourceRange(); 15489 return ExprError(); 15490 } 15491 15492 /// Rebuild an expression which simply semantically wraps another 15493 /// expression which it shares the type and value kind of. 15494 template <class T> ExprResult rebuildSugarExpr(T *E) { 15495 ExprResult SubResult = Visit(E->getSubExpr()); 15496 if (SubResult.isInvalid()) return ExprError(); 15497 15498 Expr *SubExpr = SubResult.get(); 15499 E->setSubExpr(SubExpr); 15500 E->setType(SubExpr->getType()); 15501 E->setValueKind(SubExpr->getValueKind()); 15502 assert(E->getObjectKind() == OK_Ordinary); 15503 return E; 15504 } 15505 15506 ExprResult VisitParenExpr(ParenExpr *E) { 15507 return rebuildSugarExpr(E); 15508 } 15509 15510 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15511 return rebuildSugarExpr(E); 15512 } 15513 15514 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15515 ExprResult SubResult = Visit(E->getSubExpr()); 15516 if (SubResult.isInvalid()) return ExprError(); 15517 15518 Expr *SubExpr = SubResult.get(); 15519 E->setSubExpr(SubExpr); 15520 E->setType(S.Context.getPointerType(SubExpr->getType())); 15521 assert(E->getValueKind() == VK_RValue); 15522 assert(E->getObjectKind() == OK_Ordinary); 15523 return E; 15524 } 15525 15526 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15527 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15528 15529 E->setType(VD->getType()); 15530 15531 assert(E->getValueKind() == VK_RValue); 15532 if (S.getLangOpts().CPlusPlus && 15533 !(isa<CXXMethodDecl>(VD) && 15534 cast<CXXMethodDecl>(VD)->isInstance())) 15535 E->setValueKind(VK_LValue); 15536 15537 return E; 15538 } 15539 15540 ExprResult VisitMemberExpr(MemberExpr *E) { 15541 return resolveDecl(E, E->getMemberDecl()); 15542 } 15543 15544 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15545 return resolveDecl(E, E->getDecl()); 15546 } 15547 }; 15548 } 15549 15550 /// Given a function expression of unknown-any type, try to rebuild it 15551 /// to have a function type. 15552 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15553 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15554 if (Result.isInvalid()) return ExprError(); 15555 return S.DefaultFunctionArrayConversion(Result.get()); 15556 } 15557 15558 namespace { 15559 /// A visitor for rebuilding an expression of type __unknown_anytype 15560 /// into one which resolves the type directly on the referring 15561 /// expression. Strict preservation of the original source 15562 /// structure is not a goal. 15563 struct RebuildUnknownAnyExpr 15564 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15565 15566 Sema &S; 15567 15568 /// The current destination type. 15569 QualType DestType; 15570 15571 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15572 : S(S), DestType(CastType) {} 15573 15574 ExprResult VisitStmt(Stmt *S) { 15575 llvm_unreachable("unexpected statement!"); 15576 } 15577 15578 ExprResult VisitExpr(Expr *E) { 15579 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15580 << E->getSourceRange(); 15581 return ExprError(); 15582 } 15583 15584 ExprResult VisitCallExpr(CallExpr *E); 15585 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15586 15587 /// Rebuild an expression which simply semantically wraps another 15588 /// expression which it shares the type and value kind of. 15589 template <class T> ExprResult rebuildSugarExpr(T *E) { 15590 ExprResult SubResult = Visit(E->getSubExpr()); 15591 if (SubResult.isInvalid()) return ExprError(); 15592 Expr *SubExpr = SubResult.get(); 15593 E->setSubExpr(SubExpr); 15594 E->setType(SubExpr->getType()); 15595 E->setValueKind(SubExpr->getValueKind()); 15596 assert(E->getObjectKind() == OK_Ordinary); 15597 return E; 15598 } 15599 15600 ExprResult VisitParenExpr(ParenExpr *E) { 15601 return rebuildSugarExpr(E); 15602 } 15603 15604 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15605 return rebuildSugarExpr(E); 15606 } 15607 15608 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15609 const PointerType *Ptr = DestType->getAs<PointerType>(); 15610 if (!Ptr) { 15611 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15612 << E->getSourceRange(); 15613 return ExprError(); 15614 } 15615 15616 if (isa<CallExpr>(E->getSubExpr())) { 15617 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15618 << E->getSourceRange(); 15619 return ExprError(); 15620 } 15621 15622 assert(E->getValueKind() == VK_RValue); 15623 assert(E->getObjectKind() == OK_Ordinary); 15624 E->setType(DestType); 15625 15626 // Build the sub-expression as if it were an object of the pointee type. 15627 DestType = Ptr->getPointeeType(); 15628 ExprResult SubResult = Visit(E->getSubExpr()); 15629 if (SubResult.isInvalid()) return ExprError(); 15630 E->setSubExpr(SubResult.get()); 15631 return E; 15632 } 15633 15634 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15635 15636 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15637 15638 ExprResult VisitMemberExpr(MemberExpr *E) { 15639 return resolveDecl(E, E->getMemberDecl()); 15640 } 15641 15642 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15643 return resolveDecl(E, E->getDecl()); 15644 } 15645 }; 15646 } 15647 15648 /// Rebuilds a call expression which yielded __unknown_anytype. 15649 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15650 Expr *CalleeExpr = E->getCallee(); 15651 15652 enum FnKind { 15653 FK_MemberFunction, 15654 FK_FunctionPointer, 15655 FK_BlockPointer 15656 }; 15657 15658 FnKind Kind; 15659 QualType CalleeType = CalleeExpr->getType(); 15660 if (CalleeType == S.Context.BoundMemberTy) { 15661 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15662 Kind = FK_MemberFunction; 15663 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15664 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15665 CalleeType = Ptr->getPointeeType(); 15666 Kind = FK_FunctionPointer; 15667 } else { 15668 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15669 Kind = FK_BlockPointer; 15670 } 15671 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15672 15673 // Verify that this is a legal result type of a function. 15674 if (DestType->isArrayType() || DestType->isFunctionType()) { 15675 unsigned diagID = diag::err_func_returning_array_function; 15676 if (Kind == FK_BlockPointer) 15677 diagID = diag::err_block_returning_array_function; 15678 15679 S.Diag(E->getExprLoc(), diagID) 15680 << DestType->isFunctionType() << DestType; 15681 return ExprError(); 15682 } 15683 15684 // Otherwise, go ahead and set DestType as the call's result. 15685 E->setType(DestType.getNonLValueExprType(S.Context)); 15686 E->setValueKind(Expr::getValueKindForType(DestType)); 15687 assert(E->getObjectKind() == OK_Ordinary); 15688 15689 // Rebuild the function type, replacing the result type with DestType. 15690 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15691 if (Proto) { 15692 // __unknown_anytype(...) is a special case used by the debugger when 15693 // it has no idea what a function's signature is. 15694 // 15695 // We want to build this call essentially under the K&R 15696 // unprototyped rules, but making a FunctionNoProtoType in C++ 15697 // would foul up all sorts of assumptions. However, we cannot 15698 // simply pass all arguments as variadic arguments, nor can we 15699 // portably just call the function under a non-variadic type; see 15700 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15701 // However, it turns out that in practice it is generally safe to 15702 // call a function declared as "A foo(B,C,D);" under the prototype 15703 // "A foo(B,C,D,...);". The only known exception is with the 15704 // Windows ABI, where any variadic function is implicitly cdecl 15705 // regardless of its normal CC. Therefore we change the parameter 15706 // types to match the types of the arguments. 15707 // 15708 // This is a hack, but it is far superior to moving the 15709 // corresponding target-specific code from IR-gen to Sema/AST. 15710 15711 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15712 SmallVector<QualType, 8> ArgTypes; 15713 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15714 ArgTypes.reserve(E->getNumArgs()); 15715 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15716 Expr *Arg = E->getArg(i); 15717 QualType ArgType = Arg->getType(); 15718 if (E->isLValue()) { 15719 ArgType = S.Context.getLValueReferenceType(ArgType); 15720 } else if (E->isXValue()) { 15721 ArgType = S.Context.getRValueReferenceType(ArgType); 15722 } 15723 ArgTypes.push_back(ArgType); 15724 } 15725 ParamTypes = ArgTypes; 15726 } 15727 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15728 Proto->getExtProtoInfo()); 15729 } else { 15730 DestType = S.Context.getFunctionNoProtoType(DestType, 15731 FnType->getExtInfo()); 15732 } 15733 15734 // Rebuild the appropriate pointer-to-function type. 15735 switch (Kind) { 15736 case FK_MemberFunction: 15737 // Nothing to do. 15738 break; 15739 15740 case FK_FunctionPointer: 15741 DestType = S.Context.getPointerType(DestType); 15742 break; 15743 15744 case FK_BlockPointer: 15745 DestType = S.Context.getBlockPointerType(DestType); 15746 break; 15747 } 15748 15749 // Finally, we can recurse. 15750 ExprResult CalleeResult = Visit(CalleeExpr); 15751 if (!CalleeResult.isUsable()) return ExprError(); 15752 E->setCallee(CalleeResult.get()); 15753 15754 // Bind a temporary if necessary. 15755 return S.MaybeBindToTemporary(E); 15756 } 15757 15758 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15759 // Verify that this is a legal result type of a call. 15760 if (DestType->isArrayType() || DestType->isFunctionType()) { 15761 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15762 << DestType->isFunctionType() << DestType; 15763 return ExprError(); 15764 } 15765 15766 // Rewrite the method result type if available. 15767 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15768 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15769 Method->setReturnType(DestType); 15770 } 15771 15772 // Change the type of the message. 15773 E->setType(DestType.getNonReferenceType()); 15774 E->setValueKind(Expr::getValueKindForType(DestType)); 15775 15776 return S.MaybeBindToTemporary(E); 15777 } 15778 15779 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15780 // The only case we should ever see here is a function-to-pointer decay. 15781 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15782 assert(E->getValueKind() == VK_RValue); 15783 assert(E->getObjectKind() == OK_Ordinary); 15784 15785 E->setType(DestType); 15786 15787 // Rebuild the sub-expression as the pointee (function) type. 15788 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15789 15790 ExprResult Result = Visit(E->getSubExpr()); 15791 if (!Result.isUsable()) return ExprError(); 15792 15793 E->setSubExpr(Result.get()); 15794 return E; 15795 } else if (E->getCastKind() == CK_LValueToRValue) { 15796 assert(E->getValueKind() == VK_RValue); 15797 assert(E->getObjectKind() == OK_Ordinary); 15798 15799 assert(isa<BlockPointerType>(E->getType())); 15800 15801 E->setType(DestType); 15802 15803 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15804 DestType = S.Context.getLValueReferenceType(DestType); 15805 15806 ExprResult Result = Visit(E->getSubExpr()); 15807 if (!Result.isUsable()) return ExprError(); 15808 15809 E->setSubExpr(Result.get()); 15810 return E; 15811 } else { 15812 llvm_unreachable("Unhandled cast type!"); 15813 } 15814 } 15815 15816 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15817 ExprValueKind ValueKind = VK_LValue; 15818 QualType Type = DestType; 15819 15820 // We know how to make this work for certain kinds of decls: 15821 15822 // - functions 15823 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15824 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15825 DestType = Ptr->getPointeeType(); 15826 ExprResult Result = resolveDecl(E, VD); 15827 if (Result.isInvalid()) return ExprError(); 15828 return S.ImpCastExprToType(Result.get(), Type, 15829 CK_FunctionToPointerDecay, VK_RValue); 15830 } 15831 15832 if (!Type->isFunctionType()) { 15833 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15834 << VD << E->getSourceRange(); 15835 return ExprError(); 15836 } 15837 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15838 // We must match the FunctionDecl's type to the hack introduced in 15839 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15840 // type. See the lengthy commentary in that routine. 15841 QualType FDT = FD->getType(); 15842 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15843 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15844 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15845 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15846 SourceLocation Loc = FD->getLocation(); 15847 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15848 FD->getDeclContext(), 15849 Loc, Loc, FD->getNameInfo().getName(), 15850 DestType, FD->getTypeSourceInfo(), 15851 SC_None, false/*isInlineSpecified*/, 15852 FD->hasPrototype(), 15853 false/*isConstexprSpecified*/); 15854 15855 if (FD->getQualifier()) 15856 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15857 15858 SmallVector<ParmVarDecl*, 16> Params; 15859 for (const auto &AI : FT->param_types()) { 15860 ParmVarDecl *Param = 15861 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15862 Param->setScopeInfo(0, Params.size()); 15863 Params.push_back(Param); 15864 } 15865 NewFD->setParams(Params); 15866 DRE->setDecl(NewFD); 15867 VD = DRE->getDecl(); 15868 } 15869 } 15870 15871 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15872 if (MD->isInstance()) { 15873 ValueKind = VK_RValue; 15874 Type = S.Context.BoundMemberTy; 15875 } 15876 15877 // Function references aren't l-values in C. 15878 if (!S.getLangOpts().CPlusPlus) 15879 ValueKind = VK_RValue; 15880 15881 // - variables 15882 } else if (isa<VarDecl>(VD)) { 15883 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15884 Type = RefTy->getPointeeType(); 15885 } else if (Type->isFunctionType()) { 15886 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15887 << VD << E->getSourceRange(); 15888 return ExprError(); 15889 } 15890 15891 // - nothing else 15892 } else { 15893 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15894 << VD << E->getSourceRange(); 15895 return ExprError(); 15896 } 15897 15898 // Modifying the declaration like this is friendly to IR-gen but 15899 // also really dangerous. 15900 VD->setType(DestType); 15901 E->setType(Type); 15902 E->setValueKind(ValueKind); 15903 return E; 15904 } 15905 15906 /// Check a cast of an unknown-any type. We intentionally only 15907 /// trigger this for C-style casts. 15908 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15909 Expr *CastExpr, CastKind &CastKind, 15910 ExprValueKind &VK, CXXCastPath &Path) { 15911 // The type we're casting to must be either void or complete. 15912 if (!CastType->isVoidType() && 15913 RequireCompleteType(TypeRange.getBegin(), CastType, 15914 diag::err_typecheck_cast_to_incomplete)) 15915 return ExprError(); 15916 15917 // Rewrite the casted expression from scratch. 15918 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15919 if (!result.isUsable()) return ExprError(); 15920 15921 CastExpr = result.get(); 15922 VK = CastExpr->getValueKind(); 15923 CastKind = CK_NoOp; 15924 15925 return CastExpr; 15926 } 15927 15928 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15929 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15930 } 15931 15932 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15933 Expr *arg, QualType ¶mType) { 15934 // If the syntactic form of the argument is not an explicit cast of 15935 // any sort, just do default argument promotion. 15936 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15937 if (!castArg) { 15938 ExprResult result = DefaultArgumentPromotion(arg); 15939 if (result.isInvalid()) return ExprError(); 15940 paramType = result.get()->getType(); 15941 return result; 15942 } 15943 15944 // Otherwise, use the type that was written in the explicit cast. 15945 assert(!arg->hasPlaceholderType()); 15946 paramType = castArg->getTypeAsWritten(); 15947 15948 // Copy-initialize a parameter of that type. 15949 InitializedEntity entity = 15950 InitializedEntity::InitializeParameter(Context, paramType, 15951 /*consumed*/ false); 15952 return PerformCopyInitialization(entity, callLoc, arg); 15953 } 15954 15955 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15956 Expr *orig = E; 15957 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15958 while (true) { 15959 E = E->IgnoreParenImpCasts(); 15960 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15961 E = call->getCallee(); 15962 diagID = diag::err_uncasted_call_of_unknown_any; 15963 } else { 15964 break; 15965 } 15966 } 15967 15968 SourceLocation loc; 15969 NamedDecl *d; 15970 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15971 loc = ref->getLocation(); 15972 d = ref->getDecl(); 15973 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15974 loc = mem->getMemberLoc(); 15975 d = mem->getMemberDecl(); 15976 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15977 diagID = diag::err_uncasted_call_of_unknown_any; 15978 loc = msg->getSelectorStartLoc(); 15979 d = msg->getMethodDecl(); 15980 if (!d) { 15981 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15982 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15983 << orig->getSourceRange(); 15984 return ExprError(); 15985 } 15986 } else { 15987 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15988 << E->getSourceRange(); 15989 return ExprError(); 15990 } 15991 15992 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15993 15994 // Never recoverable. 15995 return ExprError(); 15996 } 15997 15998 /// Check for operands with placeholder types and complain if found. 15999 /// Returns ExprError() if there was an error and no recovery was possible. 16000 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16001 if (!getLangOpts().CPlusPlus) { 16002 // C cannot handle TypoExpr nodes on either side of a binop because it 16003 // doesn't handle dependent types properly, so make sure any TypoExprs have 16004 // been dealt with before checking the operands. 16005 ExprResult Result = CorrectDelayedTyposInExpr(E); 16006 if (!Result.isUsable()) return ExprError(); 16007 E = Result.get(); 16008 } 16009 16010 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16011 if (!placeholderType) return E; 16012 16013 switch (placeholderType->getKind()) { 16014 16015 // Overloaded expressions. 16016 case BuiltinType::Overload: { 16017 // Try to resolve a single function template specialization. 16018 // This is obligatory. 16019 ExprResult Result = E; 16020 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16021 return Result; 16022 16023 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16024 // leaves Result unchanged on failure. 16025 Result = E; 16026 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16027 return Result; 16028 16029 // If that failed, try to recover with a call. 16030 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16031 /*complain*/ true); 16032 return Result; 16033 } 16034 16035 // Bound member functions. 16036 case BuiltinType::BoundMember: { 16037 ExprResult result = E; 16038 const Expr *BME = E->IgnoreParens(); 16039 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16040 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16041 if (isa<CXXPseudoDestructorExpr>(BME)) { 16042 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16043 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16044 if (ME->getMemberNameInfo().getName().getNameKind() == 16045 DeclarationName::CXXDestructorName) 16046 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16047 } 16048 tryToRecoverWithCall(result, PD, 16049 /*complain*/ true); 16050 return result; 16051 } 16052 16053 // ARC unbridged casts. 16054 case BuiltinType::ARCUnbridgedCast: { 16055 Expr *realCast = stripARCUnbridgedCast(E); 16056 diagnoseARCUnbridgedCast(realCast); 16057 return realCast; 16058 } 16059 16060 // Expressions of unknown type. 16061 case BuiltinType::UnknownAny: 16062 return diagnoseUnknownAnyExpr(*this, E); 16063 16064 // Pseudo-objects. 16065 case BuiltinType::PseudoObject: 16066 return checkPseudoObjectRValue(E); 16067 16068 case BuiltinType::BuiltinFn: { 16069 // Accept __noop without parens by implicitly converting it to a call expr. 16070 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16071 if (DRE) { 16072 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16073 if (FD->getBuiltinID() == Builtin::BI__noop) { 16074 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16075 CK_BuiltinFnToFnPtr).get(); 16076 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16077 VK_RValue, SourceLocation()); 16078 } 16079 } 16080 16081 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16082 return ExprError(); 16083 } 16084 16085 // Expressions of unknown type. 16086 case BuiltinType::OMPArraySection: 16087 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16088 return ExprError(); 16089 16090 // Everything else should be impossible. 16091 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16092 case BuiltinType::Id: 16093 #include "clang/Basic/OpenCLImageTypes.def" 16094 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16095 #define PLACEHOLDER_TYPE(Id, SingletonId) 16096 #include "clang/AST/BuiltinTypes.def" 16097 break; 16098 } 16099 16100 llvm_unreachable("invalid placeholder type!"); 16101 } 16102 16103 bool Sema::CheckCaseExpression(Expr *E) { 16104 if (E->isTypeDependent()) 16105 return true; 16106 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16107 return E->getType()->isIntegralOrEnumerationType(); 16108 return false; 16109 } 16110 16111 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16112 ExprResult 16113 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16114 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16115 "Unknown Objective-C Boolean value!"); 16116 QualType BoolT = Context.ObjCBuiltinBoolTy; 16117 if (!Context.getBOOLDecl()) { 16118 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16119 Sema::LookupOrdinaryName); 16120 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16121 NamedDecl *ND = Result.getFoundDecl(); 16122 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16123 Context.setBOOLDecl(TD); 16124 } 16125 } 16126 if (Context.getBOOLDecl()) 16127 BoolT = Context.getBOOLType(); 16128 return new (Context) 16129 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16130 } 16131 16132 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16133 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16134 SourceLocation RParen) { 16135 16136 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16137 16138 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16139 [&](const AvailabilitySpec &Spec) { 16140 return Spec.getPlatform() == Platform; 16141 }); 16142 16143 VersionTuple Version; 16144 if (Spec != AvailSpecs.end()) 16145 Version = Spec->getVersion(); 16146 16147 // The use of `@available` in the enclosing function should be analyzed to 16148 // warn when it's used inappropriately (i.e. not if(@available)). 16149 if (getCurFunctionOrMethodDecl()) 16150 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16151 else if (getCurBlock() || getCurLambda()) 16152 getCurFunction()->HasPotentialAvailabilityViolations = true; 16153 16154 return new (Context) 16155 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16156 } 16157