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.isCXX98PODType(Context)) 780 return VAK_Valid; 781 782 // C++11 [expr.call]p7: 783 // Passing a potentially-evaluated argument of class type (Clause 9) 784 // having a non-trivial copy constructor, a non-trivial move constructor, 785 // or a non-trivial destructor, with no corresponding parameter, 786 // is conditionally-supported with implementation-defined semantics. 787 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 788 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 789 if (!Record->hasNonTrivialCopyConstructor() && 790 !Record->hasNonTrivialMoveConstructor() && 791 !Record->hasNonTrivialDestructor()) 792 return VAK_ValidInCXX11; 793 794 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 795 return VAK_Valid; 796 797 if (Ty->isObjCObjectType()) 798 return VAK_Invalid; 799 800 if (getLangOpts().MSVCCompat) 801 return VAK_MSVCUndefined; 802 803 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 804 // permitted to reject them. We should consider doing so. 805 return VAK_Undefined; 806 } 807 808 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 809 // Don't allow one to pass an Objective-C interface to a vararg. 810 const QualType &Ty = E->getType(); 811 VarArgKind VAK = isValidVarArgType(Ty); 812 813 // Complain about passing non-POD types through varargs. 814 switch (VAK) { 815 case VAK_ValidInCXX11: 816 DiagRuntimeBehavior( 817 E->getLocStart(), nullptr, 818 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 819 << Ty << CT); 820 LLVM_FALLTHROUGH; 821 case VAK_Valid: 822 if (Ty->isRecordType()) { 823 // This is unlikely to be what the user intended. If the class has a 824 // 'c_str' member function, the user probably meant to call that. 825 DiagRuntimeBehavior(E->getLocStart(), nullptr, 826 PDiag(diag::warn_pass_class_arg_to_vararg) 827 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 828 } 829 break; 830 831 case VAK_Undefined: 832 case VAK_MSVCUndefined: 833 DiagRuntimeBehavior( 834 E->getLocStart(), nullptr, 835 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 836 << getLangOpts().CPlusPlus11 << Ty << CT); 837 break; 838 839 case VAK_Invalid: 840 if (Ty->isObjCObjectType()) 841 DiagRuntimeBehavior( 842 E->getLocStart(), nullptr, 843 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 844 << Ty << CT); 845 else 846 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 847 << isa<InitListExpr>(E) << Ty << CT; 848 break; 849 } 850 } 851 852 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 853 /// will create a trap if the resulting type is not a POD type. 854 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 855 FunctionDecl *FDecl) { 856 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 857 // Strip the unbridged-cast placeholder expression off, if applicable. 858 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 859 (CT == VariadicMethod || 860 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 861 E = stripARCUnbridgedCast(E); 862 863 // Otherwise, do normal placeholder checking. 864 } else { 865 ExprResult ExprRes = CheckPlaceholderExpr(E); 866 if (ExprRes.isInvalid()) 867 return ExprError(); 868 E = ExprRes.get(); 869 } 870 } 871 872 ExprResult ExprRes = DefaultArgumentPromotion(E); 873 if (ExprRes.isInvalid()) 874 return ExprError(); 875 E = ExprRes.get(); 876 877 // Diagnostics regarding non-POD argument types are 878 // emitted along with format string checking in Sema::CheckFunctionCall(). 879 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 880 // Turn this into a trap. 881 CXXScopeSpec SS; 882 SourceLocation TemplateKWLoc; 883 UnqualifiedId Name; 884 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 885 E->getLocStart()); 886 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 887 Name, true, false); 888 if (TrapFn.isInvalid()) 889 return ExprError(); 890 891 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 892 E->getLocStart(), None, 893 E->getLocEnd()); 894 if (Call.isInvalid()) 895 return ExprError(); 896 897 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 898 Call.get(), E); 899 if (Comma.isInvalid()) 900 return ExprError(); 901 return Comma.get(); 902 } 903 904 if (!getLangOpts().CPlusPlus && 905 RequireCompleteType(E->getExprLoc(), E->getType(), 906 diag::err_call_incomplete_argument)) 907 return ExprError(); 908 909 return E; 910 } 911 912 /// \brief Converts an integer to complex float type. Helper function of 913 /// UsualArithmeticConversions() 914 /// 915 /// \return false if the integer expression is an integer type and is 916 /// successfully converted to the complex type. 917 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 918 ExprResult &ComplexExpr, 919 QualType IntTy, 920 QualType ComplexTy, 921 bool SkipCast) { 922 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 923 if (SkipCast) return false; 924 if (IntTy->isIntegerType()) { 925 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 926 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 927 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 928 CK_FloatingRealToComplex); 929 } else { 930 assert(IntTy->isComplexIntegerType()); 931 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 932 CK_IntegralComplexToFloatingComplex); 933 } 934 return false; 935 } 936 937 /// \brief Handle arithmetic conversion with complex types. Helper function of 938 /// UsualArithmeticConversions() 939 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 940 ExprResult &RHS, QualType LHSType, 941 QualType RHSType, 942 bool IsCompAssign) { 943 // if we have an integer operand, the result is the complex type. 944 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 945 /*skipCast*/false)) 946 return LHSType; 947 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 948 /*skipCast*/IsCompAssign)) 949 return RHSType; 950 951 // This handles complex/complex, complex/float, or float/complex. 952 // When both operands are complex, the shorter operand is converted to the 953 // type of the longer, and that is the type of the result. This corresponds 954 // to what is done when combining two real floating-point operands. 955 // The fun begins when size promotion occur across type domains. 956 // From H&S 6.3.4: When one operand is complex and the other is a real 957 // floating-point type, the less precise type is converted, within it's 958 // real or complex domain, to the precision of the other type. For example, 959 // when combining a "long double" with a "double _Complex", the 960 // "double _Complex" is promoted to "long double _Complex". 961 962 // Compute the rank of the two types, regardless of whether they are complex. 963 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 964 965 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 966 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 967 QualType LHSElementType = 968 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 969 QualType RHSElementType = 970 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 971 972 QualType ResultType = S.Context.getComplexType(LHSElementType); 973 if (Order < 0) { 974 // Promote the precision of the LHS if not an assignment. 975 ResultType = S.Context.getComplexType(RHSElementType); 976 if (!IsCompAssign) { 977 if (LHSComplexType) 978 LHS = 979 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 980 else 981 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 982 } 983 } else if (Order > 0) { 984 // Promote the precision of the RHS. 985 if (RHSComplexType) 986 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 987 else 988 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 989 } 990 return ResultType; 991 } 992 993 /// \brief Handle arithmetic conversion from integer to float. Helper function 994 /// of UsualArithmeticConversions() 995 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 996 ExprResult &IntExpr, 997 QualType FloatTy, QualType IntTy, 998 bool ConvertFloat, bool ConvertInt) { 999 if (IntTy->isIntegerType()) { 1000 if (ConvertInt) 1001 // Convert intExpr to the lhs floating point type. 1002 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1003 CK_IntegralToFloating); 1004 return FloatTy; 1005 } 1006 1007 // Convert both sides to the appropriate complex float. 1008 assert(IntTy->isComplexIntegerType()); 1009 QualType result = S.Context.getComplexType(FloatTy); 1010 1011 // _Complex int -> _Complex float 1012 if (ConvertInt) 1013 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1014 CK_IntegralComplexToFloatingComplex); 1015 1016 // float -> _Complex float 1017 if (ConvertFloat) 1018 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1019 CK_FloatingRealToComplex); 1020 1021 return result; 1022 } 1023 1024 /// \brief Handle arithmethic conversion with floating point types. Helper 1025 /// function of UsualArithmeticConversions() 1026 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1027 ExprResult &RHS, QualType LHSType, 1028 QualType RHSType, bool IsCompAssign) { 1029 bool LHSFloat = LHSType->isRealFloatingType(); 1030 bool RHSFloat = RHSType->isRealFloatingType(); 1031 1032 // If we have two real floating types, convert the smaller operand 1033 // to the bigger result. 1034 if (LHSFloat && RHSFloat) { 1035 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1036 if (order > 0) { 1037 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1038 return LHSType; 1039 } 1040 1041 assert(order < 0 && "illegal float comparison"); 1042 if (!IsCompAssign) 1043 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1044 return RHSType; 1045 } 1046 1047 if (LHSFloat) { 1048 // Half FP has to be promoted to float unless it is natively supported 1049 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1050 LHSType = S.Context.FloatTy; 1051 1052 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1053 /*convertFloat=*/!IsCompAssign, 1054 /*convertInt=*/ true); 1055 } 1056 assert(RHSFloat); 1057 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1058 /*convertInt=*/ true, 1059 /*convertFloat=*/!IsCompAssign); 1060 } 1061 1062 /// \brief Diagnose attempts to convert between __float128 and long double if 1063 /// there is no support for such conversion. Helper function of 1064 /// UsualArithmeticConversions(). 1065 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1066 QualType RHSType) { 1067 /* No issue converting if at least one of the types is not a floating point 1068 type or the two types have the same rank. 1069 */ 1070 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1071 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1072 return false; 1073 1074 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1075 "The remaining types must be floating point types."); 1076 1077 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1078 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1079 1080 QualType LHSElemType = LHSComplex ? 1081 LHSComplex->getElementType() : LHSType; 1082 QualType RHSElemType = RHSComplex ? 1083 RHSComplex->getElementType() : RHSType; 1084 1085 // No issue if the two types have the same representation 1086 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1087 &S.Context.getFloatTypeSemantics(RHSElemType)) 1088 return false; 1089 1090 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1091 RHSElemType == S.Context.LongDoubleTy); 1092 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1093 RHSElemType == S.Context.Float128Ty); 1094 1095 // We've handled the situation where __float128 and long double have the same 1096 // representation. We allow all conversions for all possible long double types 1097 // except PPC's double double. 1098 return Float128AndLongDouble && 1099 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1100 &llvm::APFloat::PPCDoubleDouble()); 1101 } 1102 1103 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1104 1105 namespace { 1106 /// These helper callbacks are placed in an anonymous namespace to 1107 /// permit their use as function template parameters. 1108 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1109 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1110 } 1111 1112 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1113 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1114 CK_IntegralComplexCast); 1115 } 1116 } 1117 1118 /// \brief Handle integer arithmetic conversions. Helper function of 1119 /// UsualArithmeticConversions() 1120 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1121 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1122 ExprResult &RHS, QualType LHSType, 1123 QualType RHSType, bool IsCompAssign) { 1124 // The rules for this case are in C99 6.3.1.8 1125 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1126 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1127 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1128 if (LHSSigned == RHSSigned) { 1129 // Same signedness; use the higher-ranked type 1130 if (order >= 0) { 1131 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1132 return LHSType; 1133 } else if (!IsCompAssign) 1134 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1135 return RHSType; 1136 } else if (order != (LHSSigned ? 1 : -1)) { 1137 // The unsigned type has greater than or equal rank to the 1138 // signed type, so use the unsigned type 1139 if (RHSSigned) { 1140 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1141 return LHSType; 1142 } else if (!IsCompAssign) 1143 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1144 return RHSType; 1145 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1146 // The two types are different widths; if we are here, that 1147 // means the signed type is larger than the unsigned type, so 1148 // use the signed type. 1149 if (LHSSigned) { 1150 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1151 return LHSType; 1152 } else if (!IsCompAssign) 1153 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1154 return RHSType; 1155 } else { 1156 // The signed type is higher-ranked than the unsigned type, 1157 // but isn't actually any bigger (like unsigned int and long 1158 // on most 32-bit systems). Use the unsigned type corresponding 1159 // to the signed type. 1160 QualType result = 1161 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1162 RHS = (*doRHSCast)(S, RHS.get(), result); 1163 if (!IsCompAssign) 1164 LHS = (*doLHSCast)(S, LHS.get(), result); 1165 return result; 1166 } 1167 } 1168 1169 /// \brief Handle conversions with GCC complex int extension. Helper function 1170 /// of UsualArithmeticConversions() 1171 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1172 ExprResult &RHS, QualType LHSType, 1173 QualType RHSType, 1174 bool IsCompAssign) { 1175 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1176 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1177 1178 if (LHSComplexInt && RHSComplexInt) { 1179 QualType LHSEltType = LHSComplexInt->getElementType(); 1180 QualType RHSEltType = RHSComplexInt->getElementType(); 1181 QualType ScalarType = 1182 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1183 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1184 1185 return S.Context.getComplexType(ScalarType); 1186 } 1187 1188 if (LHSComplexInt) { 1189 QualType LHSEltType = LHSComplexInt->getElementType(); 1190 QualType ScalarType = 1191 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1192 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1193 QualType ComplexType = S.Context.getComplexType(ScalarType); 1194 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1195 CK_IntegralRealToComplex); 1196 1197 return ComplexType; 1198 } 1199 1200 assert(RHSComplexInt); 1201 1202 QualType RHSEltType = RHSComplexInt->getElementType(); 1203 QualType ScalarType = 1204 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1205 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1206 QualType ComplexType = S.Context.getComplexType(ScalarType); 1207 1208 if (!IsCompAssign) 1209 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1210 CK_IntegralRealToComplex); 1211 return ComplexType; 1212 } 1213 1214 /// UsualArithmeticConversions - Performs various conversions that are common to 1215 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1216 /// routine returns the first non-arithmetic type found. The client is 1217 /// responsible for emitting appropriate error diagnostics. 1218 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1219 bool IsCompAssign) { 1220 if (!IsCompAssign) { 1221 LHS = UsualUnaryConversions(LHS.get()); 1222 if (LHS.isInvalid()) 1223 return QualType(); 1224 } 1225 1226 RHS = UsualUnaryConversions(RHS.get()); 1227 if (RHS.isInvalid()) 1228 return QualType(); 1229 1230 // For conversion purposes, we ignore any qualifiers. 1231 // For example, "const float" and "float" are equivalent. 1232 QualType LHSType = 1233 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1234 QualType RHSType = 1235 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1236 1237 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1238 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1239 LHSType = AtomicLHS->getValueType(); 1240 1241 // If both types are identical, no conversion is needed. 1242 if (LHSType == RHSType) 1243 return LHSType; 1244 1245 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1246 // The caller can deal with this (e.g. pointer + int). 1247 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1248 return QualType(); 1249 1250 // Apply unary and bitfield promotions to the LHS's type. 1251 QualType LHSUnpromotedType = LHSType; 1252 if (LHSType->isPromotableIntegerType()) 1253 LHSType = Context.getPromotedIntegerType(LHSType); 1254 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1255 if (!LHSBitfieldPromoteTy.isNull()) 1256 LHSType = LHSBitfieldPromoteTy; 1257 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1258 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1259 1260 // If both types are identical, no conversion is needed. 1261 if (LHSType == RHSType) 1262 return LHSType; 1263 1264 // At this point, we have two different arithmetic types. 1265 1266 // Diagnose attempts to convert between __float128 and long double where 1267 // such conversions currently can't be handled. 1268 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1269 return QualType(); 1270 1271 // Handle complex types first (C99 6.3.1.8p1). 1272 if (LHSType->isComplexType() || RHSType->isComplexType()) 1273 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1274 IsCompAssign); 1275 1276 // Now handle "real" floating types (i.e. float, double, long double). 1277 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1278 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1279 IsCompAssign); 1280 1281 // Handle GCC complex int extension. 1282 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1283 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1284 IsCompAssign); 1285 1286 // Finally, we have two differing integer types. 1287 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1288 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1289 } 1290 1291 1292 //===----------------------------------------------------------------------===// 1293 // Semantic Analysis for various Expression Types 1294 //===----------------------------------------------------------------------===// 1295 1296 1297 ExprResult 1298 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1299 SourceLocation DefaultLoc, 1300 SourceLocation RParenLoc, 1301 Expr *ControllingExpr, 1302 ArrayRef<ParsedType> ArgTypes, 1303 ArrayRef<Expr *> ArgExprs) { 1304 unsigned NumAssocs = ArgTypes.size(); 1305 assert(NumAssocs == ArgExprs.size()); 1306 1307 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1308 for (unsigned i = 0; i < NumAssocs; ++i) { 1309 if (ArgTypes[i]) 1310 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1311 else 1312 Types[i] = nullptr; 1313 } 1314 1315 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1316 ControllingExpr, 1317 llvm::makeArrayRef(Types, NumAssocs), 1318 ArgExprs); 1319 delete [] Types; 1320 return ER; 1321 } 1322 1323 ExprResult 1324 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1325 SourceLocation DefaultLoc, 1326 SourceLocation RParenLoc, 1327 Expr *ControllingExpr, 1328 ArrayRef<TypeSourceInfo *> Types, 1329 ArrayRef<Expr *> Exprs) { 1330 unsigned NumAssocs = Types.size(); 1331 assert(NumAssocs == Exprs.size()); 1332 1333 // Decay and strip qualifiers for the controlling expression type, and handle 1334 // placeholder type replacement. See committee discussion from WG14 DR423. 1335 { 1336 EnterExpressionEvaluationContext Unevaluated( 1337 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1338 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1339 if (R.isInvalid()) 1340 return ExprError(); 1341 ControllingExpr = R.get(); 1342 } 1343 1344 // The controlling expression is an unevaluated operand, so side effects are 1345 // likely unintended. 1346 if (!inTemplateInstantiation() && 1347 ControllingExpr->HasSideEffects(Context, false)) 1348 Diag(ControllingExpr->getExprLoc(), 1349 diag::warn_side_effects_unevaluated_context); 1350 1351 bool TypeErrorFound = false, 1352 IsResultDependent = ControllingExpr->isTypeDependent(), 1353 ContainsUnexpandedParameterPack 1354 = ControllingExpr->containsUnexpandedParameterPack(); 1355 1356 for (unsigned i = 0; i < NumAssocs; ++i) { 1357 if (Exprs[i]->containsUnexpandedParameterPack()) 1358 ContainsUnexpandedParameterPack = true; 1359 1360 if (Types[i]) { 1361 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1362 ContainsUnexpandedParameterPack = true; 1363 1364 if (Types[i]->getType()->isDependentType()) { 1365 IsResultDependent = true; 1366 } else { 1367 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1368 // complete object type other than a variably modified type." 1369 unsigned D = 0; 1370 if (Types[i]->getType()->isIncompleteType()) 1371 D = diag::err_assoc_type_incomplete; 1372 else if (!Types[i]->getType()->isObjectType()) 1373 D = diag::err_assoc_type_nonobject; 1374 else if (Types[i]->getType()->isVariablyModifiedType()) 1375 D = diag::err_assoc_type_variably_modified; 1376 1377 if (D != 0) { 1378 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1379 << Types[i]->getTypeLoc().getSourceRange() 1380 << Types[i]->getType(); 1381 TypeErrorFound = true; 1382 } 1383 1384 // C11 6.5.1.1p2 "No two generic associations in the same generic 1385 // selection shall specify compatible types." 1386 for (unsigned j = i+1; j < NumAssocs; ++j) 1387 if (Types[j] && !Types[j]->getType()->isDependentType() && 1388 Context.typesAreCompatible(Types[i]->getType(), 1389 Types[j]->getType())) { 1390 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1391 diag::err_assoc_compatible_types) 1392 << Types[j]->getTypeLoc().getSourceRange() 1393 << Types[j]->getType() 1394 << Types[i]->getType(); 1395 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1396 diag::note_compat_assoc) 1397 << Types[i]->getTypeLoc().getSourceRange() 1398 << Types[i]->getType(); 1399 TypeErrorFound = true; 1400 } 1401 } 1402 } 1403 } 1404 if (TypeErrorFound) 1405 return ExprError(); 1406 1407 // If we determined that the generic selection is result-dependent, don't 1408 // try to compute the result expression. 1409 if (IsResultDependent) 1410 return new (Context) GenericSelectionExpr( 1411 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1412 ContainsUnexpandedParameterPack); 1413 1414 SmallVector<unsigned, 1> CompatIndices; 1415 unsigned DefaultIndex = -1U; 1416 for (unsigned i = 0; i < NumAssocs; ++i) { 1417 if (!Types[i]) 1418 DefaultIndex = i; 1419 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1420 Types[i]->getType())) 1421 CompatIndices.push_back(i); 1422 } 1423 1424 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1425 // type compatible with at most one of the types named in its generic 1426 // association list." 1427 if (CompatIndices.size() > 1) { 1428 // We strip parens here because the controlling expression is typically 1429 // parenthesized in macro definitions. 1430 ControllingExpr = ControllingExpr->IgnoreParens(); 1431 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1432 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1433 << (unsigned) CompatIndices.size(); 1434 for (unsigned I : CompatIndices) { 1435 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1436 diag::note_compat_assoc) 1437 << Types[I]->getTypeLoc().getSourceRange() 1438 << Types[I]->getType(); 1439 } 1440 return ExprError(); 1441 } 1442 1443 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1444 // its controlling expression shall have type compatible with exactly one of 1445 // the types named in its generic association list." 1446 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1447 // We strip parens here because the controlling expression is typically 1448 // parenthesized in macro definitions. 1449 ControllingExpr = ControllingExpr->IgnoreParens(); 1450 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1451 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1452 return ExprError(); 1453 } 1454 1455 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1456 // type name that is compatible with the type of the controlling expression, 1457 // then the result expression of the generic selection is the expression 1458 // in that generic association. Otherwise, the result expression of the 1459 // generic selection is the expression in the default generic association." 1460 unsigned ResultIndex = 1461 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1462 1463 return new (Context) GenericSelectionExpr( 1464 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1465 ContainsUnexpandedParameterPack, ResultIndex); 1466 } 1467 1468 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1469 /// location of the token and the offset of the ud-suffix within it. 1470 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1471 unsigned Offset) { 1472 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1473 S.getLangOpts()); 1474 } 1475 1476 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1477 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1478 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1479 IdentifierInfo *UDSuffix, 1480 SourceLocation UDSuffixLoc, 1481 ArrayRef<Expr*> Args, 1482 SourceLocation LitEndLoc) { 1483 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1484 1485 QualType ArgTy[2]; 1486 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1487 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1488 if (ArgTy[ArgIdx]->isArrayType()) 1489 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1490 } 1491 1492 DeclarationName OpName = 1493 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1494 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1495 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1496 1497 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1498 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1499 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1500 /*AllowStringTemplate*/ false, 1501 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1502 return ExprError(); 1503 1504 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1505 } 1506 1507 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1508 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1509 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1510 /// multiple tokens. However, the common case is that StringToks points to one 1511 /// string. 1512 /// 1513 ExprResult 1514 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1515 assert(!StringToks.empty() && "Must have at least one string!"); 1516 1517 StringLiteralParser Literal(StringToks, PP); 1518 if (Literal.hadError) 1519 return ExprError(); 1520 1521 SmallVector<SourceLocation, 4> StringTokLocs; 1522 for (const Token &Tok : StringToks) 1523 StringTokLocs.push_back(Tok.getLocation()); 1524 1525 QualType CharTy = Context.CharTy; 1526 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1527 if (Literal.isWide()) { 1528 CharTy = Context.getWideCharType(); 1529 Kind = StringLiteral::Wide; 1530 } else if (Literal.isUTF8()) { 1531 Kind = StringLiteral::UTF8; 1532 } else if (Literal.isUTF16()) { 1533 CharTy = Context.Char16Ty; 1534 Kind = StringLiteral::UTF16; 1535 } else if (Literal.isUTF32()) { 1536 CharTy = Context.Char32Ty; 1537 Kind = StringLiteral::UTF32; 1538 } else if (Literal.isPascal()) { 1539 CharTy = Context.UnsignedCharTy; 1540 } 1541 1542 QualType CharTyConst = CharTy; 1543 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1544 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1545 CharTyConst.addConst(); 1546 1547 // Get an array type for the string, according to C99 6.4.5. This includes 1548 // the nul terminator character as well as the string length for pascal 1549 // strings. 1550 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1551 llvm::APInt(32, Literal.GetNumStringChars()+1), 1552 ArrayType::Normal, 0); 1553 1554 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1555 if (getLangOpts().OpenCL) { 1556 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1557 } 1558 1559 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1560 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1561 Kind, Literal.Pascal, StrTy, 1562 &StringTokLocs[0], 1563 StringTokLocs.size()); 1564 if (Literal.getUDSuffix().empty()) 1565 return Lit; 1566 1567 // We're building a user-defined literal. 1568 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1569 SourceLocation UDSuffixLoc = 1570 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1571 Literal.getUDSuffixOffset()); 1572 1573 // Make sure we're allowed user-defined literals here. 1574 if (!UDLScope) 1575 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1576 1577 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1578 // operator "" X (str, len) 1579 QualType SizeType = Context.getSizeType(); 1580 1581 DeclarationName OpName = 1582 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1583 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1584 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1585 1586 QualType ArgTy[] = { 1587 Context.getArrayDecayedType(StrTy), SizeType 1588 }; 1589 1590 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1591 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1592 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1593 /*AllowStringTemplate*/ true, 1594 /*DiagnoseMissing*/ true)) { 1595 1596 case LOLR_Cooked: { 1597 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1598 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1599 StringTokLocs[0]); 1600 Expr *Args[] = { Lit, LenArg }; 1601 1602 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1603 } 1604 1605 case LOLR_StringTemplate: { 1606 TemplateArgumentListInfo ExplicitArgs; 1607 1608 unsigned CharBits = Context.getIntWidth(CharTy); 1609 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1610 llvm::APSInt Value(CharBits, CharIsUnsigned); 1611 1612 TemplateArgument TypeArg(CharTy); 1613 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1614 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1615 1616 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1617 Value = Lit->getCodeUnit(I); 1618 TemplateArgument Arg(Context, Value, CharTy); 1619 TemplateArgumentLocInfo ArgInfo; 1620 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1621 } 1622 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1623 &ExplicitArgs); 1624 } 1625 case LOLR_Raw: 1626 case LOLR_Template: 1627 case LOLR_ErrorNoDiagnostic: 1628 llvm_unreachable("unexpected literal operator lookup result"); 1629 case LOLR_Error: 1630 return ExprError(); 1631 } 1632 llvm_unreachable("unexpected literal operator lookup result"); 1633 } 1634 1635 ExprResult 1636 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1637 SourceLocation Loc, 1638 const CXXScopeSpec *SS) { 1639 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1640 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1641 } 1642 1643 /// BuildDeclRefExpr - Build an expression that references a 1644 /// declaration that does not require a closure capture. 1645 ExprResult 1646 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1647 const DeclarationNameInfo &NameInfo, 1648 const CXXScopeSpec *SS, NamedDecl *FoundD, 1649 const TemplateArgumentListInfo *TemplateArgs) { 1650 bool RefersToCapturedVariable = 1651 isa<VarDecl>(D) && 1652 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1653 1654 DeclRefExpr *E; 1655 if (isa<VarTemplateSpecializationDecl>(D)) { 1656 VarTemplateSpecializationDecl *VarSpec = 1657 cast<VarTemplateSpecializationDecl>(D); 1658 1659 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1660 : NestedNameSpecifierLoc(), 1661 VarSpec->getTemplateKeywordLoc(), D, 1662 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1663 FoundD, TemplateArgs); 1664 } else { 1665 assert(!TemplateArgs && "No template arguments for non-variable" 1666 " template specialization references"); 1667 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1668 : NestedNameSpecifierLoc(), 1669 SourceLocation(), D, RefersToCapturedVariable, 1670 NameInfo, Ty, VK, FoundD); 1671 } 1672 1673 MarkDeclRefReferenced(E); 1674 1675 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1676 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1677 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1678 recordUseOfEvaluatedWeak(E); 1679 1680 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1681 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1682 FD = IFD->getAnonField(); 1683 if (FD) { 1684 UnusedPrivateFields.remove(FD); 1685 // Just in case we're building an illegal pointer-to-member. 1686 if (FD->isBitField()) 1687 E->setObjectKind(OK_BitField); 1688 } 1689 1690 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1691 // designates a bit-field. 1692 if (auto *BD = dyn_cast<BindingDecl>(D)) 1693 if (auto *BE = BD->getBinding()) 1694 E->setObjectKind(BE->getObjectKind()); 1695 1696 return E; 1697 } 1698 1699 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1700 /// possibly a list of template arguments. 1701 /// 1702 /// If this produces template arguments, it is permitted to call 1703 /// DecomposeTemplateName. 1704 /// 1705 /// This actually loses a lot of source location information for 1706 /// non-standard name kinds; we should consider preserving that in 1707 /// some way. 1708 void 1709 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1710 TemplateArgumentListInfo &Buffer, 1711 DeclarationNameInfo &NameInfo, 1712 const TemplateArgumentListInfo *&TemplateArgs) { 1713 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1714 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1715 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1716 1717 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1718 Id.TemplateId->NumArgs); 1719 translateTemplateArguments(TemplateArgsPtr, Buffer); 1720 1721 TemplateName TName = Id.TemplateId->Template.get(); 1722 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1723 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1724 TemplateArgs = &Buffer; 1725 } else { 1726 NameInfo = GetNameFromUnqualifiedId(Id); 1727 TemplateArgs = nullptr; 1728 } 1729 } 1730 1731 static void emitEmptyLookupTypoDiagnostic( 1732 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1733 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1734 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1735 DeclContext *Ctx = 1736 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1737 if (!TC) { 1738 // Emit a special diagnostic for failed member lookups. 1739 // FIXME: computing the declaration context might fail here (?) 1740 if (Ctx) 1741 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1742 << SS.getRange(); 1743 else 1744 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1745 return; 1746 } 1747 1748 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1749 bool DroppedSpecifier = 1750 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1751 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1752 ? diag::note_implicit_param_decl 1753 : diag::note_previous_decl; 1754 if (!Ctx) 1755 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1756 SemaRef.PDiag(NoteID)); 1757 else 1758 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1759 << Typo << Ctx << DroppedSpecifier 1760 << SS.getRange(), 1761 SemaRef.PDiag(NoteID)); 1762 } 1763 1764 /// Diagnose an empty lookup. 1765 /// 1766 /// \return false if new lookup candidates were found 1767 bool 1768 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1769 std::unique_ptr<CorrectionCandidateCallback> CCC, 1770 TemplateArgumentListInfo *ExplicitTemplateArgs, 1771 ArrayRef<Expr *> Args, TypoExpr **Out) { 1772 DeclarationName Name = R.getLookupName(); 1773 1774 unsigned diagnostic = diag::err_undeclared_var_use; 1775 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1776 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1777 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1778 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1779 diagnostic = diag::err_undeclared_use; 1780 diagnostic_suggest = diag::err_undeclared_use_suggest; 1781 } 1782 1783 // If the original lookup was an unqualified lookup, fake an 1784 // unqualified lookup. This is useful when (for example) the 1785 // original lookup would not have found something because it was a 1786 // dependent name. 1787 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1788 while (DC) { 1789 if (isa<CXXRecordDecl>(DC)) { 1790 LookupQualifiedName(R, DC); 1791 1792 if (!R.empty()) { 1793 // Don't give errors about ambiguities in this lookup. 1794 R.suppressDiagnostics(); 1795 1796 // During a default argument instantiation the CurContext points 1797 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1798 // function parameter list, hence add an explicit check. 1799 bool isDefaultArgument = 1800 !CodeSynthesisContexts.empty() && 1801 CodeSynthesisContexts.back().Kind == 1802 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1803 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1804 bool isInstance = CurMethod && 1805 CurMethod->isInstance() && 1806 DC == CurMethod->getParent() && !isDefaultArgument; 1807 1808 // Give a code modification hint to insert 'this->'. 1809 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1810 // Actually quite difficult! 1811 if (getLangOpts().MSVCCompat) 1812 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1813 if (isInstance) { 1814 Diag(R.getNameLoc(), diagnostic) << Name 1815 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1816 CheckCXXThisCapture(R.getNameLoc()); 1817 } else { 1818 Diag(R.getNameLoc(), diagnostic) << Name; 1819 } 1820 1821 // Do we really want to note all of these? 1822 for (NamedDecl *D : R) 1823 Diag(D->getLocation(), diag::note_dependent_var_use); 1824 1825 // Return true if we are inside a default argument instantiation 1826 // and the found name refers to an instance member function, otherwise 1827 // the function calling DiagnoseEmptyLookup will try to create an 1828 // implicit member call and this is wrong for default argument. 1829 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1830 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1831 return true; 1832 } 1833 1834 // Tell the callee to try to recover. 1835 return false; 1836 } 1837 1838 R.clear(); 1839 } 1840 1841 // In Microsoft mode, if we are performing lookup from within a friend 1842 // function definition declared at class scope then we must set 1843 // DC to the lexical parent to be able to search into the parent 1844 // class. 1845 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1846 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1847 DC->getLexicalParent()->isRecord()) 1848 DC = DC->getLexicalParent(); 1849 else 1850 DC = DC->getParent(); 1851 } 1852 1853 // We didn't find anything, so try to correct for a typo. 1854 TypoCorrection Corrected; 1855 if (S && Out) { 1856 SourceLocation TypoLoc = R.getNameLoc(); 1857 assert(!ExplicitTemplateArgs && 1858 "Diagnosing an empty lookup with explicit template args!"); 1859 *Out = CorrectTypoDelayed( 1860 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1861 [=](const TypoCorrection &TC) { 1862 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1863 diagnostic, diagnostic_suggest); 1864 }, 1865 nullptr, CTK_ErrorRecovery); 1866 if (*Out) 1867 return true; 1868 } else if (S && (Corrected = 1869 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1870 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1871 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1872 bool DroppedSpecifier = 1873 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1874 R.setLookupName(Corrected.getCorrection()); 1875 1876 bool AcceptableWithRecovery = false; 1877 bool AcceptableWithoutRecovery = false; 1878 NamedDecl *ND = Corrected.getFoundDecl(); 1879 if (ND) { 1880 if (Corrected.isOverloaded()) { 1881 OverloadCandidateSet OCS(R.getNameLoc(), 1882 OverloadCandidateSet::CSK_Normal); 1883 OverloadCandidateSet::iterator Best; 1884 for (NamedDecl *CD : Corrected) { 1885 if (FunctionTemplateDecl *FTD = 1886 dyn_cast<FunctionTemplateDecl>(CD)) 1887 AddTemplateOverloadCandidate( 1888 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1889 Args, OCS); 1890 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1891 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1892 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1893 Args, OCS); 1894 } 1895 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1896 case OR_Success: 1897 ND = Best->FoundDecl; 1898 Corrected.setCorrectionDecl(ND); 1899 break; 1900 default: 1901 // FIXME: Arbitrarily pick the first declaration for the note. 1902 Corrected.setCorrectionDecl(ND); 1903 break; 1904 } 1905 } 1906 R.addDecl(ND); 1907 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1908 CXXRecordDecl *Record = nullptr; 1909 if (Corrected.getCorrectionSpecifier()) { 1910 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1911 Record = Ty->getAsCXXRecordDecl(); 1912 } 1913 if (!Record) 1914 Record = cast<CXXRecordDecl>( 1915 ND->getDeclContext()->getRedeclContext()); 1916 R.setNamingClass(Record); 1917 } 1918 1919 auto *UnderlyingND = ND->getUnderlyingDecl(); 1920 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1921 isa<FunctionTemplateDecl>(UnderlyingND); 1922 // FIXME: If we ended up with a typo for a type name or 1923 // Objective-C class name, we're in trouble because the parser 1924 // is in the wrong place to recover. Suggest the typo 1925 // correction, but don't make it a fix-it since we're not going 1926 // to recover well anyway. 1927 AcceptableWithoutRecovery = 1928 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1929 } else { 1930 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1931 // because we aren't able to recover. 1932 AcceptableWithoutRecovery = true; 1933 } 1934 1935 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1936 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1937 ? diag::note_implicit_param_decl 1938 : diag::note_previous_decl; 1939 if (SS.isEmpty()) 1940 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1941 PDiag(NoteID), AcceptableWithRecovery); 1942 else 1943 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1944 << Name << computeDeclContext(SS, false) 1945 << DroppedSpecifier << SS.getRange(), 1946 PDiag(NoteID), AcceptableWithRecovery); 1947 1948 // Tell the callee whether to try to recover. 1949 return !AcceptableWithRecovery; 1950 } 1951 } 1952 R.clear(); 1953 1954 // Emit a special diagnostic for failed member lookups. 1955 // FIXME: computing the declaration context might fail here (?) 1956 if (!SS.isEmpty()) { 1957 Diag(R.getNameLoc(), diag::err_no_member) 1958 << Name << computeDeclContext(SS, false) 1959 << SS.getRange(); 1960 return true; 1961 } 1962 1963 // Give up, we can't recover. 1964 Diag(R.getNameLoc(), diagnostic) << Name; 1965 return true; 1966 } 1967 1968 /// In Microsoft mode, if we are inside a template class whose parent class has 1969 /// dependent base classes, and we can't resolve an unqualified identifier, then 1970 /// assume the identifier is a member of a dependent base class. We can only 1971 /// recover successfully in static methods, instance methods, and other contexts 1972 /// where 'this' is available. This doesn't precisely match MSVC's 1973 /// instantiation model, but it's close enough. 1974 static Expr * 1975 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1976 DeclarationNameInfo &NameInfo, 1977 SourceLocation TemplateKWLoc, 1978 const TemplateArgumentListInfo *TemplateArgs) { 1979 // Only try to recover from lookup into dependent bases in static methods or 1980 // contexts where 'this' is available. 1981 QualType ThisType = S.getCurrentThisType(); 1982 const CXXRecordDecl *RD = nullptr; 1983 if (!ThisType.isNull()) 1984 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1985 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1986 RD = MD->getParent(); 1987 if (!RD || !RD->hasAnyDependentBases()) 1988 return nullptr; 1989 1990 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1991 // is available, suggest inserting 'this->' as a fixit. 1992 SourceLocation Loc = NameInfo.getLoc(); 1993 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1994 DB << NameInfo.getName() << RD; 1995 1996 if (!ThisType.isNull()) { 1997 DB << FixItHint::CreateInsertion(Loc, "this->"); 1998 return CXXDependentScopeMemberExpr::Create( 1999 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2000 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2001 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2002 } 2003 2004 // Synthesize a fake NNS that points to the derived class. This will 2005 // perform name lookup during template instantiation. 2006 CXXScopeSpec SS; 2007 auto *NNS = 2008 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2009 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2010 return DependentScopeDeclRefExpr::Create( 2011 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2012 TemplateArgs); 2013 } 2014 2015 ExprResult 2016 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2017 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2018 bool HasTrailingLParen, bool IsAddressOfOperand, 2019 std::unique_ptr<CorrectionCandidateCallback> CCC, 2020 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2021 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2022 "cannot be direct & operand and have a trailing lparen"); 2023 if (SS.isInvalid()) 2024 return ExprError(); 2025 2026 TemplateArgumentListInfo TemplateArgsBuffer; 2027 2028 // Decompose the UnqualifiedId into the following data. 2029 DeclarationNameInfo NameInfo; 2030 const TemplateArgumentListInfo *TemplateArgs; 2031 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2032 2033 DeclarationName Name = NameInfo.getName(); 2034 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2035 SourceLocation NameLoc = NameInfo.getLoc(); 2036 2037 if (II && II->isEditorPlaceholder()) { 2038 // FIXME: When typed placeholders are supported we can create a typed 2039 // placeholder expression node. 2040 return ExprError(); 2041 } 2042 2043 // C++ [temp.dep.expr]p3: 2044 // An id-expression is type-dependent if it contains: 2045 // -- an identifier that was declared with a dependent type, 2046 // (note: handled after lookup) 2047 // -- a template-id that is dependent, 2048 // (note: handled in BuildTemplateIdExpr) 2049 // -- a conversion-function-id that specifies a dependent type, 2050 // -- a nested-name-specifier that contains a class-name that 2051 // names a dependent type. 2052 // Determine whether this is a member of an unknown specialization; 2053 // we need to handle these differently. 2054 bool DependentID = false; 2055 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2056 Name.getCXXNameType()->isDependentType()) { 2057 DependentID = true; 2058 } else if (SS.isSet()) { 2059 if (DeclContext *DC = computeDeclContext(SS, false)) { 2060 if (RequireCompleteDeclContext(SS, DC)) 2061 return ExprError(); 2062 } else { 2063 DependentID = true; 2064 } 2065 } 2066 2067 if (DependentID) 2068 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2069 IsAddressOfOperand, TemplateArgs); 2070 2071 // Perform the required lookup. 2072 LookupResult R(*this, NameInfo, 2073 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2074 ? LookupObjCImplicitSelfParam 2075 : LookupOrdinaryName); 2076 if (TemplateArgs) { 2077 // Lookup the template name again to correctly establish the context in 2078 // which it was found. This is really unfortunate as we already did the 2079 // lookup to determine that it was a template name in the first place. If 2080 // this becomes a performance hit, we can work harder to preserve those 2081 // results until we get here but it's likely not worth it. 2082 bool MemberOfUnknownSpecialization; 2083 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2084 MemberOfUnknownSpecialization); 2085 2086 if (MemberOfUnknownSpecialization || 2087 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2088 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2089 IsAddressOfOperand, TemplateArgs); 2090 } else { 2091 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2092 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2093 2094 // If the result might be in a dependent base class, this is a dependent 2095 // id-expression. 2096 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2097 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2098 IsAddressOfOperand, TemplateArgs); 2099 2100 // If this reference is in an Objective-C method, then we need to do 2101 // some special Objective-C lookup, too. 2102 if (IvarLookupFollowUp) { 2103 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2104 if (E.isInvalid()) 2105 return ExprError(); 2106 2107 if (Expr *Ex = E.getAs<Expr>()) 2108 return Ex; 2109 } 2110 } 2111 2112 if (R.isAmbiguous()) 2113 return ExprError(); 2114 2115 // This could be an implicitly declared function reference (legal in C90, 2116 // extension in C99, forbidden in C++). 2117 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2118 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2119 if (D) R.addDecl(D); 2120 } 2121 2122 // Determine whether this name might be a candidate for 2123 // argument-dependent lookup. 2124 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2125 2126 if (R.empty() && !ADL) { 2127 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2128 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2129 TemplateKWLoc, TemplateArgs)) 2130 return E; 2131 } 2132 2133 // Don't diagnose an empty lookup for inline assembly. 2134 if (IsInlineAsmIdentifier) 2135 return ExprError(); 2136 2137 // If this name wasn't predeclared and if this is not a function 2138 // call, diagnose the problem. 2139 TypoExpr *TE = nullptr; 2140 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2141 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2142 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2143 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2144 "Typo correction callback misconfigured"); 2145 if (CCC) { 2146 // Make sure the callback knows what the typo being diagnosed is. 2147 CCC->setTypoName(II); 2148 if (SS.isValid()) 2149 CCC->setTypoNNS(SS.getScopeRep()); 2150 } 2151 if (DiagnoseEmptyLookup(S, SS, R, 2152 CCC ? std::move(CCC) : std::move(DefaultValidator), 2153 nullptr, None, &TE)) { 2154 if (TE && KeywordReplacement) { 2155 auto &State = getTypoExprState(TE); 2156 auto BestTC = State.Consumer->getNextCorrection(); 2157 if (BestTC.isKeyword()) { 2158 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2159 if (State.DiagHandler) 2160 State.DiagHandler(BestTC); 2161 KeywordReplacement->startToken(); 2162 KeywordReplacement->setKind(II->getTokenID()); 2163 KeywordReplacement->setIdentifierInfo(II); 2164 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2165 // Clean up the state associated with the TypoExpr, since it has 2166 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2167 clearDelayedTypo(TE); 2168 // Signal that a correction to a keyword was performed by returning a 2169 // valid-but-null ExprResult. 2170 return (Expr*)nullptr; 2171 } 2172 State.Consumer->resetCorrectionStream(); 2173 } 2174 return TE ? TE : ExprError(); 2175 } 2176 2177 assert(!R.empty() && 2178 "DiagnoseEmptyLookup returned false but added no results"); 2179 2180 // If we found an Objective-C instance variable, let 2181 // LookupInObjCMethod build the appropriate expression to 2182 // reference the ivar. 2183 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2184 R.clear(); 2185 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2186 // In a hopelessly buggy code, Objective-C instance variable 2187 // lookup fails and no expression will be built to reference it. 2188 if (!E.isInvalid() && !E.get()) 2189 return ExprError(); 2190 return E; 2191 } 2192 } 2193 2194 // This is guaranteed from this point on. 2195 assert(!R.empty() || ADL); 2196 2197 // Check whether this might be a C++ implicit instance member access. 2198 // C++ [class.mfct.non-static]p3: 2199 // When an id-expression that is not part of a class member access 2200 // syntax and not used to form a pointer to member is used in the 2201 // body of a non-static member function of class X, if name lookup 2202 // resolves the name in the id-expression to a non-static non-type 2203 // member of some class C, the id-expression is transformed into a 2204 // class member access expression using (*this) as the 2205 // postfix-expression to the left of the . operator. 2206 // 2207 // But we don't actually need to do this for '&' operands if R 2208 // resolved to a function or overloaded function set, because the 2209 // expression is ill-formed if it actually works out to be a 2210 // non-static member function: 2211 // 2212 // C++ [expr.ref]p4: 2213 // Otherwise, if E1.E2 refers to a non-static member function. . . 2214 // [t]he expression can be used only as the left-hand operand of a 2215 // member function call. 2216 // 2217 // There are other safeguards against such uses, but it's important 2218 // to get this right here so that we don't end up making a 2219 // spuriously dependent expression if we're inside a dependent 2220 // instance method. 2221 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2222 bool MightBeImplicitMember; 2223 if (!IsAddressOfOperand) 2224 MightBeImplicitMember = true; 2225 else if (!SS.isEmpty()) 2226 MightBeImplicitMember = false; 2227 else if (R.isOverloadedResult()) 2228 MightBeImplicitMember = false; 2229 else if (R.isUnresolvableResult()) 2230 MightBeImplicitMember = true; 2231 else 2232 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2233 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2234 isa<MSPropertyDecl>(R.getFoundDecl()); 2235 2236 if (MightBeImplicitMember) 2237 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2238 R, TemplateArgs, S); 2239 } 2240 2241 if (TemplateArgs || TemplateKWLoc.isValid()) { 2242 2243 // In C++1y, if this is a variable template id, then check it 2244 // in BuildTemplateIdExpr(). 2245 // The single lookup result must be a variable template declaration. 2246 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2247 Id.TemplateId->Kind == TNK_Var_template) { 2248 assert(R.getAsSingle<VarTemplateDecl>() && 2249 "There should only be one declaration found."); 2250 } 2251 2252 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2253 } 2254 2255 return BuildDeclarationNameExpr(SS, R, ADL); 2256 } 2257 2258 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2259 /// declaration name, generally during template instantiation. 2260 /// There's a large number of things which don't need to be done along 2261 /// this path. 2262 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2263 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2264 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2265 DeclContext *DC = computeDeclContext(SS, false); 2266 if (!DC) 2267 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2268 NameInfo, /*TemplateArgs=*/nullptr); 2269 2270 if (RequireCompleteDeclContext(SS, DC)) 2271 return ExprError(); 2272 2273 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2274 LookupQualifiedName(R, DC); 2275 2276 if (R.isAmbiguous()) 2277 return ExprError(); 2278 2279 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2280 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2281 NameInfo, /*TemplateArgs=*/nullptr); 2282 2283 if (R.empty()) { 2284 Diag(NameInfo.getLoc(), diag::err_no_member) 2285 << NameInfo.getName() << DC << SS.getRange(); 2286 return ExprError(); 2287 } 2288 2289 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2290 // Diagnose a missing typename if this resolved unambiguously to a type in 2291 // a dependent context. If we can recover with a type, downgrade this to 2292 // a warning in Microsoft compatibility mode. 2293 unsigned DiagID = diag::err_typename_missing; 2294 if (RecoveryTSI && getLangOpts().MSVCCompat) 2295 DiagID = diag::ext_typename_missing; 2296 SourceLocation Loc = SS.getBeginLoc(); 2297 auto D = Diag(Loc, DiagID); 2298 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2299 << SourceRange(Loc, NameInfo.getEndLoc()); 2300 2301 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2302 // context. 2303 if (!RecoveryTSI) 2304 return ExprError(); 2305 2306 // Only issue the fixit if we're prepared to recover. 2307 D << FixItHint::CreateInsertion(Loc, "typename "); 2308 2309 // Recover by pretending this was an elaborated type. 2310 QualType Ty = Context.getTypeDeclType(TD); 2311 TypeLocBuilder TLB; 2312 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2313 2314 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2315 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2316 QTL.setElaboratedKeywordLoc(SourceLocation()); 2317 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2318 2319 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2320 2321 return ExprEmpty(); 2322 } 2323 2324 // Defend against this resolving to an implicit member access. We usually 2325 // won't get here if this might be a legitimate a class member (we end up in 2326 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2327 // a pointer-to-member or in an unevaluated context in C++11. 2328 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2329 return BuildPossibleImplicitMemberExpr(SS, 2330 /*TemplateKWLoc=*/SourceLocation(), 2331 R, /*TemplateArgs=*/nullptr, S); 2332 2333 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2334 } 2335 2336 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2337 /// detected that we're currently inside an ObjC method. Perform some 2338 /// additional lookup. 2339 /// 2340 /// Ideally, most of this would be done by lookup, but there's 2341 /// actually quite a lot of extra work involved. 2342 /// 2343 /// Returns a null sentinel to indicate trivial success. 2344 ExprResult 2345 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2346 IdentifierInfo *II, bool AllowBuiltinCreation) { 2347 SourceLocation Loc = Lookup.getNameLoc(); 2348 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2349 2350 // Check for error condition which is already reported. 2351 if (!CurMethod) 2352 return ExprError(); 2353 2354 // There are two cases to handle here. 1) scoped lookup could have failed, 2355 // in which case we should look for an ivar. 2) scoped lookup could have 2356 // found a decl, but that decl is outside the current instance method (i.e. 2357 // a global variable). In these two cases, we do a lookup for an ivar with 2358 // this name, if the lookup sucedes, we replace it our current decl. 2359 2360 // If we're in a class method, we don't normally want to look for 2361 // ivars. But if we don't find anything else, and there's an 2362 // ivar, that's an error. 2363 bool IsClassMethod = CurMethod->isClassMethod(); 2364 2365 bool LookForIvars; 2366 if (Lookup.empty()) 2367 LookForIvars = true; 2368 else if (IsClassMethod) 2369 LookForIvars = false; 2370 else 2371 LookForIvars = (Lookup.isSingleResult() && 2372 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2373 ObjCInterfaceDecl *IFace = nullptr; 2374 if (LookForIvars) { 2375 IFace = CurMethod->getClassInterface(); 2376 ObjCInterfaceDecl *ClassDeclared; 2377 ObjCIvarDecl *IV = nullptr; 2378 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2379 // Diagnose using an ivar in a class method. 2380 if (IsClassMethod) 2381 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2382 << IV->getDeclName()); 2383 2384 // If we're referencing an invalid decl, just return this as a silent 2385 // error node. The error diagnostic was already emitted on the decl. 2386 if (IV->isInvalidDecl()) 2387 return ExprError(); 2388 2389 // Check if referencing a field with __attribute__((deprecated)). 2390 if (DiagnoseUseOfDecl(IV, Loc)) 2391 return ExprError(); 2392 2393 // Diagnose the use of an ivar outside of the declaring class. 2394 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2395 !declaresSameEntity(ClassDeclared, IFace) && 2396 !getLangOpts().DebuggerSupport) 2397 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2398 2399 // FIXME: This should use a new expr for a direct reference, don't 2400 // turn this into Self->ivar, just return a BareIVarExpr or something. 2401 IdentifierInfo &II = Context.Idents.get("self"); 2402 UnqualifiedId SelfName; 2403 SelfName.setIdentifier(&II, SourceLocation()); 2404 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2405 CXXScopeSpec SelfScopeSpec; 2406 SourceLocation TemplateKWLoc; 2407 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2408 SelfName, false, false); 2409 if (SelfExpr.isInvalid()) 2410 return ExprError(); 2411 2412 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2413 if (SelfExpr.isInvalid()) 2414 return ExprError(); 2415 2416 MarkAnyDeclReferenced(Loc, IV, true); 2417 2418 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2419 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2420 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2421 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2422 2423 ObjCIvarRefExpr *Result = new (Context) 2424 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2425 IV->getLocation(), SelfExpr.get(), true, true); 2426 2427 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2428 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2429 recordUseOfEvaluatedWeak(Result); 2430 } 2431 if (getLangOpts().ObjCAutoRefCount) { 2432 if (CurContext->isClosure()) 2433 Diag(Loc, diag::warn_implicitly_retains_self) 2434 << FixItHint::CreateInsertion(Loc, "self->"); 2435 } 2436 2437 return Result; 2438 } 2439 } else if (CurMethod->isInstanceMethod()) { 2440 // We should warn if a local variable hides an ivar. 2441 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2442 ObjCInterfaceDecl *ClassDeclared; 2443 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2444 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2445 declaresSameEntity(IFace, ClassDeclared)) 2446 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2447 } 2448 } 2449 } else if (Lookup.isSingleResult() && 2450 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2451 // If accessing a stand-alone ivar in a class method, this is an error. 2452 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2453 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2454 << IV->getDeclName()); 2455 } 2456 2457 if (Lookup.empty() && II && AllowBuiltinCreation) { 2458 // FIXME. Consolidate this with similar code in LookupName. 2459 if (unsigned BuiltinID = II->getBuiltinID()) { 2460 if (!(getLangOpts().CPlusPlus && 2461 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2462 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2463 S, Lookup.isForRedeclaration(), 2464 Lookup.getNameLoc()); 2465 if (D) Lookup.addDecl(D); 2466 } 2467 } 2468 } 2469 // Sentinel value saying that we didn't do anything special. 2470 return ExprResult((Expr *)nullptr); 2471 } 2472 2473 /// \brief Cast a base object to a member's actual type. 2474 /// 2475 /// Logically this happens in three phases: 2476 /// 2477 /// * First we cast from the base type to the naming class. 2478 /// The naming class is the class into which we were looking 2479 /// when we found the member; it's the qualifier type if a 2480 /// qualifier was provided, and otherwise it's the base type. 2481 /// 2482 /// * Next we cast from the naming class to the declaring class. 2483 /// If the member we found was brought into a class's scope by 2484 /// a using declaration, this is that class; otherwise it's 2485 /// the class declaring the member. 2486 /// 2487 /// * Finally we cast from the declaring class to the "true" 2488 /// declaring class of the member. This conversion does not 2489 /// obey access control. 2490 ExprResult 2491 Sema::PerformObjectMemberConversion(Expr *From, 2492 NestedNameSpecifier *Qualifier, 2493 NamedDecl *FoundDecl, 2494 NamedDecl *Member) { 2495 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2496 if (!RD) 2497 return From; 2498 2499 QualType DestRecordType; 2500 QualType DestType; 2501 QualType FromRecordType; 2502 QualType FromType = From->getType(); 2503 bool PointerConversions = false; 2504 if (isa<FieldDecl>(Member)) { 2505 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2506 2507 if (FromType->getAs<PointerType>()) { 2508 DestType = Context.getPointerType(DestRecordType); 2509 FromRecordType = FromType->getPointeeType(); 2510 PointerConversions = true; 2511 } else { 2512 DestType = DestRecordType; 2513 FromRecordType = FromType; 2514 } 2515 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2516 if (Method->isStatic()) 2517 return From; 2518 2519 DestType = Method->getThisType(Context); 2520 DestRecordType = DestType->getPointeeType(); 2521 2522 if (FromType->getAs<PointerType>()) { 2523 FromRecordType = FromType->getPointeeType(); 2524 PointerConversions = true; 2525 } else { 2526 FromRecordType = FromType; 2527 DestType = DestRecordType; 2528 } 2529 } else { 2530 // No conversion necessary. 2531 return From; 2532 } 2533 2534 if (DestType->isDependentType() || FromType->isDependentType()) 2535 return From; 2536 2537 // If the unqualified types are the same, no conversion is necessary. 2538 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2539 return From; 2540 2541 SourceRange FromRange = From->getSourceRange(); 2542 SourceLocation FromLoc = FromRange.getBegin(); 2543 2544 ExprValueKind VK = From->getValueKind(); 2545 2546 // C++ [class.member.lookup]p8: 2547 // [...] Ambiguities can often be resolved by qualifying a name with its 2548 // class name. 2549 // 2550 // If the member was a qualified name and the qualified referred to a 2551 // specific base subobject type, we'll cast to that intermediate type 2552 // first and then to the object in which the member is declared. That allows 2553 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2554 // 2555 // class Base { public: int x; }; 2556 // class Derived1 : public Base { }; 2557 // class Derived2 : public Base { }; 2558 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2559 // 2560 // void VeryDerived::f() { 2561 // x = 17; // error: ambiguous base subobjects 2562 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2563 // } 2564 if (Qualifier && Qualifier->getAsType()) { 2565 QualType QType = QualType(Qualifier->getAsType(), 0); 2566 assert(QType->isRecordType() && "lookup done with non-record type"); 2567 2568 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2569 2570 // In C++98, the qualifier type doesn't actually have to be a base 2571 // type of the object type, in which case we just ignore it. 2572 // Otherwise build the appropriate casts. 2573 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2574 CXXCastPath BasePath; 2575 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2576 FromLoc, FromRange, &BasePath)) 2577 return ExprError(); 2578 2579 if (PointerConversions) 2580 QType = Context.getPointerType(QType); 2581 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2582 VK, &BasePath).get(); 2583 2584 FromType = QType; 2585 FromRecordType = QRecordType; 2586 2587 // If the qualifier type was the same as the destination type, 2588 // we're done. 2589 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2590 return From; 2591 } 2592 } 2593 2594 bool IgnoreAccess = false; 2595 2596 // If we actually found the member through a using declaration, cast 2597 // down to the using declaration's type. 2598 // 2599 // Pointer equality is fine here because only one declaration of a 2600 // class ever has member declarations. 2601 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2602 assert(isa<UsingShadowDecl>(FoundDecl)); 2603 QualType URecordType = Context.getTypeDeclType( 2604 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2605 2606 // We only need to do this if the naming-class to declaring-class 2607 // conversion is non-trivial. 2608 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2609 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2610 CXXCastPath BasePath; 2611 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2612 FromLoc, FromRange, &BasePath)) 2613 return ExprError(); 2614 2615 QualType UType = URecordType; 2616 if (PointerConversions) 2617 UType = Context.getPointerType(UType); 2618 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2619 VK, &BasePath).get(); 2620 FromType = UType; 2621 FromRecordType = URecordType; 2622 } 2623 2624 // We don't do access control for the conversion from the 2625 // declaring class to the true declaring class. 2626 IgnoreAccess = true; 2627 } 2628 2629 CXXCastPath BasePath; 2630 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2631 FromLoc, FromRange, &BasePath, 2632 IgnoreAccess)) 2633 return ExprError(); 2634 2635 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2636 VK, &BasePath); 2637 } 2638 2639 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2640 const LookupResult &R, 2641 bool HasTrailingLParen) { 2642 // Only when used directly as the postfix-expression of a call. 2643 if (!HasTrailingLParen) 2644 return false; 2645 2646 // Never if a scope specifier was provided. 2647 if (SS.isSet()) 2648 return false; 2649 2650 // Only in C++ or ObjC++. 2651 if (!getLangOpts().CPlusPlus) 2652 return false; 2653 2654 // Turn off ADL when we find certain kinds of declarations during 2655 // normal lookup: 2656 for (NamedDecl *D : R) { 2657 // C++0x [basic.lookup.argdep]p3: 2658 // -- a declaration of a class member 2659 // Since using decls preserve this property, we check this on the 2660 // original decl. 2661 if (D->isCXXClassMember()) 2662 return false; 2663 2664 // C++0x [basic.lookup.argdep]p3: 2665 // -- a block-scope function declaration that is not a 2666 // using-declaration 2667 // NOTE: we also trigger this for function templates (in fact, we 2668 // don't check the decl type at all, since all other decl types 2669 // turn off ADL anyway). 2670 if (isa<UsingShadowDecl>(D)) 2671 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2672 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2673 return false; 2674 2675 // C++0x [basic.lookup.argdep]p3: 2676 // -- a declaration that is neither a function or a function 2677 // template 2678 // And also for builtin functions. 2679 if (isa<FunctionDecl>(D)) { 2680 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2681 2682 // But also builtin functions. 2683 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2684 return false; 2685 } else if (!isa<FunctionTemplateDecl>(D)) 2686 return false; 2687 } 2688 2689 return true; 2690 } 2691 2692 2693 /// Diagnoses obvious problems with the use of the given declaration 2694 /// as an expression. This is only actually called for lookups that 2695 /// were not overloaded, and it doesn't promise that the declaration 2696 /// will in fact be used. 2697 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2698 if (D->isInvalidDecl()) 2699 return true; 2700 2701 if (isa<TypedefNameDecl>(D)) { 2702 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2703 return true; 2704 } 2705 2706 if (isa<ObjCInterfaceDecl>(D)) { 2707 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2708 return true; 2709 } 2710 2711 if (isa<NamespaceDecl>(D)) { 2712 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2713 return true; 2714 } 2715 2716 return false; 2717 } 2718 2719 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2720 LookupResult &R, bool NeedsADL, 2721 bool AcceptInvalidDecl) { 2722 // If this is a single, fully-resolved result and we don't need ADL, 2723 // just build an ordinary singleton decl ref. 2724 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2725 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2726 R.getRepresentativeDecl(), nullptr, 2727 AcceptInvalidDecl); 2728 2729 // We only need to check the declaration if there's exactly one 2730 // result, because in the overloaded case the results can only be 2731 // functions and function templates. 2732 if (R.isSingleResult() && 2733 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2734 return ExprError(); 2735 2736 // Otherwise, just build an unresolved lookup expression. Suppress 2737 // any lookup-related diagnostics; we'll hash these out later, when 2738 // we've picked a target. 2739 R.suppressDiagnostics(); 2740 2741 UnresolvedLookupExpr *ULE 2742 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2743 SS.getWithLocInContext(Context), 2744 R.getLookupNameInfo(), 2745 NeedsADL, R.isOverloadedResult(), 2746 R.begin(), R.end()); 2747 2748 return ULE; 2749 } 2750 2751 static void 2752 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2753 ValueDecl *var, DeclContext *DC); 2754 2755 /// \brief Complete semantic analysis for a reference to the given declaration. 2756 ExprResult Sema::BuildDeclarationNameExpr( 2757 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2758 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2759 bool AcceptInvalidDecl) { 2760 assert(D && "Cannot refer to a NULL declaration"); 2761 assert(!isa<FunctionTemplateDecl>(D) && 2762 "Cannot refer unambiguously to a function template"); 2763 2764 SourceLocation Loc = NameInfo.getLoc(); 2765 if (CheckDeclInExpr(*this, Loc, D)) 2766 return ExprError(); 2767 2768 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2769 // Specifically diagnose references to class templates that are missing 2770 // a template argument list. 2771 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2772 << Template << SS.getRange(); 2773 Diag(Template->getLocation(), diag::note_template_decl_here); 2774 return ExprError(); 2775 } 2776 2777 // Make sure that we're referring to a value. 2778 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2779 if (!VD) { 2780 Diag(Loc, diag::err_ref_non_value) 2781 << D << SS.getRange(); 2782 Diag(D->getLocation(), diag::note_declared_at); 2783 return ExprError(); 2784 } 2785 2786 // Check whether this declaration can be used. Note that we suppress 2787 // this check when we're going to perform argument-dependent lookup 2788 // on this function name, because this might not be the function 2789 // that overload resolution actually selects. 2790 if (DiagnoseUseOfDecl(VD, Loc)) 2791 return ExprError(); 2792 2793 // Only create DeclRefExpr's for valid Decl's. 2794 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2795 return ExprError(); 2796 2797 // Handle members of anonymous structs and unions. If we got here, 2798 // and the reference is to a class member indirect field, then this 2799 // must be the subject of a pointer-to-member expression. 2800 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2801 if (!indirectField->isCXXClassMember()) 2802 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2803 indirectField); 2804 2805 { 2806 QualType type = VD->getType(); 2807 if (type.isNull()) 2808 return ExprError(); 2809 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2810 // C++ [except.spec]p17: 2811 // An exception-specification is considered to be needed when: 2812 // - in an expression, the function is the unique lookup result or 2813 // the selected member of a set of overloaded functions. 2814 ResolveExceptionSpec(Loc, FPT); 2815 type = VD->getType(); 2816 } 2817 ExprValueKind valueKind = VK_RValue; 2818 2819 switch (D->getKind()) { 2820 // Ignore all the non-ValueDecl kinds. 2821 #define ABSTRACT_DECL(kind) 2822 #define VALUE(type, base) 2823 #define DECL(type, base) \ 2824 case Decl::type: 2825 #include "clang/AST/DeclNodes.inc" 2826 llvm_unreachable("invalid value decl kind"); 2827 2828 // These shouldn't make it here. 2829 case Decl::ObjCAtDefsField: 2830 case Decl::ObjCIvar: 2831 llvm_unreachable("forming non-member reference to ivar?"); 2832 2833 // Enum constants are always r-values and never references. 2834 // Unresolved using declarations are dependent. 2835 case Decl::EnumConstant: 2836 case Decl::UnresolvedUsingValue: 2837 case Decl::OMPDeclareReduction: 2838 valueKind = VK_RValue; 2839 break; 2840 2841 // Fields and indirect fields that got here must be for 2842 // pointer-to-member expressions; we just call them l-values for 2843 // internal consistency, because this subexpression doesn't really 2844 // exist in the high-level semantics. 2845 case Decl::Field: 2846 case Decl::IndirectField: 2847 assert(getLangOpts().CPlusPlus && 2848 "building reference to field in C?"); 2849 2850 // These can't have reference type in well-formed programs, but 2851 // for internal consistency we do this anyway. 2852 type = type.getNonReferenceType(); 2853 valueKind = VK_LValue; 2854 break; 2855 2856 // Non-type template parameters are either l-values or r-values 2857 // depending on the type. 2858 case Decl::NonTypeTemplateParm: { 2859 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2860 type = reftype->getPointeeType(); 2861 valueKind = VK_LValue; // even if the parameter is an r-value reference 2862 break; 2863 } 2864 2865 // For non-references, we need to strip qualifiers just in case 2866 // the template parameter was declared as 'const int' or whatever. 2867 valueKind = VK_RValue; 2868 type = type.getUnqualifiedType(); 2869 break; 2870 } 2871 2872 case Decl::Var: 2873 case Decl::VarTemplateSpecialization: 2874 case Decl::VarTemplatePartialSpecialization: 2875 case Decl::Decomposition: 2876 case Decl::OMPCapturedExpr: 2877 // In C, "extern void blah;" is valid and is an r-value. 2878 if (!getLangOpts().CPlusPlus && 2879 !type.hasQualifiers() && 2880 type->isVoidType()) { 2881 valueKind = VK_RValue; 2882 break; 2883 } 2884 LLVM_FALLTHROUGH; 2885 2886 case Decl::ImplicitParam: 2887 case Decl::ParmVar: { 2888 // These are always l-values. 2889 valueKind = VK_LValue; 2890 type = type.getNonReferenceType(); 2891 2892 // FIXME: Does the addition of const really only apply in 2893 // potentially-evaluated contexts? Since the variable isn't actually 2894 // captured in an unevaluated context, it seems that the answer is no. 2895 if (!isUnevaluatedContext()) { 2896 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2897 if (!CapturedType.isNull()) 2898 type = CapturedType; 2899 } 2900 2901 break; 2902 } 2903 2904 case Decl::Binding: { 2905 // These are always lvalues. 2906 valueKind = VK_LValue; 2907 type = type.getNonReferenceType(); 2908 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2909 // decides how that's supposed to work. 2910 auto *BD = cast<BindingDecl>(VD); 2911 if (BD->getDeclContext()->isFunctionOrMethod() && 2912 BD->getDeclContext() != CurContext) 2913 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2914 break; 2915 } 2916 2917 case Decl::Function: { 2918 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2919 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2920 type = Context.BuiltinFnTy; 2921 valueKind = VK_RValue; 2922 break; 2923 } 2924 } 2925 2926 const FunctionType *fty = type->castAs<FunctionType>(); 2927 2928 // If we're referring to a function with an __unknown_anytype 2929 // result type, make the entire expression __unknown_anytype. 2930 if (fty->getReturnType() == Context.UnknownAnyTy) { 2931 type = Context.UnknownAnyTy; 2932 valueKind = VK_RValue; 2933 break; 2934 } 2935 2936 // Functions are l-values in C++. 2937 if (getLangOpts().CPlusPlus) { 2938 valueKind = VK_LValue; 2939 break; 2940 } 2941 2942 // C99 DR 316 says that, if a function type comes from a 2943 // function definition (without a prototype), that type is only 2944 // used for checking compatibility. Therefore, when referencing 2945 // the function, we pretend that we don't have the full function 2946 // type. 2947 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2948 isa<FunctionProtoType>(fty)) 2949 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2950 fty->getExtInfo()); 2951 2952 // Functions are r-values in C. 2953 valueKind = VK_RValue; 2954 break; 2955 } 2956 2957 case Decl::CXXDeductionGuide: 2958 llvm_unreachable("building reference to deduction guide"); 2959 2960 case Decl::MSProperty: 2961 valueKind = VK_LValue; 2962 break; 2963 2964 case Decl::CXXMethod: 2965 // If we're referring to a method with an __unknown_anytype 2966 // result type, make the entire expression __unknown_anytype. 2967 // This should only be possible with a type written directly. 2968 if (const FunctionProtoType *proto 2969 = dyn_cast<FunctionProtoType>(VD->getType())) 2970 if (proto->getReturnType() == Context.UnknownAnyTy) { 2971 type = Context.UnknownAnyTy; 2972 valueKind = VK_RValue; 2973 break; 2974 } 2975 2976 // C++ methods are l-values if static, r-values if non-static. 2977 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2978 valueKind = VK_LValue; 2979 break; 2980 } 2981 LLVM_FALLTHROUGH; 2982 2983 case Decl::CXXConversion: 2984 case Decl::CXXDestructor: 2985 case Decl::CXXConstructor: 2986 valueKind = VK_RValue; 2987 break; 2988 } 2989 2990 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2991 TemplateArgs); 2992 } 2993 } 2994 2995 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2996 SmallString<32> &Target) { 2997 Target.resize(CharByteWidth * (Source.size() + 1)); 2998 char *ResultPtr = &Target[0]; 2999 const llvm::UTF8 *ErrorPtr; 3000 bool success = 3001 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3002 (void)success; 3003 assert(success); 3004 Target.resize(ResultPtr - &Target[0]); 3005 } 3006 3007 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3008 PredefinedExpr::IdentType IT) { 3009 // Pick the current block, lambda, captured statement or function. 3010 Decl *currentDecl = nullptr; 3011 if (const BlockScopeInfo *BSI = getCurBlock()) 3012 currentDecl = BSI->TheDecl; 3013 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3014 currentDecl = LSI->CallOperator; 3015 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3016 currentDecl = CSI->TheCapturedDecl; 3017 else 3018 currentDecl = getCurFunctionOrMethodDecl(); 3019 3020 if (!currentDecl) { 3021 Diag(Loc, diag::ext_predef_outside_function); 3022 currentDecl = Context.getTranslationUnitDecl(); 3023 } 3024 3025 QualType ResTy; 3026 StringLiteral *SL = nullptr; 3027 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3028 ResTy = Context.DependentTy; 3029 else { 3030 // Pre-defined identifiers are of type char[x], where x is the length of 3031 // the string. 3032 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3033 unsigned Length = Str.length(); 3034 3035 llvm::APInt LengthI(32, Length + 1); 3036 if (IT == PredefinedExpr::LFunction) { 3037 ResTy = Context.WideCharTy.withConst(); 3038 SmallString<32> RawChars; 3039 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3040 Str, RawChars); 3041 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3042 /*IndexTypeQuals*/ 0); 3043 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3044 /*Pascal*/ false, ResTy, Loc); 3045 } else { 3046 ResTy = Context.CharTy.withConst(); 3047 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3048 /*IndexTypeQuals*/ 0); 3049 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3050 /*Pascal*/ false, ResTy, Loc); 3051 } 3052 } 3053 3054 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3055 } 3056 3057 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3058 PredefinedExpr::IdentType IT; 3059 3060 switch (Kind) { 3061 default: llvm_unreachable("Unknown simple primary expr!"); 3062 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3063 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3064 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3065 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3066 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3067 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3068 } 3069 3070 return BuildPredefinedExpr(Loc, IT); 3071 } 3072 3073 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3074 SmallString<16> CharBuffer; 3075 bool Invalid = false; 3076 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3077 if (Invalid) 3078 return ExprError(); 3079 3080 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3081 PP, Tok.getKind()); 3082 if (Literal.hadError()) 3083 return ExprError(); 3084 3085 QualType Ty; 3086 if (Literal.isWide()) 3087 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3088 else if (Literal.isUTF16()) 3089 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3090 else if (Literal.isUTF32()) 3091 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3092 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3093 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3094 else 3095 Ty = Context.CharTy; // 'x' -> char in C++ 3096 3097 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3098 if (Literal.isWide()) 3099 Kind = CharacterLiteral::Wide; 3100 else if (Literal.isUTF16()) 3101 Kind = CharacterLiteral::UTF16; 3102 else if (Literal.isUTF32()) 3103 Kind = CharacterLiteral::UTF32; 3104 else if (Literal.isUTF8()) 3105 Kind = CharacterLiteral::UTF8; 3106 3107 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3108 Tok.getLocation()); 3109 3110 if (Literal.getUDSuffix().empty()) 3111 return Lit; 3112 3113 // We're building a user-defined literal. 3114 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3115 SourceLocation UDSuffixLoc = 3116 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3117 3118 // Make sure we're allowed user-defined literals here. 3119 if (!UDLScope) 3120 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3121 3122 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3123 // operator "" X (ch) 3124 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3125 Lit, Tok.getLocation()); 3126 } 3127 3128 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3129 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3130 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3131 Context.IntTy, Loc); 3132 } 3133 3134 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3135 QualType Ty, SourceLocation Loc) { 3136 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3137 3138 using llvm::APFloat; 3139 APFloat Val(Format); 3140 3141 APFloat::opStatus result = Literal.GetFloatValue(Val); 3142 3143 // Overflow is always an error, but underflow is only an error if 3144 // we underflowed to zero (APFloat reports denormals as underflow). 3145 if ((result & APFloat::opOverflow) || 3146 ((result & APFloat::opUnderflow) && Val.isZero())) { 3147 unsigned diagnostic; 3148 SmallString<20> buffer; 3149 if (result & APFloat::opOverflow) { 3150 diagnostic = diag::warn_float_overflow; 3151 APFloat::getLargest(Format).toString(buffer); 3152 } else { 3153 diagnostic = diag::warn_float_underflow; 3154 APFloat::getSmallest(Format).toString(buffer); 3155 } 3156 3157 S.Diag(Loc, diagnostic) 3158 << Ty 3159 << StringRef(buffer.data(), buffer.size()); 3160 } 3161 3162 bool isExact = (result == APFloat::opOK); 3163 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3164 } 3165 3166 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3167 assert(E && "Invalid expression"); 3168 3169 if (E->isValueDependent()) 3170 return false; 3171 3172 QualType QT = E->getType(); 3173 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3174 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3175 return true; 3176 } 3177 3178 llvm::APSInt ValueAPS; 3179 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3180 3181 if (R.isInvalid()) 3182 return true; 3183 3184 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3185 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3186 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3187 << ValueAPS.toString(10) << ValueIsPositive; 3188 return true; 3189 } 3190 3191 return false; 3192 } 3193 3194 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3195 // Fast path for a single digit (which is quite common). A single digit 3196 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3197 if (Tok.getLength() == 1) { 3198 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3199 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3200 } 3201 3202 SmallString<128> SpellingBuffer; 3203 // NumericLiteralParser wants to overread by one character. Add padding to 3204 // the buffer in case the token is copied to the buffer. If getSpelling() 3205 // returns a StringRef to the memory buffer, it should have a null char at 3206 // the EOF, so it is also safe. 3207 SpellingBuffer.resize(Tok.getLength() + 1); 3208 3209 // Get the spelling of the token, which eliminates trigraphs, etc. 3210 bool Invalid = false; 3211 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3212 if (Invalid) 3213 return ExprError(); 3214 3215 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3216 if (Literal.hadError) 3217 return ExprError(); 3218 3219 if (Literal.hasUDSuffix()) { 3220 // We're building a user-defined literal. 3221 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3222 SourceLocation UDSuffixLoc = 3223 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3224 3225 // Make sure we're allowed user-defined literals here. 3226 if (!UDLScope) 3227 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3228 3229 QualType CookedTy; 3230 if (Literal.isFloatingLiteral()) { 3231 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3232 // long double, the literal is treated as a call of the form 3233 // operator "" X (f L) 3234 CookedTy = Context.LongDoubleTy; 3235 } else { 3236 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3237 // unsigned long long, the literal is treated as a call of the form 3238 // operator "" X (n ULL) 3239 CookedTy = Context.UnsignedLongLongTy; 3240 } 3241 3242 DeclarationName OpName = 3243 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3244 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3245 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3246 3247 SourceLocation TokLoc = Tok.getLocation(); 3248 3249 // Perform literal operator lookup to determine if we're building a raw 3250 // literal or a cooked one. 3251 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3252 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3253 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3254 /*AllowStringTemplate*/ false, 3255 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3256 case LOLR_ErrorNoDiagnostic: 3257 // Lookup failure for imaginary constants isn't fatal, there's still the 3258 // GNU extension producing _Complex types. 3259 break; 3260 case LOLR_Error: 3261 return ExprError(); 3262 case LOLR_Cooked: { 3263 Expr *Lit; 3264 if (Literal.isFloatingLiteral()) { 3265 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3266 } else { 3267 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3268 if (Literal.GetIntegerValue(ResultVal)) 3269 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3270 << /* Unsigned */ 1; 3271 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3272 Tok.getLocation()); 3273 } 3274 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3275 } 3276 3277 case LOLR_Raw: { 3278 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3279 // literal is treated as a call of the form 3280 // operator "" X ("n") 3281 unsigned Length = Literal.getUDSuffixOffset(); 3282 QualType StrTy = Context.getConstantArrayType( 3283 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3284 ArrayType::Normal, 0); 3285 Expr *Lit = StringLiteral::Create( 3286 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3287 /*Pascal*/false, StrTy, &TokLoc, 1); 3288 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3289 } 3290 3291 case LOLR_Template: { 3292 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3293 // template), L is treated as a call fo the form 3294 // operator "" X <'c1', 'c2', ... 'ck'>() 3295 // where n is the source character sequence c1 c2 ... ck. 3296 TemplateArgumentListInfo ExplicitArgs; 3297 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3298 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3299 llvm::APSInt Value(CharBits, CharIsUnsigned); 3300 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3301 Value = TokSpelling[I]; 3302 TemplateArgument Arg(Context, Value, Context.CharTy); 3303 TemplateArgumentLocInfo ArgInfo; 3304 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3305 } 3306 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3307 &ExplicitArgs); 3308 } 3309 case LOLR_StringTemplate: 3310 llvm_unreachable("unexpected literal operator lookup result"); 3311 } 3312 } 3313 3314 Expr *Res; 3315 3316 if (Literal.isFloatingLiteral()) { 3317 QualType Ty; 3318 if (Literal.isHalf){ 3319 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3320 Ty = Context.HalfTy; 3321 else { 3322 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3323 return ExprError(); 3324 } 3325 } else if (Literal.isFloat) 3326 Ty = Context.FloatTy; 3327 else if (Literal.isLong) 3328 Ty = Context.LongDoubleTy; 3329 else if (Literal.isFloat16) 3330 Ty = Context.Float16Ty; 3331 else if (Literal.isFloat128) 3332 Ty = Context.Float128Ty; 3333 else 3334 Ty = Context.DoubleTy; 3335 3336 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3337 3338 if (Ty == Context.DoubleTy) { 3339 if (getLangOpts().SinglePrecisionConstants) { 3340 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3341 if (BTy->getKind() != BuiltinType::Float) { 3342 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3343 } 3344 } else if (getLangOpts().OpenCL && 3345 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3346 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3347 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3348 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3349 } 3350 } 3351 } else if (!Literal.isIntegerLiteral()) { 3352 return ExprError(); 3353 } else { 3354 QualType Ty; 3355 3356 // 'long long' is a C99 or C++11 feature. 3357 if (!getLangOpts().C99 && Literal.isLongLong) { 3358 if (getLangOpts().CPlusPlus) 3359 Diag(Tok.getLocation(), 3360 getLangOpts().CPlusPlus11 ? 3361 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3362 else 3363 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3364 } 3365 3366 // Get the value in the widest-possible width. 3367 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3368 llvm::APInt ResultVal(MaxWidth, 0); 3369 3370 if (Literal.GetIntegerValue(ResultVal)) { 3371 // If this value didn't fit into uintmax_t, error and force to ull. 3372 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3373 << /* Unsigned */ 1; 3374 Ty = Context.UnsignedLongLongTy; 3375 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3376 "long long is not intmax_t?"); 3377 } else { 3378 // If this value fits into a ULL, try to figure out what else it fits into 3379 // according to the rules of C99 6.4.4.1p5. 3380 3381 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3382 // be an unsigned int. 3383 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3384 3385 // Check from smallest to largest, picking the smallest type we can. 3386 unsigned Width = 0; 3387 3388 // Microsoft specific integer suffixes are explicitly sized. 3389 if (Literal.MicrosoftInteger) { 3390 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3391 Width = 8; 3392 Ty = Context.CharTy; 3393 } else { 3394 Width = Literal.MicrosoftInteger; 3395 Ty = Context.getIntTypeForBitwidth(Width, 3396 /*Signed=*/!Literal.isUnsigned); 3397 } 3398 } 3399 3400 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3401 // Are int/unsigned possibilities? 3402 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3403 3404 // Does it fit in a unsigned int? 3405 if (ResultVal.isIntN(IntSize)) { 3406 // Does it fit in a signed int? 3407 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3408 Ty = Context.IntTy; 3409 else if (AllowUnsigned) 3410 Ty = Context.UnsignedIntTy; 3411 Width = IntSize; 3412 } 3413 } 3414 3415 // Are long/unsigned long possibilities? 3416 if (Ty.isNull() && !Literal.isLongLong) { 3417 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3418 3419 // Does it fit in a unsigned long? 3420 if (ResultVal.isIntN(LongSize)) { 3421 // Does it fit in a signed long? 3422 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3423 Ty = Context.LongTy; 3424 else if (AllowUnsigned) 3425 Ty = Context.UnsignedLongTy; 3426 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3427 // is compatible. 3428 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3429 const unsigned LongLongSize = 3430 Context.getTargetInfo().getLongLongWidth(); 3431 Diag(Tok.getLocation(), 3432 getLangOpts().CPlusPlus 3433 ? Literal.isLong 3434 ? diag::warn_old_implicitly_unsigned_long_cxx 3435 : /*C++98 UB*/ diag:: 3436 ext_old_implicitly_unsigned_long_cxx 3437 : diag::warn_old_implicitly_unsigned_long) 3438 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3439 : /*will be ill-formed*/ 1); 3440 Ty = Context.UnsignedLongTy; 3441 } 3442 Width = LongSize; 3443 } 3444 } 3445 3446 // Check long long if needed. 3447 if (Ty.isNull()) { 3448 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3449 3450 // Does it fit in a unsigned long long? 3451 if (ResultVal.isIntN(LongLongSize)) { 3452 // Does it fit in a signed long long? 3453 // To be compatible with MSVC, hex integer literals ending with the 3454 // LL or i64 suffix are always signed in Microsoft mode. 3455 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3456 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3457 Ty = Context.LongLongTy; 3458 else if (AllowUnsigned) 3459 Ty = Context.UnsignedLongLongTy; 3460 Width = LongLongSize; 3461 } 3462 } 3463 3464 // If we still couldn't decide a type, we probably have something that 3465 // does not fit in a signed long long, but has no U suffix. 3466 if (Ty.isNull()) { 3467 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3468 Ty = Context.UnsignedLongLongTy; 3469 Width = Context.getTargetInfo().getLongLongWidth(); 3470 } 3471 3472 if (ResultVal.getBitWidth() != Width) 3473 ResultVal = ResultVal.trunc(Width); 3474 } 3475 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3476 } 3477 3478 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3479 if (Literal.isImaginary) { 3480 Res = new (Context) ImaginaryLiteral(Res, 3481 Context.getComplexType(Res->getType())); 3482 3483 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3484 } 3485 return Res; 3486 } 3487 3488 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3489 assert(E && "ActOnParenExpr() missing expr"); 3490 return new (Context) ParenExpr(L, R, E); 3491 } 3492 3493 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3494 SourceLocation Loc, 3495 SourceRange ArgRange) { 3496 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3497 // scalar or vector data type argument..." 3498 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3499 // type (C99 6.2.5p18) or void. 3500 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3501 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3502 << T << ArgRange; 3503 return true; 3504 } 3505 3506 assert((T->isVoidType() || !T->isIncompleteType()) && 3507 "Scalar types should always be complete"); 3508 return false; 3509 } 3510 3511 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3512 SourceLocation Loc, 3513 SourceRange ArgRange, 3514 UnaryExprOrTypeTrait TraitKind) { 3515 // Invalid types must be hard errors for SFINAE in C++. 3516 if (S.LangOpts.CPlusPlus) 3517 return true; 3518 3519 // C99 6.5.3.4p1: 3520 if (T->isFunctionType() && 3521 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3522 // sizeof(function)/alignof(function) is allowed as an extension. 3523 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3524 << TraitKind << ArgRange; 3525 return false; 3526 } 3527 3528 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3529 // this is an error (OpenCL v1.1 s6.3.k) 3530 if (T->isVoidType()) { 3531 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3532 : diag::ext_sizeof_alignof_void_type; 3533 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3534 return false; 3535 } 3536 3537 return true; 3538 } 3539 3540 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3541 SourceLocation Loc, 3542 SourceRange ArgRange, 3543 UnaryExprOrTypeTrait TraitKind) { 3544 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3545 // runtime doesn't allow it. 3546 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3547 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3548 << T << (TraitKind == UETT_SizeOf) 3549 << ArgRange; 3550 return true; 3551 } 3552 3553 return false; 3554 } 3555 3556 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3557 /// pointer type is equal to T) and emit a warning if it is. 3558 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3559 Expr *E) { 3560 // Don't warn if the operation changed the type. 3561 if (T != E->getType()) 3562 return; 3563 3564 // Now look for array decays. 3565 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3566 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3567 return; 3568 3569 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3570 << ICE->getType() 3571 << ICE->getSubExpr()->getType(); 3572 } 3573 3574 /// \brief Check the constraints on expression operands to unary type expression 3575 /// and type traits. 3576 /// 3577 /// Completes any types necessary and validates the constraints on the operand 3578 /// expression. The logic mostly mirrors the type-based overload, but may modify 3579 /// the expression as it completes the type for that expression through template 3580 /// instantiation, etc. 3581 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3582 UnaryExprOrTypeTrait ExprKind) { 3583 QualType ExprTy = E->getType(); 3584 assert(!ExprTy->isReferenceType()); 3585 3586 if (ExprKind == UETT_VecStep) 3587 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3588 E->getSourceRange()); 3589 3590 // Whitelist some types as extensions 3591 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3592 E->getSourceRange(), ExprKind)) 3593 return false; 3594 3595 // 'alignof' applied to an expression only requires the base element type of 3596 // the expression to be complete. 'sizeof' requires the expression's type to 3597 // be complete (and will attempt to complete it if it's an array of unknown 3598 // bound). 3599 if (ExprKind == UETT_AlignOf) { 3600 if (RequireCompleteType(E->getExprLoc(), 3601 Context.getBaseElementType(E->getType()), 3602 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3603 E->getSourceRange())) 3604 return true; 3605 } else { 3606 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3607 ExprKind, E->getSourceRange())) 3608 return true; 3609 } 3610 3611 // Completing the expression's type may have changed it. 3612 ExprTy = E->getType(); 3613 assert(!ExprTy->isReferenceType()); 3614 3615 if (ExprTy->isFunctionType()) { 3616 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3617 << ExprKind << E->getSourceRange(); 3618 return true; 3619 } 3620 3621 // The operand for sizeof and alignof is in an unevaluated expression context, 3622 // so side effects could result in unintended consequences. 3623 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3624 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3625 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3626 3627 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3628 E->getSourceRange(), ExprKind)) 3629 return true; 3630 3631 if (ExprKind == UETT_SizeOf) { 3632 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3633 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3634 QualType OType = PVD->getOriginalType(); 3635 QualType Type = PVD->getType(); 3636 if (Type->isPointerType() && OType->isArrayType()) { 3637 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3638 << Type << OType; 3639 Diag(PVD->getLocation(), diag::note_declared_at); 3640 } 3641 } 3642 } 3643 3644 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3645 // decays into a pointer and returns an unintended result. This is most 3646 // likely a typo for "sizeof(array) op x". 3647 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3648 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3649 BO->getLHS()); 3650 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3651 BO->getRHS()); 3652 } 3653 } 3654 3655 return false; 3656 } 3657 3658 /// \brief Check the constraints on operands to unary expression and type 3659 /// traits. 3660 /// 3661 /// This will complete any types necessary, and validate the various constraints 3662 /// on those operands. 3663 /// 3664 /// The UsualUnaryConversions() function is *not* called by this routine. 3665 /// C99 6.3.2.1p[2-4] all state: 3666 /// Except when it is the operand of the sizeof operator ... 3667 /// 3668 /// C++ [expr.sizeof]p4 3669 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3670 /// standard conversions are not applied to the operand of sizeof. 3671 /// 3672 /// This policy is followed for all of the unary trait expressions. 3673 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3674 SourceLocation OpLoc, 3675 SourceRange ExprRange, 3676 UnaryExprOrTypeTrait ExprKind) { 3677 if (ExprType->isDependentType()) 3678 return false; 3679 3680 // C++ [expr.sizeof]p2: 3681 // When applied to a reference or a reference type, the result 3682 // is the size of the referenced type. 3683 // C++11 [expr.alignof]p3: 3684 // When alignof is applied to a reference type, the result 3685 // shall be the alignment of the referenced type. 3686 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3687 ExprType = Ref->getPointeeType(); 3688 3689 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3690 // When alignof or _Alignof is applied to an array type, the result 3691 // is the alignment of the element type. 3692 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3693 ExprType = Context.getBaseElementType(ExprType); 3694 3695 if (ExprKind == UETT_VecStep) 3696 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3697 3698 // Whitelist some types as extensions 3699 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3700 ExprKind)) 3701 return false; 3702 3703 if (RequireCompleteType(OpLoc, ExprType, 3704 diag::err_sizeof_alignof_incomplete_type, 3705 ExprKind, ExprRange)) 3706 return true; 3707 3708 if (ExprType->isFunctionType()) { 3709 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3710 << ExprKind << ExprRange; 3711 return true; 3712 } 3713 3714 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3715 ExprKind)) 3716 return true; 3717 3718 return false; 3719 } 3720 3721 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3722 E = E->IgnoreParens(); 3723 3724 // Cannot know anything else if the expression is dependent. 3725 if (E->isTypeDependent()) 3726 return false; 3727 3728 if (E->getObjectKind() == OK_BitField) { 3729 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3730 << 1 << E->getSourceRange(); 3731 return true; 3732 } 3733 3734 ValueDecl *D = nullptr; 3735 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3736 D = DRE->getDecl(); 3737 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3738 D = ME->getMemberDecl(); 3739 } 3740 3741 // If it's a field, require the containing struct to have a 3742 // complete definition so that we can compute the layout. 3743 // 3744 // This can happen in C++11 onwards, either by naming the member 3745 // in a way that is not transformed into a member access expression 3746 // (in an unevaluated operand, for instance), or by naming the member 3747 // in a trailing-return-type. 3748 // 3749 // For the record, since __alignof__ on expressions is a GCC 3750 // extension, GCC seems to permit this but always gives the 3751 // nonsensical answer 0. 3752 // 3753 // We don't really need the layout here --- we could instead just 3754 // directly check for all the appropriate alignment-lowing 3755 // attributes --- but that would require duplicating a lot of 3756 // logic that just isn't worth duplicating for such a marginal 3757 // use-case. 3758 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3759 // Fast path this check, since we at least know the record has a 3760 // definition if we can find a member of it. 3761 if (!FD->getParent()->isCompleteDefinition()) { 3762 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3763 << E->getSourceRange(); 3764 return true; 3765 } 3766 3767 // Otherwise, if it's a field, and the field doesn't have 3768 // reference type, then it must have a complete type (or be a 3769 // flexible array member, which we explicitly want to 3770 // white-list anyway), which makes the following checks trivial. 3771 if (!FD->getType()->isReferenceType()) 3772 return false; 3773 } 3774 3775 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3776 } 3777 3778 bool Sema::CheckVecStepExpr(Expr *E) { 3779 E = E->IgnoreParens(); 3780 3781 // Cannot know anything else if the expression is dependent. 3782 if (E->isTypeDependent()) 3783 return false; 3784 3785 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3786 } 3787 3788 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3789 CapturingScopeInfo *CSI) { 3790 assert(T->isVariablyModifiedType()); 3791 assert(CSI != nullptr); 3792 3793 // We're going to walk down into the type and look for VLA expressions. 3794 do { 3795 const Type *Ty = T.getTypePtr(); 3796 switch (Ty->getTypeClass()) { 3797 #define TYPE(Class, Base) 3798 #define ABSTRACT_TYPE(Class, Base) 3799 #define NON_CANONICAL_TYPE(Class, Base) 3800 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3801 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3802 #include "clang/AST/TypeNodes.def" 3803 T = QualType(); 3804 break; 3805 // These types are never variably-modified. 3806 case Type::Builtin: 3807 case Type::Complex: 3808 case Type::Vector: 3809 case Type::ExtVector: 3810 case Type::Record: 3811 case Type::Enum: 3812 case Type::Elaborated: 3813 case Type::TemplateSpecialization: 3814 case Type::ObjCObject: 3815 case Type::ObjCInterface: 3816 case Type::ObjCObjectPointer: 3817 case Type::ObjCTypeParam: 3818 case Type::Pipe: 3819 llvm_unreachable("type class is never variably-modified!"); 3820 case Type::Adjusted: 3821 T = cast<AdjustedType>(Ty)->getOriginalType(); 3822 break; 3823 case Type::Decayed: 3824 T = cast<DecayedType>(Ty)->getPointeeType(); 3825 break; 3826 case Type::Pointer: 3827 T = cast<PointerType>(Ty)->getPointeeType(); 3828 break; 3829 case Type::BlockPointer: 3830 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3831 break; 3832 case Type::LValueReference: 3833 case Type::RValueReference: 3834 T = cast<ReferenceType>(Ty)->getPointeeType(); 3835 break; 3836 case Type::MemberPointer: 3837 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3838 break; 3839 case Type::ConstantArray: 3840 case Type::IncompleteArray: 3841 // Losing element qualification here is fine. 3842 T = cast<ArrayType>(Ty)->getElementType(); 3843 break; 3844 case Type::VariableArray: { 3845 // Losing element qualification here is fine. 3846 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3847 3848 // Unknown size indication requires no size computation. 3849 // Otherwise, evaluate and record it. 3850 if (auto Size = VAT->getSizeExpr()) { 3851 if (!CSI->isVLATypeCaptured(VAT)) { 3852 RecordDecl *CapRecord = nullptr; 3853 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3854 CapRecord = LSI->Lambda; 3855 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3856 CapRecord = CRSI->TheRecordDecl; 3857 } 3858 if (CapRecord) { 3859 auto ExprLoc = Size->getExprLoc(); 3860 auto SizeType = Context.getSizeType(); 3861 // Build the non-static data member. 3862 auto Field = 3863 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3864 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3865 /*BW*/ nullptr, /*Mutable*/ false, 3866 /*InitStyle*/ ICIS_NoInit); 3867 Field->setImplicit(true); 3868 Field->setAccess(AS_private); 3869 Field->setCapturedVLAType(VAT); 3870 CapRecord->addDecl(Field); 3871 3872 CSI->addVLATypeCapture(ExprLoc, SizeType); 3873 } 3874 } 3875 } 3876 T = VAT->getElementType(); 3877 break; 3878 } 3879 case Type::FunctionProto: 3880 case Type::FunctionNoProto: 3881 T = cast<FunctionType>(Ty)->getReturnType(); 3882 break; 3883 case Type::Paren: 3884 case Type::TypeOf: 3885 case Type::UnaryTransform: 3886 case Type::Attributed: 3887 case Type::SubstTemplateTypeParm: 3888 case Type::PackExpansion: 3889 // Keep walking after single level desugaring. 3890 T = T.getSingleStepDesugaredType(Context); 3891 break; 3892 case Type::Typedef: 3893 T = cast<TypedefType>(Ty)->desugar(); 3894 break; 3895 case Type::Decltype: 3896 T = cast<DecltypeType>(Ty)->desugar(); 3897 break; 3898 case Type::Auto: 3899 case Type::DeducedTemplateSpecialization: 3900 T = cast<DeducedType>(Ty)->getDeducedType(); 3901 break; 3902 case Type::TypeOfExpr: 3903 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3904 break; 3905 case Type::Atomic: 3906 T = cast<AtomicType>(Ty)->getValueType(); 3907 break; 3908 } 3909 } while (!T.isNull() && T->isVariablyModifiedType()); 3910 } 3911 3912 /// \brief Build a sizeof or alignof expression given a type operand. 3913 ExprResult 3914 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3915 SourceLocation OpLoc, 3916 UnaryExprOrTypeTrait ExprKind, 3917 SourceRange R) { 3918 if (!TInfo) 3919 return ExprError(); 3920 3921 QualType T = TInfo->getType(); 3922 3923 if (!T->isDependentType() && 3924 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3925 return ExprError(); 3926 3927 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3928 if (auto *TT = T->getAs<TypedefType>()) { 3929 for (auto I = FunctionScopes.rbegin(), 3930 E = std::prev(FunctionScopes.rend()); 3931 I != E; ++I) { 3932 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3933 if (CSI == nullptr) 3934 break; 3935 DeclContext *DC = nullptr; 3936 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3937 DC = LSI->CallOperator; 3938 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3939 DC = CRSI->TheCapturedDecl; 3940 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3941 DC = BSI->TheDecl; 3942 if (DC) { 3943 if (DC->containsDecl(TT->getDecl())) 3944 break; 3945 captureVariablyModifiedType(Context, T, CSI); 3946 } 3947 } 3948 } 3949 } 3950 3951 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3952 return new (Context) UnaryExprOrTypeTraitExpr( 3953 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3954 } 3955 3956 /// \brief Build a sizeof or alignof expression given an expression 3957 /// operand. 3958 ExprResult 3959 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3960 UnaryExprOrTypeTrait ExprKind) { 3961 ExprResult PE = CheckPlaceholderExpr(E); 3962 if (PE.isInvalid()) 3963 return ExprError(); 3964 3965 E = PE.get(); 3966 3967 // Verify that the operand is valid. 3968 bool isInvalid = false; 3969 if (E->isTypeDependent()) { 3970 // Delay type-checking for type-dependent expressions. 3971 } else if (ExprKind == UETT_AlignOf) { 3972 isInvalid = CheckAlignOfExpr(*this, E); 3973 } else if (ExprKind == UETT_VecStep) { 3974 isInvalid = CheckVecStepExpr(E); 3975 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3976 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3977 isInvalid = true; 3978 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3979 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3980 isInvalid = true; 3981 } else { 3982 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3983 } 3984 3985 if (isInvalid) 3986 return ExprError(); 3987 3988 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3989 PE = TransformToPotentiallyEvaluated(E); 3990 if (PE.isInvalid()) return ExprError(); 3991 E = PE.get(); 3992 } 3993 3994 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3995 return new (Context) UnaryExprOrTypeTraitExpr( 3996 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3997 } 3998 3999 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4000 /// expr and the same for @c alignof and @c __alignof 4001 /// Note that the ArgRange is invalid if isType is false. 4002 ExprResult 4003 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4004 UnaryExprOrTypeTrait ExprKind, bool IsType, 4005 void *TyOrEx, SourceRange ArgRange) { 4006 // If error parsing type, ignore. 4007 if (!TyOrEx) return ExprError(); 4008 4009 if (IsType) { 4010 TypeSourceInfo *TInfo; 4011 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4012 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4013 } 4014 4015 Expr *ArgEx = (Expr *)TyOrEx; 4016 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4017 return Result; 4018 } 4019 4020 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4021 bool IsReal) { 4022 if (V.get()->isTypeDependent()) 4023 return S.Context.DependentTy; 4024 4025 // _Real and _Imag are only l-values for normal l-values. 4026 if (V.get()->getObjectKind() != OK_Ordinary) { 4027 V = S.DefaultLvalueConversion(V.get()); 4028 if (V.isInvalid()) 4029 return QualType(); 4030 } 4031 4032 // These operators return the element type of a complex type. 4033 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4034 return CT->getElementType(); 4035 4036 // Otherwise they pass through real integer and floating point types here. 4037 if (V.get()->getType()->isArithmeticType()) 4038 return V.get()->getType(); 4039 4040 // Test for placeholders. 4041 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4042 if (PR.isInvalid()) return QualType(); 4043 if (PR.get() != V.get()) { 4044 V = PR; 4045 return CheckRealImagOperand(S, V, Loc, IsReal); 4046 } 4047 4048 // Reject anything else. 4049 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4050 << (IsReal ? "__real" : "__imag"); 4051 return QualType(); 4052 } 4053 4054 4055 4056 ExprResult 4057 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4058 tok::TokenKind Kind, Expr *Input) { 4059 UnaryOperatorKind Opc; 4060 switch (Kind) { 4061 default: llvm_unreachable("Unknown unary op!"); 4062 case tok::plusplus: Opc = UO_PostInc; break; 4063 case tok::minusminus: Opc = UO_PostDec; break; 4064 } 4065 4066 // Since this might is a postfix expression, get rid of ParenListExprs. 4067 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4068 if (Result.isInvalid()) return ExprError(); 4069 Input = Result.get(); 4070 4071 return BuildUnaryOp(S, OpLoc, Opc, Input); 4072 } 4073 4074 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4075 /// 4076 /// \return true on error 4077 static bool checkArithmeticOnObjCPointer(Sema &S, 4078 SourceLocation opLoc, 4079 Expr *op) { 4080 assert(op->getType()->isObjCObjectPointerType()); 4081 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4082 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4083 return false; 4084 4085 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4086 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4087 << op->getSourceRange(); 4088 return true; 4089 } 4090 4091 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4092 auto *BaseNoParens = Base->IgnoreParens(); 4093 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4094 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4095 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4096 } 4097 4098 ExprResult 4099 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4100 Expr *idx, SourceLocation rbLoc) { 4101 if (base && !base->getType().isNull() && 4102 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4103 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4104 /*Length=*/nullptr, rbLoc); 4105 4106 // Since this might be a postfix expression, get rid of ParenListExprs. 4107 if (isa<ParenListExpr>(base)) { 4108 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4109 if (result.isInvalid()) return ExprError(); 4110 base = result.get(); 4111 } 4112 4113 // Handle any non-overload placeholder types in the base and index 4114 // expressions. We can't handle overloads here because the other 4115 // operand might be an overloadable type, in which case the overload 4116 // resolution for the operator overload should get the first crack 4117 // at the overload. 4118 bool IsMSPropertySubscript = false; 4119 if (base->getType()->isNonOverloadPlaceholderType()) { 4120 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4121 if (!IsMSPropertySubscript) { 4122 ExprResult result = CheckPlaceholderExpr(base); 4123 if (result.isInvalid()) 4124 return ExprError(); 4125 base = result.get(); 4126 } 4127 } 4128 if (idx->getType()->isNonOverloadPlaceholderType()) { 4129 ExprResult result = CheckPlaceholderExpr(idx); 4130 if (result.isInvalid()) return ExprError(); 4131 idx = result.get(); 4132 } 4133 4134 // Build an unanalyzed expression if either operand is type-dependent. 4135 if (getLangOpts().CPlusPlus && 4136 (base->isTypeDependent() || idx->isTypeDependent())) { 4137 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4138 VK_LValue, OK_Ordinary, rbLoc); 4139 } 4140 4141 // MSDN, property (C++) 4142 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4143 // This attribute can also be used in the declaration of an empty array in a 4144 // class or structure definition. For example: 4145 // __declspec(property(get=GetX, put=PutX)) int x[]; 4146 // The above statement indicates that x[] can be used with one or more array 4147 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4148 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4149 if (IsMSPropertySubscript) { 4150 // Build MS property subscript expression if base is MS property reference 4151 // or MS property subscript. 4152 return new (Context) MSPropertySubscriptExpr( 4153 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4154 } 4155 4156 // Use C++ overloaded-operator rules if either operand has record 4157 // type. The spec says to do this if either type is *overloadable*, 4158 // but enum types can't declare subscript operators or conversion 4159 // operators, so there's nothing interesting for overload resolution 4160 // to do if there aren't any record types involved. 4161 // 4162 // ObjC pointers have their own subscripting logic that is not tied 4163 // to overload resolution and so should not take this path. 4164 if (getLangOpts().CPlusPlus && 4165 (base->getType()->isRecordType() || 4166 (!base->getType()->isObjCObjectPointerType() && 4167 idx->getType()->isRecordType()))) { 4168 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4169 } 4170 4171 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4172 } 4173 4174 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4175 Expr *LowerBound, 4176 SourceLocation ColonLoc, Expr *Length, 4177 SourceLocation RBLoc) { 4178 if (Base->getType()->isPlaceholderType() && 4179 !Base->getType()->isSpecificPlaceholderType( 4180 BuiltinType::OMPArraySection)) { 4181 ExprResult Result = CheckPlaceholderExpr(Base); 4182 if (Result.isInvalid()) 4183 return ExprError(); 4184 Base = Result.get(); 4185 } 4186 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4187 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4188 if (Result.isInvalid()) 4189 return ExprError(); 4190 Result = DefaultLvalueConversion(Result.get()); 4191 if (Result.isInvalid()) 4192 return ExprError(); 4193 LowerBound = Result.get(); 4194 } 4195 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4196 ExprResult Result = CheckPlaceholderExpr(Length); 4197 if (Result.isInvalid()) 4198 return ExprError(); 4199 Result = DefaultLvalueConversion(Result.get()); 4200 if (Result.isInvalid()) 4201 return ExprError(); 4202 Length = Result.get(); 4203 } 4204 4205 // Build an unanalyzed expression if either operand is type-dependent. 4206 if (Base->isTypeDependent() || 4207 (LowerBound && 4208 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4209 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4210 return new (Context) 4211 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4212 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4213 } 4214 4215 // Perform default conversions. 4216 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4217 QualType ResultTy; 4218 if (OriginalTy->isAnyPointerType()) { 4219 ResultTy = OriginalTy->getPointeeType(); 4220 } else if (OriginalTy->isArrayType()) { 4221 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4222 } else { 4223 return ExprError( 4224 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4225 << Base->getSourceRange()); 4226 } 4227 // C99 6.5.2.1p1 4228 if (LowerBound) { 4229 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4230 LowerBound); 4231 if (Res.isInvalid()) 4232 return ExprError(Diag(LowerBound->getExprLoc(), 4233 diag::err_omp_typecheck_section_not_integer) 4234 << 0 << LowerBound->getSourceRange()); 4235 LowerBound = Res.get(); 4236 4237 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4238 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4239 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4240 << 0 << LowerBound->getSourceRange(); 4241 } 4242 if (Length) { 4243 auto Res = 4244 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4245 if (Res.isInvalid()) 4246 return ExprError(Diag(Length->getExprLoc(), 4247 diag::err_omp_typecheck_section_not_integer) 4248 << 1 << Length->getSourceRange()); 4249 Length = Res.get(); 4250 4251 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4252 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4253 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4254 << 1 << Length->getSourceRange(); 4255 } 4256 4257 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4258 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4259 // type. Note that functions are not objects, and that (in C99 parlance) 4260 // incomplete types are not object types. 4261 if (ResultTy->isFunctionType()) { 4262 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4263 << ResultTy << Base->getSourceRange(); 4264 return ExprError(); 4265 } 4266 4267 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4268 diag::err_omp_section_incomplete_type, Base)) 4269 return ExprError(); 4270 4271 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4272 llvm::APSInt LowerBoundValue; 4273 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4274 // OpenMP 4.5, [2.4 Array Sections] 4275 // The array section must be a subset of the original array. 4276 if (LowerBoundValue.isNegative()) { 4277 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4278 << LowerBound->getSourceRange(); 4279 return ExprError(); 4280 } 4281 } 4282 } 4283 4284 if (Length) { 4285 llvm::APSInt LengthValue; 4286 if (Length->EvaluateAsInt(LengthValue, Context)) { 4287 // OpenMP 4.5, [2.4 Array Sections] 4288 // The length must evaluate to non-negative integers. 4289 if (LengthValue.isNegative()) { 4290 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4291 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4292 << Length->getSourceRange(); 4293 return ExprError(); 4294 } 4295 } 4296 } else if (ColonLoc.isValid() && 4297 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4298 !OriginalTy->isVariableArrayType()))) { 4299 // OpenMP 4.5, [2.4 Array Sections] 4300 // When the size of the array dimension is not known, the length must be 4301 // specified explicitly. 4302 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4303 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4304 return ExprError(); 4305 } 4306 4307 if (!Base->getType()->isSpecificPlaceholderType( 4308 BuiltinType::OMPArraySection)) { 4309 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4310 if (Result.isInvalid()) 4311 return ExprError(); 4312 Base = Result.get(); 4313 } 4314 return new (Context) 4315 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4316 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4317 } 4318 4319 ExprResult 4320 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4321 Expr *Idx, SourceLocation RLoc) { 4322 Expr *LHSExp = Base; 4323 Expr *RHSExp = Idx; 4324 4325 ExprValueKind VK = VK_LValue; 4326 ExprObjectKind OK = OK_Ordinary; 4327 4328 // Per C++ core issue 1213, the result is an xvalue if either operand is 4329 // a non-lvalue array, and an lvalue otherwise. 4330 if (getLangOpts().CPlusPlus11 && 4331 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4332 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4333 VK = VK_XValue; 4334 4335 // Perform default conversions. 4336 if (!LHSExp->getType()->getAs<VectorType>()) { 4337 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4338 if (Result.isInvalid()) 4339 return ExprError(); 4340 LHSExp = Result.get(); 4341 } 4342 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4343 if (Result.isInvalid()) 4344 return ExprError(); 4345 RHSExp = Result.get(); 4346 4347 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4348 4349 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4350 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4351 // in the subscript position. As a result, we need to derive the array base 4352 // and index from the expression types. 4353 Expr *BaseExpr, *IndexExpr; 4354 QualType ResultType; 4355 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4356 BaseExpr = LHSExp; 4357 IndexExpr = RHSExp; 4358 ResultType = Context.DependentTy; 4359 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4360 BaseExpr = LHSExp; 4361 IndexExpr = RHSExp; 4362 ResultType = PTy->getPointeeType(); 4363 } else if (const ObjCObjectPointerType *PTy = 4364 LHSTy->getAs<ObjCObjectPointerType>()) { 4365 BaseExpr = LHSExp; 4366 IndexExpr = RHSExp; 4367 4368 // Use custom logic if this should be the pseudo-object subscript 4369 // expression. 4370 if (!LangOpts.isSubscriptPointerArithmetic()) 4371 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4372 nullptr); 4373 4374 ResultType = PTy->getPointeeType(); 4375 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4376 // Handle the uncommon case of "123[Ptr]". 4377 BaseExpr = RHSExp; 4378 IndexExpr = LHSExp; 4379 ResultType = PTy->getPointeeType(); 4380 } else if (const ObjCObjectPointerType *PTy = 4381 RHSTy->getAs<ObjCObjectPointerType>()) { 4382 // Handle the uncommon case of "123[Ptr]". 4383 BaseExpr = RHSExp; 4384 IndexExpr = LHSExp; 4385 ResultType = PTy->getPointeeType(); 4386 if (!LangOpts.isSubscriptPointerArithmetic()) { 4387 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4388 << ResultType << BaseExpr->getSourceRange(); 4389 return ExprError(); 4390 } 4391 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4392 BaseExpr = LHSExp; // vectors: V[123] 4393 IndexExpr = RHSExp; 4394 VK = LHSExp->getValueKind(); 4395 if (VK != VK_RValue) 4396 OK = OK_VectorComponent; 4397 4398 // FIXME: need to deal with const... 4399 ResultType = VTy->getElementType(); 4400 } else if (LHSTy->isArrayType()) { 4401 // If we see an array that wasn't promoted by 4402 // DefaultFunctionArrayLvalueConversion, it must be an array that 4403 // wasn't promoted because of the C90 rule that doesn't 4404 // allow promoting non-lvalue arrays. Warn, then 4405 // force the promotion here. 4406 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4407 LHSExp->getSourceRange(); 4408 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4409 CK_ArrayToPointerDecay).get(); 4410 LHSTy = LHSExp->getType(); 4411 4412 BaseExpr = LHSExp; 4413 IndexExpr = RHSExp; 4414 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4415 } else if (RHSTy->isArrayType()) { 4416 // Same as previous, except for 123[f().a] case 4417 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4418 RHSExp->getSourceRange(); 4419 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4420 CK_ArrayToPointerDecay).get(); 4421 RHSTy = RHSExp->getType(); 4422 4423 BaseExpr = RHSExp; 4424 IndexExpr = LHSExp; 4425 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4426 } else { 4427 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4428 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4429 } 4430 // C99 6.5.2.1p1 4431 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4432 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4433 << IndexExpr->getSourceRange()); 4434 4435 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4436 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4437 && !IndexExpr->isTypeDependent()) 4438 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4439 4440 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4441 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4442 // type. Note that Functions are not objects, and that (in C99 parlance) 4443 // incomplete types are not object types. 4444 if (ResultType->isFunctionType()) { 4445 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4446 << ResultType << BaseExpr->getSourceRange(); 4447 return ExprError(); 4448 } 4449 4450 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4451 // GNU extension: subscripting on pointer to void 4452 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4453 << BaseExpr->getSourceRange(); 4454 4455 // C forbids expressions of unqualified void type from being l-values. 4456 // See IsCForbiddenLValueType. 4457 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4458 } else if (!ResultType->isDependentType() && 4459 RequireCompleteType(LLoc, ResultType, 4460 diag::err_subscript_incomplete_type, BaseExpr)) 4461 return ExprError(); 4462 4463 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4464 !ResultType.isCForbiddenLValueType()); 4465 4466 return new (Context) 4467 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4468 } 4469 4470 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4471 ParmVarDecl *Param) { 4472 if (Param->hasUnparsedDefaultArg()) { 4473 Diag(CallLoc, 4474 diag::err_use_of_default_argument_to_function_declared_later) << 4475 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4476 Diag(UnparsedDefaultArgLocs[Param], 4477 diag::note_default_argument_declared_here); 4478 return true; 4479 } 4480 4481 if (Param->hasUninstantiatedDefaultArg()) { 4482 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4483 4484 EnterExpressionEvaluationContext EvalContext( 4485 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4486 4487 // Instantiate the expression. 4488 // 4489 // FIXME: Pass in a correct Pattern argument, otherwise 4490 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4491 // 4492 // template<typename T> 4493 // struct A { 4494 // static int FooImpl(); 4495 // 4496 // template<typename Tp> 4497 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4498 // // template argument list [[T], [Tp]], should be [[Tp]]. 4499 // friend A<Tp> Foo(int a); 4500 // }; 4501 // 4502 // template<typename T> 4503 // A<T> Foo(int a = A<T>::FooImpl()); 4504 MultiLevelTemplateArgumentList MutiLevelArgList 4505 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4506 4507 InstantiatingTemplate Inst(*this, CallLoc, Param, 4508 MutiLevelArgList.getInnermost()); 4509 if (Inst.isInvalid()) 4510 return true; 4511 if (Inst.isAlreadyInstantiating()) { 4512 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4513 Param->setInvalidDecl(); 4514 return true; 4515 } 4516 4517 ExprResult Result; 4518 { 4519 // C++ [dcl.fct.default]p5: 4520 // The names in the [default argument] expression are bound, and 4521 // the semantic constraints are checked, at the point where the 4522 // default argument expression appears. 4523 ContextRAII SavedContext(*this, FD); 4524 LocalInstantiationScope Local(*this); 4525 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4526 /*DirectInit*/false); 4527 } 4528 if (Result.isInvalid()) 4529 return true; 4530 4531 // Check the expression as an initializer for the parameter. 4532 InitializedEntity Entity 4533 = InitializedEntity::InitializeParameter(Context, Param); 4534 InitializationKind Kind 4535 = InitializationKind::CreateCopy(Param->getLocation(), 4536 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4537 Expr *ResultE = Result.getAs<Expr>(); 4538 4539 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4540 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4541 if (Result.isInvalid()) 4542 return true; 4543 4544 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4545 Param->getOuterLocStart()); 4546 if (Result.isInvalid()) 4547 return true; 4548 4549 // Remember the instantiated default argument. 4550 Param->setDefaultArg(Result.getAs<Expr>()); 4551 if (ASTMutationListener *L = getASTMutationListener()) { 4552 L->DefaultArgumentInstantiated(Param); 4553 } 4554 } 4555 4556 // If the default argument expression is not set yet, we are building it now. 4557 if (!Param->hasInit()) { 4558 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4559 Param->setInvalidDecl(); 4560 return true; 4561 } 4562 4563 // If the default expression creates temporaries, we need to 4564 // push them to the current stack of expression temporaries so they'll 4565 // be properly destroyed. 4566 // FIXME: We should really be rebuilding the default argument with new 4567 // bound temporaries; see the comment in PR5810. 4568 // We don't need to do that with block decls, though, because 4569 // blocks in default argument expression can never capture anything. 4570 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4571 // Set the "needs cleanups" bit regardless of whether there are 4572 // any explicit objects. 4573 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4574 4575 // Append all the objects to the cleanup list. Right now, this 4576 // should always be a no-op, because blocks in default argument 4577 // expressions should never be able to capture anything. 4578 assert(!Init->getNumObjects() && 4579 "default argument expression has capturing blocks?"); 4580 } 4581 4582 // We already type-checked the argument, so we know it works. 4583 // Just mark all of the declarations in this potentially-evaluated expression 4584 // as being "referenced". 4585 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4586 /*SkipLocalVariables=*/true); 4587 return false; 4588 } 4589 4590 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4591 FunctionDecl *FD, ParmVarDecl *Param) { 4592 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4593 return ExprError(); 4594 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4595 } 4596 4597 Sema::VariadicCallType 4598 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4599 Expr *Fn) { 4600 if (Proto && Proto->isVariadic()) { 4601 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4602 return VariadicConstructor; 4603 else if (Fn && Fn->getType()->isBlockPointerType()) 4604 return VariadicBlock; 4605 else if (FDecl) { 4606 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4607 if (Method->isInstance()) 4608 return VariadicMethod; 4609 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4610 return VariadicMethod; 4611 return VariadicFunction; 4612 } 4613 return VariadicDoesNotApply; 4614 } 4615 4616 namespace { 4617 class FunctionCallCCC : public FunctionCallFilterCCC { 4618 public: 4619 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4620 unsigned NumArgs, MemberExpr *ME) 4621 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4622 FunctionName(FuncName) {} 4623 4624 bool ValidateCandidate(const TypoCorrection &candidate) override { 4625 if (!candidate.getCorrectionSpecifier() || 4626 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4627 return false; 4628 } 4629 4630 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4631 } 4632 4633 private: 4634 const IdentifierInfo *const FunctionName; 4635 }; 4636 } 4637 4638 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4639 FunctionDecl *FDecl, 4640 ArrayRef<Expr *> Args) { 4641 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4642 DeclarationName FuncName = FDecl->getDeclName(); 4643 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4644 4645 if (TypoCorrection Corrected = S.CorrectTypo( 4646 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4647 S.getScopeForContext(S.CurContext), nullptr, 4648 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4649 Args.size(), ME), 4650 Sema::CTK_ErrorRecovery)) { 4651 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4652 if (Corrected.isOverloaded()) { 4653 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4654 OverloadCandidateSet::iterator Best; 4655 for (NamedDecl *CD : Corrected) { 4656 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4657 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4658 OCS); 4659 } 4660 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4661 case OR_Success: 4662 ND = Best->FoundDecl; 4663 Corrected.setCorrectionDecl(ND); 4664 break; 4665 default: 4666 break; 4667 } 4668 } 4669 ND = ND->getUnderlyingDecl(); 4670 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4671 return Corrected; 4672 } 4673 } 4674 return TypoCorrection(); 4675 } 4676 4677 /// ConvertArgumentsForCall - Converts the arguments specified in 4678 /// Args/NumArgs to the parameter types of the function FDecl with 4679 /// function prototype Proto. Call is the call expression itself, and 4680 /// Fn is the function expression. For a C++ member function, this 4681 /// routine does not attempt to convert the object argument. Returns 4682 /// true if the call is ill-formed. 4683 bool 4684 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4685 FunctionDecl *FDecl, 4686 const FunctionProtoType *Proto, 4687 ArrayRef<Expr *> Args, 4688 SourceLocation RParenLoc, 4689 bool IsExecConfig) { 4690 // Bail out early if calling a builtin with custom typechecking. 4691 if (FDecl) 4692 if (unsigned ID = FDecl->getBuiltinID()) 4693 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4694 return false; 4695 4696 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4697 // assignment, to the types of the corresponding parameter, ... 4698 unsigned NumParams = Proto->getNumParams(); 4699 bool Invalid = false; 4700 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4701 unsigned FnKind = Fn->getType()->isBlockPointerType() 4702 ? 1 /* block */ 4703 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4704 : 0 /* function */); 4705 4706 // If too few arguments are available (and we don't have default 4707 // arguments for the remaining parameters), don't make the call. 4708 if (Args.size() < NumParams) { 4709 if (Args.size() < MinArgs) { 4710 TypoCorrection TC; 4711 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4712 unsigned diag_id = 4713 MinArgs == NumParams && !Proto->isVariadic() 4714 ? diag::err_typecheck_call_too_few_args_suggest 4715 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4716 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4717 << static_cast<unsigned>(Args.size()) 4718 << TC.getCorrectionRange()); 4719 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4720 Diag(RParenLoc, 4721 MinArgs == NumParams && !Proto->isVariadic() 4722 ? diag::err_typecheck_call_too_few_args_one 4723 : diag::err_typecheck_call_too_few_args_at_least_one) 4724 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4725 else 4726 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4727 ? diag::err_typecheck_call_too_few_args 4728 : diag::err_typecheck_call_too_few_args_at_least) 4729 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4730 << Fn->getSourceRange(); 4731 4732 // Emit the location of the prototype. 4733 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4734 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4735 << FDecl; 4736 4737 return true; 4738 } 4739 Call->setNumArgs(Context, NumParams); 4740 } 4741 4742 // If too many are passed and not variadic, error on the extras and drop 4743 // them. 4744 if (Args.size() > NumParams) { 4745 if (!Proto->isVariadic()) { 4746 TypoCorrection TC; 4747 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4748 unsigned diag_id = 4749 MinArgs == NumParams && !Proto->isVariadic() 4750 ? diag::err_typecheck_call_too_many_args_suggest 4751 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4752 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4753 << static_cast<unsigned>(Args.size()) 4754 << TC.getCorrectionRange()); 4755 } else if (NumParams == 1 && FDecl && 4756 FDecl->getParamDecl(0)->getDeclName()) 4757 Diag(Args[NumParams]->getLocStart(), 4758 MinArgs == NumParams 4759 ? diag::err_typecheck_call_too_many_args_one 4760 : diag::err_typecheck_call_too_many_args_at_most_one) 4761 << FnKind << FDecl->getParamDecl(0) 4762 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4763 << SourceRange(Args[NumParams]->getLocStart(), 4764 Args.back()->getLocEnd()); 4765 else 4766 Diag(Args[NumParams]->getLocStart(), 4767 MinArgs == NumParams 4768 ? diag::err_typecheck_call_too_many_args 4769 : diag::err_typecheck_call_too_many_args_at_most) 4770 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4771 << Fn->getSourceRange() 4772 << SourceRange(Args[NumParams]->getLocStart(), 4773 Args.back()->getLocEnd()); 4774 4775 // Emit the location of the prototype. 4776 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4777 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4778 << FDecl; 4779 4780 // This deletes the extra arguments. 4781 Call->setNumArgs(Context, NumParams); 4782 return true; 4783 } 4784 } 4785 SmallVector<Expr *, 8> AllArgs; 4786 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4787 4788 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4789 Proto, 0, Args, AllArgs, CallType); 4790 if (Invalid) 4791 return true; 4792 unsigned TotalNumArgs = AllArgs.size(); 4793 for (unsigned i = 0; i < TotalNumArgs; ++i) 4794 Call->setArg(i, AllArgs[i]); 4795 4796 return false; 4797 } 4798 4799 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4800 const FunctionProtoType *Proto, 4801 unsigned FirstParam, ArrayRef<Expr *> Args, 4802 SmallVectorImpl<Expr *> &AllArgs, 4803 VariadicCallType CallType, bool AllowExplicit, 4804 bool IsListInitialization) { 4805 unsigned NumParams = Proto->getNumParams(); 4806 bool Invalid = false; 4807 size_t ArgIx = 0; 4808 // Continue to check argument types (even if we have too few/many args). 4809 for (unsigned i = FirstParam; i < NumParams; i++) { 4810 QualType ProtoArgType = Proto->getParamType(i); 4811 4812 Expr *Arg; 4813 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4814 if (ArgIx < Args.size()) { 4815 Arg = Args[ArgIx++]; 4816 4817 if (RequireCompleteType(Arg->getLocStart(), 4818 ProtoArgType, 4819 diag::err_call_incomplete_argument, Arg)) 4820 return true; 4821 4822 // Strip the unbridged-cast placeholder expression off, if applicable. 4823 bool CFAudited = false; 4824 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4825 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4826 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4827 Arg = stripARCUnbridgedCast(Arg); 4828 else if (getLangOpts().ObjCAutoRefCount && 4829 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4830 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4831 CFAudited = true; 4832 4833 InitializedEntity Entity = 4834 Param ? InitializedEntity::InitializeParameter(Context, Param, 4835 ProtoArgType) 4836 : InitializedEntity::InitializeParameter( 4837 Context, ProtoArgType, Proto->isParamConsumed(i)); 4838 4839 // Remember that parameter belongs to a CF audited API. 4840 if (CFAudited) 4841 Entity.setParameterCFAudited(); 4842 4843 ExprResult ArgE = PerformCopyInitialization( 4844 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4845 if (ArgE.isInvalid()) 4846 return true; 4847 4848 Arg = ArgE.getAs<Expr>(); 4849 } else { 4850 assert(Param && "can't use default arguments without a known callee"); 4851 4852 ExprResult ArgExpr = 4853 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4854 if (ArgExpr.isInvalid()) 4855 return true; 4856 4857 Arg = ArgExpr.getAs<Expr>(); 4858 } 4859 4860 // Check for array bounds violations for each argument to the call. This 4861 // check only triggers warnings when the argument isn't a more complex Expr 4862 // with its own checking, such as a BinaryOperator. 4863 CheckArrayAccess(Arg); 4864 4865 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4866 CheckStaticArrayArgument(CallLoc, Param, Arg); 4867 4868 AllArgs.push_back(Arg); 4869 } 4870 4871 // If this is a variadic call, handle args passed through "...". 4872 if (CallType != VariadicDoesNotApply) { 4873 // Assume that extern "C" functions with variadic arguments that 4874 // return __unknown_anytype aren't *really* variadic. 4875 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4876 FDecl->isExternC()) { 4877 for (Expr *A : Args.slice(ArgIx)) { 4878 QualType paramType; // ignored 4879 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4880 Invalid |= arg.isInvalid(); 4881 AllArgs.push_back(arg.get()); 4882 } 4883 4884 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4885 } else { 4886 for (Expr *A : Args.slice(ArgIx)) { 4887 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4888 Invalid |= Arg.isInvalid(); 4889 AllArgs.push_back(Arg.get()); 4890 } 4891 } 4892 4893 // Check for array bounds violations. 4894 for (Expr *A : Args.slice(ArgIx)) 4895 CheckArrayAccess(A); 4896 } 4897 return Invalid; 4898 } 4899 4900 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4901 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4902 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4903 TL = DTL.getOriginalLoc(); 4904 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4905 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4906 << ATL.getLocalSourceRange(); 4907 } 4908 4909 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4910 /// array parameter, check that it is non-null, and that if it is formed by 4911 /// array-to-pointer decay, the underlying array is sufficiently large. 4912 /// 4913 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4914 /// array type derivation, then for each call to the function, the value of the 4915 /// corresponding actual argument shall provide access to the first element of 4916 /// an array with at least as many elements as specified by the size expression. 4917 void 4918 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4919 ParmVarDecl *Param, 4920 const Expr *ArgExpr) { 4921 // Static array parameters are not supported in C++. 4922 if (!Param || getLangOpts().CPlusPlus) 4923 return; 4924 4925 QualType OrigTy = Param->getOriginalType(); 4926 4927 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4928 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4929 return; 4930 4931 if (ArgExpr->isNullPointerConstant(Context, 4932 Expr::NPC_NeverValueDependent)) { 4933 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4934 DiagnoseCalleeStaticArrayParam(*this, Param); 4935 return; 4936 } 4937 4938 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4939 if (!CAT) 4940 return; 4941 4942 const ConstantArrayType *ArgCAT = 4943 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4944 if (!ArgCAT) 4945 return; 4946 4947 if (ArgCAT->getSize().ult(CAT->getSize())) { 4948 Diag(CallLoc, diag::warn_static_array_too_small) 4949 << ArgExpr->getSourceRange() 4950 << (unsigned) ArgCAT->getSize().getZExtValue() 4951 << (unsigned) CAT->getSize().getZExtValue(); 4952 DiagnoseCalleeStaticArrayParam(*this, Param); 4953 } 4954 } 4955 4956 /// Given a function expression of unknown-any type, try to rebuild it 4957 /// to have a function type. 4958 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4959 4960 /// Is the given type a placeholder that we need to lower out 4961 /// immediately during argument processing? 4962 static bool isPlaceholderToRemoveAsArg(QualType type) { 4963 // Placeholders are never sugared. 4964 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4965 if (!placeholder) return false; 4966 4967 switch (placeholder->getKind()) { 4968 // Ignore all the non-placeholder types. 4969 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4970 case BuiltinType::Id: 4971 #include "clang/Basic/OpenCLImageTypes.def" 4972 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4973 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4974 #include "clang/AST/BuiltinTypes.def" 4975 return false; 4976 4977 // We cannot lower out overload sets; they might validly be resolved 4978 // by the call machinery. 4979 case BuiltinType::Overload: 4980 return false; 4981 4982 // Unbridged casts in ARC can be handled in some call positions and 4983 // should be left in place. 4984 case BuiltinType::ARCUnbridgedCast: 4985 return false; 4986 4987 // Pseudo-objects should be converted as soon as possible. 4988 case BuiltinType::PseudoObject: 4989 return true; 4990 4991 // The debugger mode could theoretically but currently does not try 4992 // to resolve unknown-typed arguments based on known parameter types. 4993 case BuiltinType::UnknownAny: 4994 return true; 4995 4996 // These are always invalid as call arguments and should be reported. 4997 case BuiltinType::BoundMember: 4998 case BuiltinType::BuiltinFn: 4999 case BuiltinType::OMPArraySection: 5000 return true; 5001 5002 } 5003 llvm_unreachable("bad builtin type kind"); 5004 } 5005 5006 /// Check an argument list for placeholders that we won't try to 5007 /// handle later. 5008 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5009 // Apply this processing to all the arguments at once instead of 5010 // dying at the first failure. 5011 bool hasInvalid = false; 5012 for (size_t i = 0, e = args.size(); i != e; i++) { 5013 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5014 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5015 if (result.isInvalid()) hasInvalid = true; 5016 else args[i] = result.get(); 5017 } else if (hasInvalid) { 5018 (void)S.CorrectDelayedTyposInExpr(args[i]); 5019 } 5020 } 5021 return hasInvalid; 5022 } 5023 5024 /// If a builtin function has a pointer argument with no explicit address 5025 /// space, then it should be able to accept a pointer to any address 5026 /// space as input. In order to do this, we need to replace the 5027 /// standard builtin declaration with one that uses the same address space 5028 /// as the call. 5029 /// 5030 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5031 /// it does not contain any pointer arguments without 5032 /// an address space qualifer. Otherwise the rewritten 5033 /// FunctionDecl is returned. 5034 /// TODO: Handle pointer return types. 5035 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5036 const FunctionDecl *FDecl, 5037 MultiExprArg ArgExprs) { 5038 5039 QualType DeclType = FDecl->getType(); 5040 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5041 5042 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5043 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5044 return nullptr; 5045 5046 bool NeedsNewDecl = false; 5047 unsigned i = 0; 5048 SmallVector<QualType, 8> OverloadParams; 5049 5050 for (QualType ParamType : FT->param_types()) { 5051 5052 // Convert array arguments to pointer to simplify type lookup. 5053 ExprResult ArgRes = 5054 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5055 if (ArgRes.isInvalid()) 5056 return nullptr; 5057 Expr *Arg = ArgRes.get(); 5058 QualType ArgType = Arg->getType(); 5059 if (!ParamType->isPointerType() || 5060 ParamType.getQualifiers().hasAddressSpace() || 5061 !ArgType->isPointerType() || 5062 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5063 OverloadParams.push_back(ParamType); 5064 continue; 5065 } 5066 5067 NeedsNewDecl = true; 5068 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5069 5070 QualType PointeeType = ParamType->getPointeeType(); 5071 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5072 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5073 } 5074 5075 if (!NeedsNewDecl) 5076 return nullptr; 5077 5078 FunctionProtoType::ExtProtoInfo EPI; 5079 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5080 OverloadParams, EPI); 5081 DeclContext *Parent = Context.getTranslationUnitDecl(); 5082 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5083 FDecl->getLocation(), 5084 FDecl->getLocation(), 5085 FDecl->getIdentifier(), 5086 OverloadTy, 5087 /*TInfo=*/nullptr, 5088 SC_Extern, false, 5089 /*hasPrototype=*/true); 5090 SmallVector<ParmVarDecl*, 16> Params; 5091 FT = cast<FunctionProtoType>(OverloadTy); 5092 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5093 QualType ParamType = FT->getParamType(i); 5094 ParmVarDecl *Parm = 5095 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5096 SourceLocation(), nullptr, ParamType, 5097 /*TInfo=*/nullptr, SC_None, nullptr); 5098 Parm->setScopeInfo(0, i); 5099 Params.push_back(Parm); 5100 } 5101 OverloadDecl->setParams(Params); 5102 return OverloadDecl; 5103 } 5104 5105 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5106 FunctionDecl *Callee, 5107 MultiExprArg ArgExprs) { 5108 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5109 // similar attributes) really don't like it when functions are called with an 5110 // invalid number of args. 5111 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5112 /*PartialOverloading=*/false) && 5113 !Callee->isVariadic()) 5114 return; 5115 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5116 return; 5117 5118 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5119 S.Diag(Fn->getLocStart(), 5120 isa<CXXMethodDecl>(Callee) 5121 ? diag::err_ovl_no_viable_member_function_in_call 5122 : diag::err_ovl_no_viable_function_in_call) 5123 << Callee << Callee->getSourceRange(); 5124 S.Diag(Callee->getLocation(), 5125 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5126 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5127 return; 5128 } 5129 } 5130 5131 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5132 const UnresolvedMemberExpr *const UME, Sema &S) { 5133 5134 const auto GetFunctionLevelDCIfCXXClass = 5135 [](Sema &S) -> const CXXRecordDecl * { 5136 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5137 if (!DC || !DC->getParent()) 5138 return nullptr; 5139 5140 // If the call to some member function was made from within a member 5141 // function body 'M' return return 'M's parent. 5142 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5143 return MD->getParent()->getCanonicalDecl(); 5144 // else the call was made from within a default member initializer of a 5145 // class, so return the class. 5146 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5147 return RD->getCanonicalDecl(); 5148 return nullptr; 5149 }; 5150 // If our DeclContext is neither a member function nor a class (in the 5151 // case of a lambda in a default member initializer), we can't have an 5152 // enclosing 'this'. 5153 5154 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5155 if (!CurParentClass) 5156 return false; 5157 5158 // The naming class for implicit member functions call is the class in which 5159 // name lookup starts. 5160 const CXXRecordDecl *const NamingClass = 5161 UME->getNamingClass()->getCanonicalDecl(); 5162 assert(NamingClass && "Must have naming class even for implicit access"); 5163 5164 // If the unresolved member functions were found in a 'naming class' that is 5165 // related (either the same or derived from) to the class that contains the 5166 // member function that itself contained the implicit member access. 5167 5168 return CurParentClass == NamingClass || 5169 CurParentClass->isDerivedFrom(NamingClass); 5170 } 5171 5172 static void 5173 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5174 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5175 5176 if (!UME) 5177 return; 5178 5179 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5180 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5181 // already been captured, or if this is an implicit member function call (if 5182 // it isn't, an attempt to capture 'this' should already have been made). 5183 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5184 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5185 return; 5186 5187 // Check if the naming class in which the unresolved members were found is 5188 // related (same as or is a base of) to the enclosing class. 5189 5190 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5191 return; 5192 5193 5194 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5195 // If the enclosing function is not dependent, then this lambda is 5196 // capture ready, so if we can capture this, do so. 5197 if (!EnclosingFunctionCtx->isDependentContext()) { 5198 // If the current lambda and all enclosing lambdas can capture 'this' - 5199 // then go ahead and capture 'this' (since our unresolved overload set 5200 // contains at least one non-static member function). 5201 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5202 S.CheckCXXThisCapture(CallLoc); 5203 } else if (S.CurContext->isDependentContext()) { 5204 // ... since this is an implicit member reference, that might potentially 5205 // involve a 'this' capture, mark 'this' for potential capture in 5206 // enclosing lambdas. 5207 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5208 CurLSI->addPotentialThisCapture(CallLoc); 5209 } 5210 } 5211 5212 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5213 /// This provides the location of the left/right parens and a list of comma 5214 /// locations. 5215 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5216 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5217 Expr *ExecConfig, bool IsExecConfig) { 5218 // Since this might be a postfix expression, get rid of ParenListExprs. 5219 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5220 if (Result.isInvalid()) return ExprError(); 5221 Fn = Result.get(); 5222 5223 if (checkArgsForPlaceholders(*this, ArgExprs)) 5224 return ExprError(); 5225 5226 if (getLangOpts().CPlusPlus) { 5227 // If this is a pseudo-destructor expression, build the call immediately. 5228 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5229 if (!ArgExprs.empty()) { 5230 // Pseudo-destructor calls should not have any arguments. 5231 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5232 << FixItHint::CreateRemoval( 5233 SourceRange(ArgExprs.front()->getLocStart(), 5234 ArgExprs.back()->getLocEnd())); 5235 } 5236 5237 return new (Context) 5238 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5239 } 5240 if (Fn->getType() == Context.PseudoObjectTy) { 5241 ExprResult result = CheckPlaceholderExpr(Fn); 5242 if (result.isInvalid()) return ExprError(); 5243 Fn = result.get(); 5244 } 5245 5246 // Determine whether this is a dependent call inside a C++ template, 5247 // in which case we won't do any semantic analysis now. 5248 bool Dependent = false; 5249 if (Fn->isTypeDependent()) 5250 Dependent = true; 5251 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5252 Dependent = true; 5253 5254 if (Dependent) { 5255 if (ExecConfig) { 5256 return new (Context) CUDAKernelCallExpr( 5257 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5258 Context.DependentTy, VK_RValue, RParenLoc); 5259 } else { 5260 5261 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5262 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5263 Fn->getLocStart()); 5264 5265 return new (Context) CallExpr( 5266 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5267 } 5268 } 5269 5270 // Determine whether this is a call to an object (C++ [over.call.object]). 5271 if (Fn->getType()->isRecordType()) 5272 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5273 RParenLoc); 5274 5275 if (Fn->getType() == Context.UnknownAnyTy) { 5276 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5277 if (result.isInvalid()) return ExprError(); 5278 Fn = result.get(); 5279 } 5280 5281 if (Fn->getType() == Context.BoundMemberTy) { 5282 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5283 RParenLoc); 5284 } 5285 } 5286 5287 // Check for overloaded calls. This can happen even in C due to extensions. 5288 if (Fn->getType() == Context.OverloadTy) { 5289 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5290 5291 // We aren't supposed to apply this logic if there's an '&' involved. 5292 if (!find.HasFormOfMemberPointer) { 5293 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5294 return new (Context) CallExpr( 5295 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5296 OverloadExpr *ovl = find.Expression; 5297 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5298 return BuildOverloadedCallExpr( 5299 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5300 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5301 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5302 RParenLoc); 5303 } 5304 } 5305 5306 // If we're directly calling a function, get the appropriate declaration. 5307 if (Fn->getType() == Context.UnknownAnyTy) { 5308 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5309 if (result.isInvalid()) return ExprError(); 5310 Fn = result.get(); 5311 } 5312 5313 Expr *NakedFn = Fn->IgnoreParens(); 5314 5315 bool CallingNDeclIndirectly = false; 5316 NamedDecl *NDecl = nullptr; 5317 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5318 if (UnOp->getOpcode() == UO_AddrOf) { 5319 CallingNDeclIndirectly = true; 5320 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5321 } 5322 } 5323 5324 if (isa<DeclRefExpr>(NakedFn)) { 5325 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5326 5327 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5328 if (FDecl && FDecl->getBuiltinID()) { 5329 // Rewrite the function decl for this builtin by replacing parameters 5330 // with no explicit address space with the address space of the arguments 5331 // in ArgExprs. 5332 if ((FDecl = 5333 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5334 NDecl = FDecl; 5335 Fn = DeclRefExpr::Create( 5336 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5337 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5338 } 5339 } 5340 } else if (isa<MemberExpr>(NakedFn)) 5341 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5342 5343 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5344 if (CallingNDeclIndirectly && 5345 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5346 Fn->getLocStart())) 5347 return ExprError(); 5348 5349 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5350 return ExprError(); 5351 5352 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5353 } 5354 5355 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5356 ExecConfig, IsExecConfig); 5357 } 5358 5359 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5360 /// 5361 /// __builtin_astype( value, dst type ) 5362 /// 5363 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5364 SourceLocation BuiltinLoc, 5365 SourceLocation RParenLoc) { 5366 ExprValueKind VK = VK_RValue; 5367 ExprObjectKind OK = OK_Ordinary; 5368 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5369 QualType SrcTy = E->getType(); 5370 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5371 return ExprError(Diag(BuiltinLoc, 5372 diag::err_invalid_astype_of_different_size) 5373 << DstTy 5374 << SrcTy 5375 << E->getSourceRange()); 5376 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5377 } 5378 5379 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5380 /// provided arguments. 5381 /// 5382 /// __builtin_convertvector( value, dst type ) 5383 /// 5384 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5385 SourceLocation BuiltinLoc, 5386 SourceLocation RParenLoc) { 5387 TypeSourceInfo *TInfo; 5388 GetTypeFromParser(ParsedDestTy, &TInfo); 5389 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5390 } 5391 5392 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5393 /// i.e. an expression not of \p OverloadTy. The expression should 5394 /// unary-convert to an expression of function-pointer or 5395 /// block-pointer type. 5396 /// 5397 /// \param NDecl the declaration being called, if available 5398 ExprResult 5399 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5400 SourceLocation LParenLoc, 5401 ArrayRef<Expr *> Args, 5402 SourceLocation RParenLoc, 5403 Expr *Config, bool IsExecConfig) { 5404 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5405 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5406 5407 // Functions with 'interrupt' attribute cannot be called directly. 5408 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5409 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5410 return ExprError(); 5411 } 5412 5413 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5414 // so there's some risk when calling out to non-interrupt handler functions 5415 // that the callee might not preserve them. This is easy to diagnose here, 5416 // but can be very challenging to debug. 5417 if (auto *Caller = getCurFunctionDecl()) 5418 if (Caller->hasAttr<ARMInterruptAttr>()) { 5419 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5420 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5421 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5422 } 5423 5424 // Promote the function operand. 5425 // We special-case function promotion here because we only allow promoting 5426 // builtin functions to function pointers in the callee of a call. 5427 ExprResult Result; 5428 if (BuiltinID && 5429 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5430 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5431 CK_BuiltinFnToFnPtr).get(); 5432 } else { 5433 Result = CallExprUnaryConversions(Fn); 5434 } 5435 if (Result.isInvalid()) 5436 return ExprError(); 5437 Fn = Result.get(); 5438 5439 // Make the call expr early, before semantic checks. This guarantees cleanup 5440 // of arguments and function on error. 5441 CallExpr *TheCall; 5442 if (Config) 5443 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5444 cast<CallExpr>(Config), Args, 5445 Context.BoolTy, VK_RValue, 5446 RParenLoc); 5447 else 5448 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5449 VK_RValue, RParenLoc); 5450 5451 if (!getLangOpts().CPlusPlus) { 5452 // C cannot always handle TypoExpr nodes in builtin calls and direct 5453 // function calls as their argument checking don't necessarily handle 5454 // dependent types properly, so make sure any TypoExprs have been 5455 // dealt with. 5456 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5457 if (!Result.isUsable()) return ExprError(); 5458 TheCall = dyn_cast<CallExpr>(Result.get()); 5459 if (!TheCall) return Result; 5460 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5461 } 5462 5463 // Bail out early if calling a builtin with custom typechecking. 5464 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5465 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5466 5467 retry: 5468 const FunctionType *FuncT; 5469 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5470 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5471 // have type pointer to function". 5472 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5473 if (!FuncT) 5474 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5475 << Fn->getType() << Fn->getSourceRange()); 5476 } else if (const BlockPointerType *BPT = 5477 Fn->getType()->getAs<BlockPointerType>()) { 5478 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5479 } else { 5480 // Handle calls to expressions of unknown-any type. 5481 if (Fn->getType() == Context.UnknownAnyTy) { 5482 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5483 if (rewrite.isInvalid()) return ExprError(); 5484 Fn = rewrite.get(); 5485 TheCall->setCallee(Fn); 5486 goto retry; 5487 } 5488 5489 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5490 << Fn->getType() << Fn->getSourceRange()); 5491 } 5492 5493 if (getLangOpts().CUDA) { 5494 if (Config) { 5495 // CUDA: Kernel calls must be to global functions 5496 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5497 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5498 << FDecl->getName() << Fn->getSourceRange()); 5499 5500 // CUDA: Kernel function must have 'void' return type 5501 if (!FuncT->getReturnType()->isVoidType()) 5502 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5503 << Fn->getType() << Fn->getSourceRange()); 5504 } else { 5505 // CUDA: Calls to global functions must be configured 5506 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5507 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5508 << FDecl->getName() << Fn->getSourceRange()); 5509 } 5510 } 5511 5512 // Check for a valid return type 5513 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5514 FDecl)) 5515 return ExprError(); 5516 5517 // We know the result type of the call, set it. 5518 TheCall->setType(FuncT->getCallResultType(Context)); 5519 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5520 5521 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5522 if (Proto) { 5523 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5524 IsExecConfig)) 5525 return ExprError(); 5526 } else { 5527 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5528 5529 if (FDecl) { 5530 // Check if we have too few/too many template arguments, based 5531 // on our knowledge of the function definition. 5532 const FunctionDecl *Def = nullptr; 5533 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5534 Proto = Def->getType()->getAs<FunctionProtoType>(); 5535 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5536 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5537 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5538 } 5539 5540 // If the function we're calling isn't a function prototype, but we have 5541 // a function prototype from a prior declaratiom, use that prototype. 5542 if (!FDecl->hasPrototype()) 5543 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5544 } 5545 5546 // Promote the arguments (C99 6.5.2.2p6). 5547 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5548 Expr *Arg = Args[i]; 5549 5550 if (Proto && i < Proto->getNumParams()) { 5551 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5552 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5553 ExprResult ArgE = 5554 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5555 if (ArgE.isInvalid()) 5556 return true; 5557 5558 Arg = ArgE.getAs<Expr>(); 5559 5560 } else { 5561 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5562 5563 if (ArgE.isInvalid()) 5564 return true; 5565 5566 Arg = ArgE.getAs<Expr>(); 5567 } 5568 5569 if (RequireCompleteType(Arg->getLocStart(), 5570 Arg->getType(), 5571 diag::err_call_incomplete_argument, Arg)) 5572 return ExprError(); 5573 5574 TheCall->setArg(i, Arg); 5575 } 5576 } 5577 5578 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5579 if (!Method->isStatic()) 5580 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5581 << Fn->getSourceRange()); 5582 5583 // Check for sentinels 5584 if (NDecl) 5585 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5586 5587 // Do special checking on direct calls to functions. 5588 if (FDecl) { 5589 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5590 return ExprError(); 5591 5592 if (BuiltinID) 5593 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5594 } else if (NDecl) { 5595 if (CheckPointerCall(NDecl, TheCall, Proto)) 5596 return ExprError(); 5597 } else { 5598 if (CheckOtherCall(TheCall, Proto)) 5599 return ExprError(); 5600 } 5601 5602 return MaybeBindToTemporary(TheCall); 5603 } 5604 5605 ExprResult 5606 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5607 SourceLocation RParenLoc, Expr *InitExpr) { 5608 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5609 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5610 5611 TypeSourceInfo *TInfo; 5612 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5613 if (!TInfo) 5614 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5615 5616 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5617 } 5618 5619 ExprResult 5620 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5621 SourceLocation RParenLoc, Expr *LiteralExpr) { 5622 QualType literalType = TInfo->getType(); 5623 5624 if (literalType->isArrayType()) { 5625 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5626 diag::err_illegal_decl_array_incomplete_type, 5627 SourceRange(LParenLoc, 5628 LiteralExpr->getSourceRange().getEnd()))) 5629 return ExprError(); 5630 if (literalType->isVariableArrayType()) 5631 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5632 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5633 } else if (!literalType->isDependentType() && 5634 RequireCompleteType(LParenLoc, literalType, 5635 diag::err_typecheck_decl_incomplete_type, 5636 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5637 return ExprError(); 5638 5639 InitializedEntity Entity 5640 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5641 InitializationKind Kind 5642 = InitializationKind::CreateCStyleCast(LParenLoc, 5643 SourceRange(LParenLoc, RParenLoc), 5644 /*InitList=*/true); 5645 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5646 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5647 &literalType); 5648 if (Result.isInvalid()) 5649 return ExprError(); 5650 LiteralExpr = Result.get(); 5651 5652 bool isFileScope = !CurContext->isFunctionOrMethod(); 5653 if (isFileScope && 5654 !LiteralExpr->isTypeDependent() && 5655 !LiteralExpr->isValueDependent() && 5656 !literalType->isDependentType()) { // 6.5.2.5p3 5657 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5658 return ExprError(); 5659 } 5660 5661 // In C, compound literals are l-values for some reason. 5662 // For GCC compatibility, in C++, file-scope array compound literals with 5663 // constant initializers are also l-values, and compound literals are 5664 // otherwise prvalues. 5665 // 5666 // (GCC also treats C++ list-initialized file-scope array prvalues with 5667 // constant initializers as l-values, but that's non-conforming, so we don't 5668 // follow it there.) 5669 // 5670 // FIXME: It would be better to handle the lvalue cases as materializing and 5671 // lifetime-extending a temporary object, but our materialized temporaries 5672 // representation only supports lifetime extension from a variable, not "out 5673 // of thin air". 5674 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5675 // is bound to the result of applying array-to-pointer decay to the compound 5676 // literal. 5677 // FIXME: GCC supports compound literals of reference type, which should 5678 // obviously have a value kind derived from the kind of reference involved. 5679 ExprValueKind VK = 5680 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5681 ? VK_RValue 5682 : VK_LValue; 5683 5684 return MaybeBindToTemporary( 5685 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5686 VK, LiteralExpr, isFileScope)); 5687 } 5688 5689 ExprResult 5690 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5691 SourceLocation RBraceLoc) { 5692 // Immediately handle non-overload placeholders. Overloads can be 5693 // resolved contextually, but everything else here can't. 5694 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5695 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5696 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5697 5698 // Ignore failures; dropping the entire initializer list because 5699 // of one failure would be terrible for indexing/etc. 5700 if (result.isInvalid()) continue; 5701 5702 InitArgList[I] = result.get(); 5703 } 5704 } 5705 5706 // Semantic analysis for initializers is done by ActOnDeclarator() and 5707 // CheckInitializer() - it requires knowledge of the object being intialized. 5708 5709 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5710 RBraceLoc); 5711 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5712 return E; 5713 } 5714 5715 /// Do an explicit extend of the given block pointer if we're in ARC. 5716 void Sema::maybeExtendBlockObject(ExprResult &E) { 5717 assert(E.get()->getType()->isBlockPointerType()); 5718 assert(E.get()->isRValue()); 5719 5720 // Only do this in an r-value context. 5721 if (!getLangOpts().ObjCAutoRefCount) return; 5722 5723 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5724 CK_ARCExtendBlockObject, E.get(), 5725 /*base path*/ nullptr, VK_RValue); 5726 Cleanup.setExprNeedsCleanups(true); 5727 } 5728 5729 /// Prepare a conversion of the given expression to an ObjC object 5730 /// pointer type. 5731 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5732 QualType type = E.get()->getType(); 5733 if (type->isObjCObjectPointerType()) { 5734 return CK_BitCast; 5735 } else if (type->isBlockPointerType()) { 5736 maybeExtendBlockObject(E); 5737 return CK_BlockPointerToObjCPointerCast; 5738 } else { 5739 assert(type->isPointerType()); 5740 return CK_CPointerToObjCPointerCast; 5741 } 5742 } 5743 5744 /// Prepares for a scalar cast, performing all the necessary stages 5745 /// except the final cast and returning the kind required. 5746 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5747 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5748 // Also, callers should have filtered out the invalid cases with 5749 // pointers. Everything else should be possible. 5750 5751 QualType SrcTy = Src.get()->getType(); 5752 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5753 return CK_NoOp; 5754 5755 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5756 case Type::STK_MemberPointer: 5757 llvm_unreachable("member pointer type in C"); 5758 5759 case Type::STK_CPointer: 5760 case Type::STK_BlockPointer: 5761 case Type::STK_ObjCObjectPointer: 5762 switch (DestTy->getScalarTypeKind()) { 5763 case Type::STK_CPointer: { 5764 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5765 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5766 if (SrcAS != DestAS) 5767 return CK_AddressSpaceConversion; 5768 return CK_BitCast; 5769 } 5770 case Type::STK_BlockPointer: 5771 return (SrcKind == Type::STK_BlockPointer 5772 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5773 case Type::STK_ObjCObjectPointer: 5774 if (SrcKind == Type::STK_ObjCObjectPointer) 5775 return CK_BitCast; 5776 if (SrcKind == Type::STK_CPointer) 5777 return CK_CPointerToObjCPointerCast; 5778 maybeExtendBlockObject(Src); 5779 return CK_BlockPointerToObjCPointerCast; 5780 case Type::STK_Bool: 5781 return CK_PointerToBoolean; 5782 case Type::STK_Integral: 5783 return CK_PointerToIntegral; 5784 case Type::STK_Floating: 5785 case Type::STK_FloatingComplex: 5786 case Type::STK_IntegralComplex: 5787 case Type::STK_MemberPointer: 5788 llvm_unreachable("illegal cast from pointer"); 5789 } 5790 llvm_unreachable("Should have returned before this"); 5791 5792 case Type::STK_Bool: // casting from bool is like casting from an integer 5793 case Type::STK_Integral: 5794 switch (DestTy->getScalarTypeKind()) { 5795 case Type::STK_CPointer: 5796 case Type::STK_ObjCObjectPointer: 5797 case Type::STK_BlockPointer: 5798 if (Src.get()->isNullPointerConstant(Context, 5799 Expr::NPC_ValueDependentIsNull)) 5800 return CK_NullToPointer; 5801 return CK_IntegralToPointer; 5802 case Type::STK_Bool: 5803 return CK_IntegralToBoolean; 5804 case Type::STK_Integral: 5805 return CK_IntegralCast; 5806 case Type::STK_Floating: 5807 return CK_IntegralToFloating; 5808 case Type::STK_IntegralComplex: 5809 Src = ImpCastExprToType(Src.get(), 5810 DestTy->castAs<ComplexType>()->getElementType(), 5811 CK_IntegralCast); 5812 return CK_IntegralRealToComplex; 5813 case Type::STK_FloatingComplex: 5814 Src = ImpCastExprToType(Src.get(), 5815 DestTy->castAs<ComplexType>()->getElementType(), 5816 CK_IntegralToFloating); 5817 return CK_FloatingRealToComplex; 5818 case Type::STK_MemberPointer: 5819 llvm_unreachable("member pointer type in C"); 5820 } 5821 llvm_unreachable("Should have returned before this"); 5822 5823 case Type::STK_Floating: 5824 switch (DestTy->getScalarTypeKind()) { 5825 case Type::STK_Floating: 5826 return CK_FloatingCast; 5827 case Type::STK_Bool: 5828 return CK_FloatingToBoolean; 5829 case Type::STK_Integral: 5830 return CK_FloatingToIntegral; 5831 case Type::STK_FloatingComplex: 5832 Src = ImpCastExprToType(Src.get(), 5833 DestTy->castAs<ComplexType>()->getElementType(), 5834 CK_FloatingCast); 5835 return CK_FloatingRealToComplex; 5836 case Type::STK_IntegralComplex: 5837 Src = ImpCastExprToType(Src.get(), 5838 DestTy->castAs<ComplexType>()->getElementType(), 5839 CK_FloatingToIntegral); 5840 return CK_IntegralRealToComplex; 5841 case Type::STK_CPointer: 5842 case Type::STK_ObjCObjectPointer: 5843 case Type::STK_BlockPointer: 5844 llvm_unreachable("valid float->pointer cast?"); 5845 case Type::STK_MemberPointer: 5846 llvm_unreachable("member pointer type in C"); 5847 } 5848 llvm_unreachable("Should have returned before this"); 5849 5850 case Type::STK_FloatingComplex: 5851 switch (DestTy->getScalarTypeKind()) { 5852 case Type::STK_FloatingComplex: 5853 return CK_FloatingComplexCast; 5854 case Type::STK_IntegralComplex: 5855 return CK_FloatingComplexToIntegralComplex; 5856 case Type::STK_Floating: { 5857 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5858 if (Context.hasSameType(ET, DestTy)) 5859 return CK_FloatingComplexToReal; 5860 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5861 return CK_FloatingCast; 5862 } 5863 case Type::STK_Bool: 5864 return CK_FloatingComplexToBoolean; 5865 case Type::STK_Integral: 5866 Src = ImpCastExprToType(Src.get(), 5867 SrcTy->castAs<ComplexType>()->getElementType(), 5868 CK_FloatingComplexToReal); 5869 return CK_FloatingToIntegral; 5870 case Type::STK_CPointer: 5871 case Type::STK_ObjCObjectPointer: 5872 case Type::STK_BlockPointer: 5873 llvm_unreachable("valid complex float->pointer cast?"); 5874 case Type::STK_MemberPointer: 5875 llvm_unreachable("member pointer type in C"); 5876 } 5877 llvm_unreachable("Should have returned before this"); 5878 5879 case Type::STK_IntegralComplex: 5880 switch (DestTy->getScalarTypeKind()) { 5881 case Type::STK_FloatingComplex: 5882 return CK_IntegralComplexToFloatingComplex; 5883 case Type::STK_IntegralComplex: 5884 return CK_IntegralComplexCast; 5885 case Type::STK_Integral: { 5886 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5887 if (Context.hasSameType(ET, DestTy)) 5888 return CK_IntegralComplexToReal; 5889 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5890 return CK_IntegralCast; 5891 } 5892 case Type::STK_Bool: 5893 return CK_IntegralComplexToBoolean; 5894 case Type::STK_Floating: 5895 Src = ImpCastExprToType(Src.get(), 5896 SrcTy->castAs<ComplexType>()->getElementType(), 5897 CK_IntegralComplexToReal); 5898 return CK_IntegralToFloating; 5899 case Type::STK_CPointer: 5900 case Type::STK_ObjCObjectPointer: 5901 case Type::STK_BlockPointer: 5902 llvm_unreachable("valid complex int->pointer cast?"); 5903 case Type::STK_MemberPointer: 5904 llvm_unreachable("member pointer type in C"); 5905 } 5906 llvm_unreachable("Should have returned before this"); 5907 } 5908 5909 llvm_unreachable("Unhandled scalar cast"); 5910 } 5911 5912 static bool breakDownVectorType(QualType type, uint64_t &len, 5913 QualType &eltType) { 5914 // Vectors are simple. 5915 if (const VectorType *vecType = type->getAs<VectorType>()) { 5916 len = vecType->getNumElements(); 5917 eltType = vecType->getElementType(); 5918 assert(eltType->isScalarType()); 5919 return true; 5920 } 5921 5922 // We allow lax conversion to and from non-vector types, but only if 5923 // they're real types (i.e. non-complex, non-pointer scalar types). 5924 if (!type->isRealType()) return false; 5925 5926 len = 1; 5927 eltType = type; 5928 return true; 5929 } 5930 5931 /// Are the two types lax-compatible vector types? That is, given 5932 /// that one of them is a vector, do they have equal storage sizes, 5933 /// where the storage size is the number of elements times the element 5934 /// size? 5935 /// 5936 /// This will also return false if either of the types is neither a 5937 /// vector nor a real type. 5938 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5939 assert(destTy->isVectorType() || srcTy->isVectorType()); 5940 5941 // Disallow lax conversions between scalars and ExtVectors (these 5942 // conversions are allowed for other vector types because common headers 5943 // depend on them). Most scalar OP ExtVector cases are handled by the 5944 // splat path anyway, which does what we want (convert, not bitcast). 5945 // What this rules out for ExtVectors is crazy things like char4*float. 5946 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5947 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5948 5949 uint64_t srcLen, destLen; 5950 QualType srcEltTy, destEltTy; 5951 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5952 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5953 5954 // ASTContext::getTypeSize will return the size rounded up to a 5955 // power of 2, so instead of using that, we need to use the raw 5956 // element size multiplied by the element count. 5957 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5958 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5959 5960 return (srcLen * srcEltSize == destLen * destEltSize); 5961 } 5962 5963 /// Is this a legal conversion between two types, one of which is 5964 /// known to be a vector type? 5965 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5966 assert(destTy->isVectorType() || srcTy->isVectorType()); 5967 5968 if (!Context.getLangOpts().LaxVectorConversions) 5969 return false; 5970 return areLaxCompatibleVectorTypes(srcTy, destTy); 5971 } 5972 5973 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5974 CastKind &Kind) { 5975 assert(VectorTy->isVectorType() && "Not a vector type!"); 5976 5977 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5978 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5979 return Diag(R.getBegin(), 5980 Ty->isVectorType() ? 5981 diag::err_invalid_conversion_between_vectors : 5982 diag::err_invalid_conversion_between_vector_and_integer) 5983 << VectorTy << Ty << R; 5984 } else 5985 return Diag(R.getBegin(), 5986 diag::err_invalid_conversion_between_vector_and_scalar) 5987 << VectorTy << Ty << R; 5988 5989 Kind = CK_BitCast; 5990 return false; 5991 } 5992 5993 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5994 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5995 5996 if (DestElemTy == SplattedExpr->getType()) 5997 return SplattedExpr; 5998 5999 assert(DestElemTy->isFloatingType() || 6000 DestElemTy->isIntegralOrEnumerationType()); 6001 6002 CastKind CK; 6003 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6004 // OpenCL requires that we convert `true` boolean expressions to -1, but 6005 // only when splatting vectors. 6006 if (DestElemTy->isFloatingType()) { 6007 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6008 // in two steps: boolean to signed integral, then to floating. 6009 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6010 CK_BooleanToSignedIntegral); 6011 SplattedExpr = CastExprRes.get(); 6012 CK = CK_IntegralToFloating; 6013 } else { 6014 CK = CK_BooleanToSignedIntegral; 6015 } 6016 } else { 6017 ExprResult CastExprRes = SplattedExpr; 6018 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6019 if (CastExprRes.isInvalid()) 6020 return ExprError(); 6021 SplattedExpr = CastExprRes.get(); 6022 } 6023 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6024 } 6025 6026 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6027 Expr *CastExpr, CastKind &Kind) { 6028 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6029 6030 QualType SrcTy = CastExpr->getType(); 6031 6032 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6033 // an ExtVectorType. 6034 // In OpenCL, casts between vectors of different types are not allowed. 6035 // (See OpenCL 6.2). 6036 if (SrcTy->isVectorType()) { 6037 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6038 (getLangOpts().OpenCL && 6039 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6040 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6041 << DestTy << SrcTy << R; 6042 return ExprError(); 6043 } 6044 Kind = CK_BitCast; 6045 return CastExpr; 6046 } 6047 6048 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6049 // conversion will take place first from scalar to elt type, and then 6050 // splat from elt type to vector. 6051 if (SrcTy->isPointerType()) 6052 return Diag(R.getBegin(), 6053 diag::err_invalid_conversion_between_vector_and_scalar) 6054 << DestTy << SrcTy << R; 6055 6056 Kind = CK_VectorSplat; 6057 return prepareVectorSplat(DestTy, CastExpr); 6058 } 6059 6060 ExprResult 6061 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6062 Declarator &D, ParsedType &Ty, 6063 SourceLocation RParenLoc, Expr *CastExpr) { 6064 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6065 "ActOnCastExpr(): missing type or expr"); 6066 6067 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6068 if (D.isInvalidType()) 6069 return ExprError(); 6070 6071 if (getLangOpts().CPlusPlus) { 6072 // Check that there are no default arguments (C++ only). 6073 CheckExtraCXXDefaultArguments(D); 6074 } else { 6075 // Make sure any TypoExprs have been dealt with. 6076 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6077 if (!Res.isUsable()) 6078 return ExprError(); 6079 CastExpr = Res.get(); 6080 } 6081 6082 checkUnusedDeclAttributes(D); 6083 6084 QualType castType = castTInfo->getType(); 6085 Ty = CreateParsedType(castType, castTInfo); 6086 6087 bool isVectorLiteral = false; 6088 6089 // Check for an altivec or OpenCL literal, 6090 // i.e. all the elements are integer constants. 6091 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6092 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6093 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6094 && castType->isVectorType() && (PE || PLE)) { 6095 if (PLE && PLE->getNumExprs() == 0) { 6096 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6097 return ExprError(); 6098 } 6099 if (PE || PLE->getNumExprs() == 1) { 6100 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6101 if (!E->getType()->isVectorType()) 6102 isVectorLiteral = true; 6103 } 6104 else 6105 isVectorLiteral = true; 6106 } 6107 6108 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6109 // then handle it as such. 6110 if (isVectorLiteral) 6111 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6112 6113 // If the Expr being casted is a ParenListExpr, handle it specially. 6114 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6115 // sequence of BinOp comma operators. 6116 if (isa<ParenListExpr>(CastExpr)) { 6117 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6118 if (Result.isInvalid()) return ExprError(); 6119 CastExpr = Result.get(); 6120 } 6121 6122 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6123 !getSourceManager().isInSystemMacro(LParenLoc)) 6124 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6125 6126 CheckTollFreeBridgeCast(castType, CastExpr); 6127 6128 CheckObjCBridgeRelatedCast(castType, CastExpr); 6129 6130 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6131 6132 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6133 } 6134 6135 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6136 SourceLocation RParenLoc, Expr *E, 6137 TypeSourceInfo *TInfo) { 6138 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6139 "Expected paren or paren list expression"); 6140 6141 Expr **exprs; 6142 unsigned numExprs; 6143 Expr *subExpr; 6144 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6145 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6146 LiteralLParenLoc = PE->getLParenLoc(); 6147 LiteralRParenLoc = PE->getRParenLoc(); 6148 exprs = PE->getExprs(); 6149 numExprs = PE->getNumExprs(); 6150 } else { // isa<ParenExpr> by assertion at function entrance 6151 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6152 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6153 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6154 exprs = &subExpr; 6155 numExprs = 1; 6156 } 6157 6158 QualType Ty = TInfo->getType(); 6159 assert(Ty->isVectorType() && "Expected vector type"); 6160 6161 SmallVector<Expr *, 8> initExprs; 6162 const VectorType *VTy = Ty->getAs<VectorType>(); 6163 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6164 6165 // '(...)' form of vector initialization in AltiVec: the number of 6166 // initializers must be one or must match the size of the vector. 6167 // If a single value is specified in the initializer then it will be 6168 // replicated to all the components of the vector 6169 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6170 // The number of initializers must be one or must match the size of the 6171 // vector. If a single value is specified in the initializer then it will 6172 // be replicated to all the components of the vector 6173 if (numExprs == 1) { 6174 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6175 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6176 if (Literal.isInvalid()) 6177 return ExprError(); 6178 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6179 PrepareScalarCast(Literal, ElemTy)); 6180 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6181 } 6182 else if (numExprs < numElems) { 6183 Diag(E->getExprLoc(), 6184 diag::err_incorrect_number_of_vector_initializers); 6185 return ExprError(); 6186 } 6187 else 6188 initExprs.append(exprs, exprs + numExprs); 6189 } 6190 else { 6191 // For OpenCL, when the number of initializers is a single value, 6192 // it will be replicated to all components of the vector. 6193 if (getLangOpts().OpenCL && 6194 VTy->getVectorKind() == VectorType::GenericVector && 6195 numExprs == 1) { 6196 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6197 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6198 if (Literal.isInvalid()) 6199 return ExprError(); 6200 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6201 PrepareScalarCast(Literal, ElemTy)); 6202 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6203 } 6204 6205 initExprs.append(exprs, exprs + numExprs); 6206 } 6207 // FIXME: This means that pretty-printing the final AST will produce curly 6208 // braces instead of the original commas. 6209 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6210 initExprs, LiteralRParenLoc); 6211 initE->setType(Ty); 6212 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6213 } 6214 6215 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6216 /// the ParenListExpr into a sequence of comma binary operators. 6217 ExprResult 6218 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6219 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6220 if (!E) 6221 return OrigExpr; 6222 6223 ExprResult Result(E->getExpr(0)); 6224 6225 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6226 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6227 E->getExpr(i)); 6228 6229 if (Result.isInvalid()) return ExprError(); 6230 6231 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6232 } 6233 6234 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6235 SourceLocation R, 6236 MultiExprArg Val) { 6237 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6238 return expr; 6239 } 6240 6241 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6242 /// constant and the other is not a pointer. Returns true if a diagnostic is 6243 /// emitted. 6244 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6245 SourceLocation QuestionLoc) { 6246 Expr *NullExpr = LHSExpr; 6247 Expr *NonPointerExpr = RHSExpr; 6248 Expr::NullPointerConstantKind NullKind = 6249 NullExpr->isNullPointerConstant(Context, 6250 Expr::NPC_ValueDependentIsNotNull); 6251 6252 if (NullKind == Expr::NPCK_NotNull) { 6253 NullExpr = RHSExpr; 6254 NonPointerExpr = LHSExpr; 6255 NullKind = 6256 NullExpr->isNullPointerConstant(Context, 6257 Expr::NPC_ValueDependentIsNotNull); 6258 } 6259 6260 if (NullKind == Expr::NPCK_NotNull) 6261 return false; 6262 6263 if (NullKind == Expr::NPCK_ZeroExpression) 6264 return false; 6265 6266 if (NullKind == Expr::NPCK_ZeroLiteral) { 6267 // In this case, check to make sure that we got here from a "NULL" 6268 // string in the source code. 6269 NullExpr = NullExpr->IgnoreParenImpCasts(); 6270 SourceLocation loc = NullExpr->getExprLoc(); 6271 if (!findMacroSpelling(loc, "NULL")) 6272 return false; 6273 } 6274 6275 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6276 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6277 << NonPointerExpr->getType() << DiagType 6278 << NonPointerExpr->getSourceRange(); 6279 return true; 6280 } 6281 6282 /// \brief Return false if the condition expression is valid, true otherwise. 6283 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6284 QualType CondTy = Cond->getType(); 6285 6286 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6287 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6288 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6289 << CondTy << Cond->getSourceRange(); 6290 return true; 6291 } 6292 6293 // C99 6.5.15p2 6294 if (CondTy->isScalarType()) return false; 6295 6296 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6297 << CondTy << Cond->getSourceRange(); 6298 return true; 6299 } 6300 6301 /// \brief Handle when one or both operands are void type. 6302 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6303 ExprResult &RHS) { 6304 Expr *LHSExpr = LHS.get(); 6305 Expr *RHSExpr = RHS.get(); 6306 6307 if (!LHSExpr->getType()->isVoidType()) 6308 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6309 << RHSExpr->getSourceRange(); 6310 if (!RHSExpr->getType()->isVoidType()) 6311 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6312 << LHSExpr->getSourceRange(); 6313 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6314 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6315 return S.Context.VoidTy; 6316 } 6317 6318 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6319 /// true otherwise. 6320 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6321 QualType PointerTy) { 6322 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6323 !NullExpr.get()->isNullPointerConstant(S.Context, 6324 Expr::NPC_ValueDependentIsNull)) 6325 return true; 6326 6327 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6328 return false; 6329 } 6330 6331 /// \brief Checks compatibility between two pointers and return the resulting 6332 /// type. 6333 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6334 ExprResult &RHS, 6335 SourceLocation Loc) { 6336 QualType LHSTy = LHS.get()->getType(); 6337 QualType RHSTy = RHS.get()->getType(); 6338 6339 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6340 // Two identical pointers types are always compatible. 6341 return LHSTy; 6342 } 6343 6344 QualType lhptee, rhptee; 6345 6346 // Get the pointee types. 6347 bool IsBlockPointer = false; 6348 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6349 lhptee = LHSBTy->getPointeeType(); 6350 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6351 IsBlockPointer = true; 6352 } else { 6353 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6354 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6355 } 6356 6357 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6358 // differently qualified versions of compatible types, the result type is 6359 // a pointer to an appropriately qualified version of the composite 6360 // type. 6361 6362 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6363 // clause doesn't make sense for our extensions. E.g. address space 2 should 6364 // be incompatible with address space 3: they may live on different devices or 6365 // anything. 6366 Qualifiers lhQual = lhptee.getQualifiers(); 6367 Qualifiers rhQual = rhptee.getQualifiers(); 6368 6369 LangAS ResultAddrSpace = LangAS::Default; 6370 LangAS LAddrSpace = lhQual.getAddressSpace(); 6371 LangAS RAddrSpace = rhQual.getAddressSpace(); 6372 if (S.getLangOpts().OpenCL) { 6373 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6374 // spaces is disallowed. 6375 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6376 ResultAddrSpace = LAddrSpace; 6377 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6378 ResultAddrSpace = RAddrSpace; 6379 else { 6380 S.Diag(Loc, 6381 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6382 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6383 << RHS.get()->getSourceRange(); 6384 return QualType(); 6385 } 6386 } 6387 6388 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6389 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6390 lhQual.removeCVRQualifiers(); 6391 rhQual.removeCVRQualifiers(); 6392 6393 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6394 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6395 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6396 // qual types are compatible iff 6397 // * corresponded types are compatible 6398 // * CVR qualifiers are equal 6399 // * address spaces are equal 6400 // Thus for conditional operator we merge CVR and address space unqualified 6401 // pointees and if there is a composite type we return a pointer to it with 6402 // merged qualifiers. 6403 if (S.getLangOpts().OpenCL) { 6404 LHSCastKind = LAddrSpace == ResultAddrSpace 6405 ? CK_BitCast 6406 : CK_AddressSpaceConversion; 6407 RHSCastKind = RAddrSpace == ResultAddrSpace 6408 ? CK_BitCast 6409 : CK_AddressSpaceConversion; 6410 lhQual.removeAddressSpace(); 6411 rhQual.removeAddressSpace(); 6412 } 6413 6414 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6415 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6416 6417 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6418 6419 if (CompositeTy.isNull()) { 6420 // In this situation, we assume void* type. No especially good 6421 // reason, but this is what gcc does, and we do have to pick 6422 // to get a consistent AST. 6423 QualType incompatTy; 6424 incompatTy = S.Context.getPointerType( 6425 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6426 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6427 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6428 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6429 // for casts between types with incompatible address space qualifiers. 6430 // For the following code the compiler produces casts between global and 6431 // local address spaces of the corresponded innermost pointees: 6432 // local int *global *a; 6433 // global int *global *b; 6434 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6435 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6436 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6437 << RHS.get()->getSourceRange(); 6438 return incompatTy; 6439 } 6440 6441 // The pointer types are compatible. 6442 // In case of OpenCL ResultTy should have the address space qualifier 6443 // which is a superset of address spaces of both the 2nd and the 3rd 6444 // operands of the conditional operator. 6445 QualType ResultTy = [&, ResultAddrSpace]() { 6446 if (S.getLangOpts().OpenCL) { 6447 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6448 CompositeQuals.setAddressSpace(ResultAddrSpace); 6449 return S.Context 6450 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6451 .withCVRQualifiers(MergedCVRQual); 6452 } 6453 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6454 }(); 6455 if (IsBlockPointer) 6456 ResultTy = S.Context.getBlockPointerType(ResultTy); 6457 else 6458 ResultTy = S.Context.getPointerType(ResultTy); 6459 6460 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6461 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6462 return ResultTy; 6463 } 6464 6465 /// \brief Return the resulting type when the operands are both block pointers. 6466 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6467 ExprResult &LHS, 6468 ExprResult &RHS, 6469 SourceLocation Loc) { 6470 QualType LHSTy = LHS.get()->getType(); 6471 QualType RHSTy = RHS.get()->getType(); 6472 6473 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6474 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6475 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6476 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6477 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6478 return destType; 6479 } 6480 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6481 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6482 << RHS.get()->getSourceRange(); 6483 return QualType(); 6484 } 6485 6486 // We have 2 block pointer types. 6487 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6488 } 6489 6490 /// \brief Return the resulting type when the operands are both pointers. 6491 static QualType 6492 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6493 ExprResult &RHS, 6494 SourceLocation Loc) { 6495 // get the pointer types 6496 QualType LHSTy = LHS.get()->getType(); 6497 QualType RHSTy = RHS.get()->getType(); 6498 6499 // get the "pointed to" types 6500 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6501 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6502 6503 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6504 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6505 // Figure out necessary qualifiers (C99 6.5.15p6) 6506 QualType destPointee 6507 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6508 QualType destType = S.Context.getPointerType(destPointee); 6509 // Add qualifiers if necessary. 6510 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6511 // Promote to void*. 6512 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6513 return destType; 6514 } 6515 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6516 QualType destPointee 6517 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6518 QualType destType = S.Context.getPointerType(destPointee); 6519 // Add qualifiers if necessary. 6520 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6521 // Promote to void*. 6522 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6523 return destType; 6524 } 6525 6526 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6527 } 6528 6529 /// \brief Return false if the first expression is not an integer and the second 6530 /// expression is not a pointer, true otherwise. 6531 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6532 Expr* PointerExpr, SourceLocation Loc, 6533 bool IsIntFirstExpr) { 6534 if (!PointerExpr->getType()->isPointerType() || 6535 !Int.get()->getType()->isIntegerType()) 6536 return false; 6537 6538 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6539 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6540 6541 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6542 << Expr1->getType() << Expr2->getType() 6543 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6544 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6545 CK_IntegralToPointer); 6546 return true; 6547 } 6548 6549 /// \brief Simple conversion between integer and floating point types. 6550 /// 6551 /// Used when handling the OpenCL conditional operator where the 6552 /// condition is a vector while the other operands are scalar. 6553 /// 6554 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6555 /// types are either integer or floating type. Between the two 6556 /// operands, the type with the higher rank is defined as the "result 6557 /// type". The other operand needs to be promoted to the same type. No 6558 /// other type promotion is allowed. We cannot use 6559 /// UsualArithmeticConversions() for this purpose, since it always 6560 /// promotes promotable types. 6561 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6562 ExprResult &RHS, 6563 SourceLocation QuestionLoc) { 6564 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6565 if (LHS.isInvalid()) 6566 return QualType(); 6567 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6568 if (RHS.isInvalid()) 6569 return QualType(); 6570 6571 // For conversion purposes, we ignore any qualifiers. 6572 // For example, "const float" and "float" are equivalent. 6573 QualType LHSType = 6574 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6575 QualType RHSType = 6576 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6577 6578 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6579 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6580 << LHSType << LHS.get()->getSourceRange(); 6581 return QualType(); 6582 } 6583 6584 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6585 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6586 << RHSType << RHS.get()->getSourceRange(); 6587 return QualType(); 6588 } 6589 6590 // If both types are identical, no conversion is needed. 6591 if (LHSType == RHSType) 6592 return LHSType; 6593 6594 // Now handle "real" floating types (i.e. float, double, long double). 6595 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6596 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6597 /*IsCompAssign = */ false); 6598 6599 // Finally, we have two differing integer types. 6600 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6601 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6602 } 6603 6604 /// \brief Convert scalar operands to a vector that matches the 6605 /// condition in length. 6606 /// 6607 /// Used when handling the OpenCL conditional operator where the 6608 /// condition is a vector while the other operands are scalar. 6609 /// 6610 /// We first compute the "result type" for the scalar operands 6611 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6612 /// into a vector of that type where the length matches the condition 6613 /// vector type. s6.11.6 requires that the element types of the result 6614 /// and the condition must have the same number of bits. 6615 static QualType 6616 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6617 QualType CondTy, SourceLocation QuestionLoc) { 6618 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6619 if (ResTy.isNull()) return QualType(); 6620 6621 const VectorType *CV = CondTy->getAs<VectorType>(); 6622 assert(CV); 6623 6624 // Determine the vector result type 6625 unsigned NumElements = CV->getNumElements(); 6626 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6627 6628 // Ensure that all types have the same number of bits 6629 if (S.Context.getTypeSize(CV->getElementType()) 6630 != S.Context.getTypeSize(ResTy)) { 6631 // Since VectorTy is created internally, it does not pretty print 6632 // with an OpenCL name. Instead, we just print a description. 6633 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6634 SmallString<64> Str; 6635 llvm::raw_svector_ostream OS(Str); 6636 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6637 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6638 << CondTy << OS.str(); 6639 return QualType(); 6640 } 6641 6642 // Convert operands to the vector result type 6643 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6644 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6645 6646 return VectorTy; 6647 } 6648 6649 /// \brief Return false if this is a valid OpenCL condition vector 6650 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6651 SourceLocation QuestionLoc) { 6652 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6653 // integral type. 6654 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6655 assert(CondTy); 6656 QualType EleTy = CondTy->getElementType(); 6657 if (EleTy->isIntegerType()) return false; 6658 6659 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6660 << Cond->getType() << Cond->getSourceRange(); 6661 return true; 6662 } 6663 6664 /// \brief Return false if the vector condition type and the vector 6665 /// result type are compatible. 6666 /// 6667 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6668 /// number of elements, and their element types have the same number 6669 /// of bits. 6670 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6671 SourceLocation QuestionLoc) { 6672 const VectorType *CV = CondTy->getAs<VectorType>(); 6673 const VectorType *RV = VecResTy->getAs<VectorType>(); 6674 assert(CV && RV); 6675 6676 if (CV->getNumElements() != RV->getNumElements()) { 6677 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6678 << CondTy << VecResTy; 6679 return true; 6680 } 6681 6682 QualType CVE = CV->getElementType(); 6683 QualType RVE = RV->getElementType(); 6684 6685 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6686 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6687 << CondTy << VecResTy; 6688 return true; 6689 } 6690 6691 return false; 6692 } 6693 6694 /// \brief Return the resulting type for the conditional operator in 6695 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6696 /// s6.3.i) when the condition is a vector type. 6697 static QualType 6698 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6699 ExprResult &LHS, ExprResult &RHS, 6700 SourceLocation QuestionLoc) { 6701 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6702 if (Cond.isInvalid()) 6703 return QualType(); 6704 QualType CondTy = Cond.get()->getType(); 6705 6706 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6707 return QualType(); 6708 6709 // If either operand is a vector then find the vector type of the 6710 // result as specified in OpenCL v1.1 s6.3.i. 6711 if (LHS.get()->getType()->isVectorType() || 6712 RHS.get()->getType()->isVectorType()) { 6713 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6714 /*isCompAssign*/false, 6715 /*AllowBothBool*/true, 6716 /*AllowBoolConversions*/false); 6717 if (VecResTy.isNull()) return QualType(); 6718 // The result type must match the condition type as specified in 6719 // OpenCL v1.1 s6.11.6. 6720 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6721 return QualType(); 6722 return VecResTy; 6723 } 6724 6725 // Both operands are scalar. 6726 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6727 } 6728 6729 /// \brief Return true if the Expr is block type 6730 static bool checkBlockType(Sema &S, const Expr *E) { 6731 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6732 QualType Ty = CE->getCallee()->getType(); 6733 if (Ty->isBlockPointerType()) { 6734 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6735 return true; 6736 } 6737 } 6738 return false; 6739 } 6740 6741 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6742 /// In that case, LHS = cond. 6743 /// C99 6.5.15 6744 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6745 ExprResult &RHS, ExprValueKind &VK, 6746 ExprObjectKind &OK, 6747 SourceLocation QuestionLoc) { 6748 6749 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6750 if (!LHSResult.isUsable()) return QualType(); 6751 LHS = LHSResult; 6752 6753 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6754 if (!RHSResult.isUsable()) return QualType(); 6755 RHS = RHSResult; 6756 6757 // C++ is sufficiently different to merit its own checker. 6758 if (getLangOpts().CPlusPlus) 6759 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6760 6761 VK = VK_RValue; 6762 OK = OK_Ordinary; 6763 6764 // The OpenCL operator with a vector condition is sufficiently 6765 // different to merit its own checker. 6766 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6767 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6768 6769 // First, check the condition. 6770 Cond = UsualUnaryConversions(Cond.get()); 6771 if (Cond.isInvalid()) 6772 return QualType(); 6773 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6774 return QualType(); 6775 6776 // Now check the two expressions. 6777 if (LHS.get()->getType()->isVectorType() || 6778 RHS.get()->getType()->isVectorType()) 6779 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6780 /*AllowBothBool*/true, 6781 /*AllowBoolConversions*/false); 6782 6783 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6784 if (LHS.isInvalid() || RHS.isInvalid()) 6785 return QualType(); 6786 6787 QualType LHSTy = LHS.get()->getType(); 6788 QualType RHSTy = RHS.get()->getType(); 6789 6790 // Diagnose attempts to convert between __float128 and long double where 6791 // such conversions currently can't be handled. 6792 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6793 Diag(QuestionLoc, 6794 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6795 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6796 return QualType(); 6797 } 6798 6799 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6800 // selection operator (?:). 6801 if (getLangOpts().OpenCL && 6802 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6803 return QualType(); 6804 } 6805 6806 // If both operands have arithmetic type, do the usual arithmetic conversions 6807 // to find a common type: C99 6.5.15p3,5. 6808 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6809 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6810 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6811 6812 return ResTy; 6813 } 6814 6815 // If both operands are the same structure or union type, the result is that 6816 // type. 6817 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6818 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6819 if (LHSRT->getDecl() == RHSRT->getDecl()) 6820 // "If both the operands have structure or union type, the result has 6821 // that type." This implies that CV qualifiers are dropped. 6822 return LHSTy.getUnqualifiedType(); 6823 // FIXME: Type of conditional expression must be complete in C mode. 6824 } 6825 6826 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6827 // The following || allows only one side to be void (a GCC-ism). 6828 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6829 return checkConditionalVoidType(*this, LHS, RHS); 6830 } 6831 6832 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6833 // the type of the other operand." 6834 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6835 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6836 6837 // All objective-c pointer type analysis is done here. 6838 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6839 QuestionLoc); 6840 if (LHS.isInvalid() || RHS.isInvalid()) 6841 return QualType(); 6842 if (!compositeType.isNull()) 6843 return compositeType; 6844 6845 6846 // Handle block pointer types. 6847 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6848 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6849 QuestionLoc); 6850 6851 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6852 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6853 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6854 QuestionLoc); 6855 6856 // GCC compatibility: soften pointer/integer mismatch. Note that 6857 // null pointers have been filtered out by this point. 6858 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6859 /*isIntFirstExpr=*/true)) 6860 return RHSTy; 6861 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6862 /*isIntFirstExpr=*/false)) 6863 return LHSTy; 6864 6865 // Emit a better diagnostic if one of the expressions is a null pointer 6866 // constant and the other is not a pointer type. In this case, the user most 6867 // likely forgot to take the address of the other expression. 6868 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6869 return QualType(); 6870 6871 // Otherwise, the operands are not compatible. 6872 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6873 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6874 << RHS.get()->getSourceRange(); 6875 return QualType(); 6876 } 6877 6878 /// FindCompositeObjCPointerType - Helper method to find composite type of 6879 /// two objective-c pointer types of the two input expressions. 6880 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6881 SourceLocation QuestionLoc) { 6882 QualType LHSTy = LHS.get()->getType(); 6883 QualType RHSTy = RHS.get()->getType(); 6884 6885 // Handle things like Class and struct objc_class*. Here we case the result 6886 // to the pseudo-builtin, because that will be implicitly cast back to the 6887 // redefinition type if an attempt is made to access its fields. 6888 if (LHSTy->isObjCClassType() && 6889 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6890 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6891 return LHSTy; 6892 } 6893 if (RHSTy->isObjCClassType() && 6894 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6895 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6896 return RHSTy; 6897 } 6898 // And the same for struct objc_object* / id 6899 if (LHSTy->isObjCIdType() && 6900 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6901 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6902 return LHSTy; 6903 } 6904 if (RHSTy->isObjCIdType() && 6905 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6906 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6907 return RHSTy; 6908 } 6909 // And the same for struct objc_selector* / SEL 6910 if (Context.isObjCSelType(LHSTy) && 6911 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6912 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6913 return LHSTy; 6914 } 6915 if (Context.isObjCSelType(RHSTy) && 6916 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6917 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6918 return RHSTy; 6919 } 6920 // Check constraints for Objective-C object pointers types. 6921 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6922 6923 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6924 // Two identical object pointer types are always compatible. 6925 return LHSTy; 6926 } 6927 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6928 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6929 QualType compositeType = LHSTy; 6930 6931 // If both operands are interfaces and either operand can be 6932 // assigned to the other, use that type as the composite 6933 // type. This allows 6934 // xxx ? (A*) a : (B*) b 6935 // where B is a subclass of A. 6936 // 6937 // Additionally, as for assignment, if either type is 'id' 6938 // allow silent coercion. Finally, if the types are 6939 // incompatible then make sure to use 'id' as the composite 6940 // type so the result is acceptable for sending messages to. 6941 6942 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6943 // It could return the composite type. 6944 if (!(compositeType = 6945 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6946 // Nothing more to do. 6947 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6948 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6949 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6950 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6951 } else if ((LHSTy->isObjCQualifiedIdType() || 6952 RHSTy->isObjCQualifiedIdType()) && 6953 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6954 // Need to handle "id<xx>" explicitly. 6955 // GCC allows qualified id and any Objective-C type to devolve to 6956 // id. Currently localizing to here until clear this should be 6957 // part of ObjCQualifiedIdTypesAreCompatible. 6958 compositeType = Context.getObjCIdType(); 6959 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6960 compositeType = Context.getObjCIdType(); 6961 } else { 6962 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6963 << LHSTy << RHSTy 6964 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6965 QualType incompatTy = Context.getObjCIdType(); 6966 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6967 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6968 return incompatTy; 6969 } 6970 // The object pointer types are compatible. 6971 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6972 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6973 return compositeType; 6974 } 6975 // Check Objective-C object pointer types and 'void *' 6976 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6977 if (getLangOpts().ObjCAutoRefCount) { 6978 // ARC forbids the implicit conversion of object pointers to 'void *', 6979 // so these types are not compatible. 6980 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6982 LHS = RHS = true; 6983 return QualType(); 6984 } 6985 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6986 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6987 QualType destPointee 6988 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6989 QualType destType = Context.getPointerType(destPointee); 6990 // Add qualifiers if necessary. 6991 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6992 // Promote to void*. 6993 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6994 return destType; 6995 } 6996 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6997 if (getLangOpts().ObjCAutoRefCount) { 6998 // ARC forbids the implicit conversion of object pointers to 'void *', 6999 // so these types are not compatible. 7000 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7001 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7002 LHS = RHS = true; 7003 return QualType(); 7004 } 7005 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7006 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7007 QualType destPointee 7008 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7009 QualType destType = Context.getPointerType(destPointee); 7010 // Add qualifiers if necessary. 7011 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7012 // Promote to void*. 7013 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7014 return destType; 7015 } 7016 return QualType(); 7017 } 7018 7019 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7020 /// ParenRange in parentheses. 7021 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7022 const PartialDiagnostic &Note, 7023 SourceRange ParenRange) { 7024 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7025 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7026 EndLoc.isValid()) { 7027 Self.Diag(Loc, Note) 7028 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7029 << FixItHint::CreateInsertion(EndLoc, ")"); 7030 } else { 7031 // We can't display the parentheses, so just show the bare note. 7032 Self.Diag(Loc, Note) << ParenRange; 7033 } 7034 } 7035 7036 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7037 return BinaryOperator::isAdditiveOp(Opc) || 7038 BinaryOperator::isMultiplicativeOp(Opc) || 7039 BinaryOperator::isShiftOp(Opc); 7040 } 7041 7042 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7043 /// expression, either using a built-in or overloaded operator, 7044 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7045 /// expression. 7046 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7047 Expr **RHSExprs) { 7048 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7049 E = E->IgnoreImpCasts(); 7050 E = E->IgnoreConversionOperator(); 7051 E = E->IgnoreImpCasts(); 7052 7053 // Built-in binary operator. 7054 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7055 if (IsArithmeticOp(OP->getOpcode())) { 7056 *Opcode = OP->getOpcode(); 7057 *RHSExprs = OP->getRHS(); 7058 return true; 7059 } 7060 } 7061 7062 // Overloaded operator. 7063 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7064 if (Call->getNumArgs() != 2) 7065 return false; 7066 7067 // Make sure this is really a binary operator that is safe to pass into 7068 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7069 OverloadedOperatorKind OO = Call->getOperator(); 7070 if (OO < OO_Plus || OO > OO_Arrow || 7071 OO == OO_PlusPlus || OO == OO_MinusMinus) 7072 return false; 7073 7074 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7075 if (IsArithmeticOp(OpKind)) { 7076 *Opcode = OpKind; 7077 *RHSExprs = Call->getArg(1); 7078 return true; 7079 } 7080 } 7081 7082 return false; 7083 } 7084 7085 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7086 /// or is a logical expression such as (x==y) which has int type, but is 7087 /// commonly interpreted as boolean. 7088 static bool ExprLooksBoolean(Expr *E) { 7089 E = E->IgnoreParenImpCasts(); 7090 7091 if (E->getType()->isBooleanType()) 7092 return true; 7093 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7094 return OP->isComparisonOp() || OP->isLogicalOp(); 7095 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7096 return OP->getOpcode() == UO_LNot; 7097 if (E->getType()->isPointerType()) 7098 return true; 7099 7100 return false; 7101 } 7102 7103 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7104 /// and binary operator are mixed in a way that suggests the programmer assumed 7105 /// the conditional operator has higher precedence, for example: 7106 /// "int x = a + someBinaryCondition ? 1 : 2". 7107 static void DiagnoseConditionalPrecedence(Sema &Self, 7108 SourceLocation OpLoc, 7109 Expr *Condition, 7110 Expr *LHSExpr, 7111 Expr *RHSExpr) { 7112 BinaryOperatorKind CondOpcode; 7113 Expr *CondRHS; 7114 7115 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7116 return; 7117 if (!ExprLooksBoolean(CondRHS)) 7118 return; 7119 7120 // The condition is an arithmetic binary expression, with a right- 7121 // hand side that looks boolean, so warn. 7122 7123 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7124 << Condition->getSourceRange() 7125 << BinaryOperator::getOpcodeStr(CondOpcode); 7126 7127 SuggestParentheses(Self, OpLoc, 7128 Self.PDiag(diag::note_precedence_silence) 7129 << BinaryOperator::getOpcodeStr(CondOpcode), 7130 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7131 7132 SuggestParentheses(Self, OpLoc, 7133 Self.PDiag(diag::note_precedence_conditional_first), 7134 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7135 } 7136 7137 /// Compute the nullability of a conditional expression. 7138 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7139 QualType LHSTy, QualType RHSTy, 7140 ASTContext &Ctx) { 7141 if (!ResTy->isAnyPointerType()) 7142 return ResTy; 7143 7144 auto GetNullability = [&Ctx](QualType Ty) { 7145 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7146 if (Kind) 7147 return *Kind; 7148 return NullabilityKind::Unspecified; 7149 }; 7150 7151 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7152 NullabilityKind MergedKind; 7153 7154 // Compute nullability of a binary conditional expression. 7155 if (IsBin) { 7156 if (LHSKind == NullabilityKind::NonNull) 7157 MergedKind = NullabilityKind::NonNull; 7158 else 7159 MergedKind = RHSKind; 7160 // Compute nullability of a normal conditional expression. 7161 } else { 7162 if (LHSKind == NullabilityKind::Nullable || 7163 RHSKind == NullabilityKind::Nullable) 7164 MergedKind = NullabilityKind::Nullable; 7165 else if (LHSKind == NullabilityKind::NonNull) 7166 MergedKind = RHSKind; 7167 else if (RHSKind == NullabilityKind::NonNull) 7168 MergedKind = LHSKind; 7169 else 7170 MergedKind = NullabilityKind::Unspecified; 7171 } 7172 7173 // Return if ResTy already has the correct nullability. 7174 if (GetNullability(ResTy) == MergedKind) 7175 return ResTy; 7176 7177 // Strip all nullability from ResTy. 7178 while (ResTy->getNullability(Ctx)) 7179 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7180 7181 // Create a new AttributedType with the new nullability kind. 7182 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7183 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7184 } 7185 7186 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7187 /// in the case of a the GNU conditional expr extension. 7188 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7189 SourceLocation ColonLoc, 7190 Expr *CondExpr, Expr *LHSExpr, 7191 Expr *RHSExpr) { 7192 if (!getLangOpts().CPlusPlus) { 7193 // C cannot handle TypoExpr nodes in the condition because it 7194 // doesn't handle dependent types properly, so make sure any TypoExprs have 7195 // been dealt with before checking the operands. 7196 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7197 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7198 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7199 7200 if (!CondResult.isUsable()) 7201 return ExprError(); 7202 7203 if (LHSExpr) { 7204 if (!LHSResult.isUsable()) 7205 return ExprError(); 7206 } 7207 7208 if (!RHSResult.isUsable()) 7209 return ExprError(); 7210 7211 CondExpr = CondResult.get(); 7212 LHSExpr = LHSResult.get(); 7213 RHSExpr = RHSResult.get(); 7214 } 7215 7216 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7217 // was the condition. 7218 OpaqueValueExpr *opaqueValue = nullptr; 7219 Expr *commonExpr = nullptr; 7220 if (!LHSExpr) { 7221 commonExpr = CondExpr; 7222 // Lower out placeholder types first. This is important so that we don't 7223 // try to capture a placeholder. This happens in few cases in C++; such 7224 // as Objective-C++'s dictionary subscripting syntax. 7225 if (commonExpr->hasPlaceholderType()) { 7226 ExprResult result = CheckPlaceholderExpr(commonExpr); 7227 if (!result.isUsable()) return ExprError(); 7228 commonExpr = result.get(); 7229 } 7230 // We usually want to apply unary conversions *before* saving, except 7231 // in the special case of a C++ l-value conditional. 7232 if (!(getLangOpts().CPlusPlus 7233 && !commonExpr->isTypeDependent() 7234 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7235 && commonExpr->isGLValue() 7236 && commonExpr->isOrdinaryOrBitFieldObject() 7237 && RHSExpr->isOrdinaryOrBitFieldObject() 7238 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7239 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7240 if (commonRes.isInvalid()) 7241 return ExprError(); 7242 commonExpr = commonRes.get(); 7243 } 7244 7245 // If the common expression is a class or array prvalue, materialize it 7246 // so that we can safely refer to it multiple times. 7247 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7248 commonExpr->getType()->isArrayType())) { 7249 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7250 if (MatExpr.isInvalid()) 7251 return ExprError(); 7252 commonExpr = MatExpr.get(); 7253 } 7254 7255 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7256 commonExpr->getType(), 7257 commonExpr->getValueKind(), 7258 commonExpr->getObjectKind(), 7259 commonExpr); 7260 LHSExpr = CondExpr = opaqueValue; 7261 } 7262 7263 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7264 ExprValueKind VK = VK_RValue; 7265 ExprObjectKind OK = OK_Ordinary; 7266 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7267 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7268 VK, OK, QuestionLoc); 7269 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7270 RHS.isInvalid()) 7271 return ExprError(); 7272 7273 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7274 RHS.get()); 7275 7276 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7277 7278 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7279 Context); 7280 7281 if (!commonExpr) 7282 return new (Context) 7283 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7284 RHS.get(), result, VK, OK); 7285 7286 return new (Context) BinaryConditionalOperator( 7287 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7288 ColonLoc, result, VK, OK); 7289 } 7290 7291 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7292 // being closely modeled after the C99 spec:-). The odd characteristic of this 7293 // routine is it effectively iqnores the qualifiers on the top level pointee. 7294 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7295 // FIXME: add a couple examples in this comment. 7296 static Sema::AssignConvertType 7297 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7298 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7299 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7300 7301 // get the "pointed to" type (ignoring qualifiers at the top level) 7302 const Type *lhptee, *rhptee; 7303 Qualifiers lhq, rhq; 7304 std::tie(lhptee, lhq) = 7305 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7306 std::tie(rhptee, rhq) = 7307 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7308 7309 Sema::AssignConvertType ConvTy = Sema::Compatible; 7310 7311 // C99 6.5.16.1p1: This following citation is common to constraints 7312 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7313 // qualifiers of the type *pointed to* by the right; 7314 7315 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7316 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7317 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7318 // Ignore lifetime for further calculation. 7319 lhq.removeObjCLifetime(); 7320 rhq.removeObjCLifetime(); 7321 } 7322 7323 if (!lhq.compatiblyIncludes(rhq)) { 7324 // Treat address-space mismatches as fatal. TODO: address subspaces 7325 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7326 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7327 7328 // It's okay to add or remove GC or lifetime qualifiers when converting to 7329 // and from void*. 7330 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7331 .compatiblyIncludes( 7332 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7333 && (lhptee->isVoidType() || rhptee->isVoidType())) 7334 ; // keep old 7335 7336 // Treat lifetime mismatches as fatal. 7337 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7338 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7339 7340 // For GCC/MS compatibility, other qualifier mismatches are treated 7341 // as still compatible in C. 7342 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7343 } 7344 7345 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7346 // incomplete type and the other is a pointer to a qualified or unqualified 7347 // version of void... 7348 if (lhptee->isVoidType()) { 7349 if (rhptee->isIncompleteOrObjectType()) 7350 return ConvTy; 7351 7352 // As an extension, we allow cast to/from void* to function pointer. 7353 assert(rhptee->isFunctionType()); 7354 return Sema::FunctionVoidPointer; 7355 } 7356 7357 if (rhptee->isVoidType()) { 7358 if (lhptee->isIncompleteOrObjectType()) 7359 return ConvTy; 7360 7361 // As an extension, we allow cast to/from void* to function pointer. 7362 assert(lhptee->isFunctionType()); 7363 return Sema::FunctionVoidPointer; 7364 } 7365 7366 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7367 // unqualified versions of compatible types, ... 7368 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7369 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7370 // Check if the pointee types are compatible ignoring the sign. 7371 // We explicitly check for char so that we catch "char" vs 7372 // "unsigned char" on systems where "char" is unsigned. 7373 if (lhptee->isCharType()) 7374 ltrans = S.Context.UnsignedCharTy; 7375 else if (lhptee->hasSignedIntegerRepresentation()) 7376 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7377 7378 if (rhptee->isCharType()) 7379 rtrans = S.Context.UnsignedCharTy; 7380 else if (rhptee->hasSignedIntegerRepresentation()) 7381 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7382 7383 if (ltrans == rtrans) { 7384 // Types are compatible ignoring the sign. Qualifier incompatibility 7385 // takes priority over sign incompatibility because the sign 7386 // warning can be disabled. 7387 if (ConvTy != Sema::Compatible) 7388 return ConvTy; 7389 7390 return Sema::IncompatiblePointerSign; 7391 } 7392 7393 // If we are a multi-level pointer, it's possible that our issue is simply 7394 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7395 // the eventual target type is the same and the pointers have the same 7396 // level of indirection, this must be the issue. 7397 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7398 do { 7399 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7400 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7401 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7402 7403 if (lhptee == rhptee) 7404 return Sema::IncompatibleNestedPointerQualifiers; 7405 } 7406 7407 // General pointer incompatibility takes priority over qualifiers. 7408 return Sema::IncompatiblePointer; 7409 } 7410 if (!S.getLangOpts().CPlusPlus && 7411 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7412 return Sema::IncompatiblePointer; 7413 return ConvTy; 7414 } 7415 7416 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7417 /// block pointer types are compatible or whether a block and normal pointer 7418 /// are compatible. It is more restrict than comparing two function pointer 7419 // types. 7420 static Sema::AssignConvertType 7421 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7422 QualType RHSType) { 7423 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7424 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7425 7426 QualType lhptee, rhptee; 7427 7428 // get the "pointed to" type (ignoring qualifiers at the top level) 7429 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7430 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7431 7432 // In C++, the types have to match exactly. 7433 if (S.getLangOpts().CPlusPlus) 7434 return Sema::IncompatibleBlockPointer; 7435 7436 Sema::AssignConvertType ConvTy = Sema::Compatible; 7437 7438 // For blocks we enforce that qualifiers are identical. 7439 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7440 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7441 if (S.getLangOpts().OpenCL) { 7442 LQuals.removeAddressSpace(); 7443 RQuals.removeAddressSpace(); 7444 } 7445 if (LQuals != RQuals) 7446 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7447 7448 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7449 // assignment. 7450 // The current behavior is similar to C++ lambdas. A block might be 7451 // assigned to a variable iff its return type and parameters are compatible 7452 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7453 // an assignment. Presumably it should behave in way that a function pointer 7454 // assignment does in C, so for each parameter and return type: 7455 // * CVR and address space of LHS should be a superset of CVR and address 7456 // space of RHS. 7457 // * unqualified types should be compatible. 7458 if (S.getLangOpts().OpenCL) { 7459 if (!S.Context.typesAreBlockPointerCompatible( 7460 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7461 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7462 return Sema::IncompatibleBlockPointer; 7463 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7464 return Sema::IncompatibleBlockPointer; 7465 7466 return ConvTy; 7467 } 7468 7469 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7470 /// for assignment compatibility. 7471 static Sema::AssignConvertType 7472 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7473 QualType RHSType) { 7474 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7475 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7476 7477 if (LHSType->isObjCBuiltinType()) { 7478 // Class is not compatible with ObjC object pointers. 7479 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7480 !RHSType->isObjCQualifiedClassType()) 7481 return Sema::IncompatiblePointer; 7482 return Sema::Compatible; 7483 } 7484 if (RHSType->isObjCBuiltinType()) { 7485 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7486 !LHSType->isObjCQualifiedClassType()) 7487 return Sema::IncompatiblePointer; 7488 return Sema::Compatible; 7489 } 7490 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7491 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7492 7493 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7494 // make an exception for id<P> 7495 !LHSType->isObjCQualifiedIdType()) 7496 return Sema::CompatiblePointerDiscardsQualifiers; 7497 7498 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7499 return Sema::Compatible; 7500 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7501 return Sema::IncompatibleObjCQualifiedId; 7502 return Sema::IncompatiblePointer; 7503 } 7504 7505 Sema::AssignConvertType 7506 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7507 QualType LHSType, QualType RHSType) { 7508 // Fake up an opaque expression. We don't actually care about what 7509 // cast operations are required, so if CheckAssignmentConstraints 7510 // adds casts to this they'll be wasted, but fortunately that doesn't 7511 // usually happen on valid code. 7512 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7513 ExprResult RHSPtr = &RHSExpr; 7514 CastKind K; 7515 7516 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7517 } 7518 7519 /// This helper function returns true if QT is a vector type that has element 7520 /// type ElementType. 7521 static bool isVector(QualType QT, QualType ElementType) { 7522 if (const VectorType *VT = QT->getAs<VectorType>()) 7523 return VT->getElementType() == ElementType; 7524 return false; 7525 } 7526 7527 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7528 /// has code to accommodate several GCC extensions when type checking 7529 /// pointers. Here are some objectionable examples that GCC considers warnings: 7530 /// 7531 /// int a, *pint; 7532 /// short *pshort; 7533 /// struct foo *pfoo; 7534 /// 7535 /// pint = pshort; // warning: assignment from incompatible pointer type 7536 /// a = pint; // warning: assignment makes integer from pointer without a cast 7537 /// pint = a; // warning: assignment makes pointer from integer without a cast 7538 /// pint = pfoo; // warning: assignment from incompatible pointer type 7539 /// 7540 /// As a result, the code for dealing with pointers is more complex than the 7541 /// C99 spec dictates. 7542 /// 7543 /// Sets 'Kind' for any result kind except Incompatible. 7544 Sema::AssignConvertType 7545 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7546 CastKind &Kind, bool ConvertRHS) { 7547 QualType RHSType = RHS.get()->getType(); 7548 QualType OrigLHSType = LHSType; 7549 7550 // Get canonical types. We're not formatting these types, just comparing 7551 // them. 7552 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7553 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7554 7555 // Common case: no conversion required. 7556 if (LHSType == RHSType) { 7557 Kind = CK_NoOp; 7558 return Compatible; 7559 } 7560 7561 // If we have an atomic type, try a non-atomic assignment, then just add an 7562 // atomic qualification step. 7563 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7564 Sema::AssignConvertType result = 7565 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7566 if (result != Compatible) 7567 return result; 7568 if (Kind != CK_NoOp && ConvertRHS) 7569 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7570 Kind = CK_NonAtomicToAtomic; 7571 return Compatible; 7572 } 7573 7574 // If the left-hand side is a reference type, then we are in a 7575 // (rare!) case where we've allowed the use of references in C, 7576 // e.g., as a parameter type in a built-in function. In this case, 7577 // just make sure that the type referenced is compatible with the 7578 // right-hand side type. The caller is responsible for adjusting 7579 // LHSType so that the resulting expression does not have reference 7580 // type. 7581 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7582 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7583 Kind = CK_LValueBitCast; 7584 return Compatible; 7585 } 7586 return Incompatible; 7587 } 7588 7589 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7590 // to the same ExtVector type. 7591 if (LHSType->isExtVectorType()) { 7592 if (RHSType->isExtVectorType()) 7593 return Incompatible; 7594 if (RHSType->isArithmeticType()) { 7595 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7596 if (ConvertRHS) 7597 RHS = prepareVectorSplat(LHSType, RHS.get()); 7598 Kind = CK_VectorSplat; 7599 return Compatible; 7600 } 7601 } 7602 7603 // Conversions to or from vector type. 7604 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7605 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7606 // Allow assignments of an AltiVec vector type to an equivalent GCC 7607 // vector type and vice versa 7608 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7609 Kind = CK_BitCast; 7610 return Compatible; 7611 } 7612 7613 // If we are allowing lax vector conversions, and LHS and RHS are both 7614 // vectors, the total size only needs to be the same. This is a bitcast; 7615 // no bits are changed but the result type is different. 7616 if (isLaxVectorConversion(RHSType, LHSType)) { 7617 Kind = CK_BitCast; 7618 return IncompatibleVectors; 7619 } 7620 } 7621 7622 // When the RHS comes from another lax conversion (e.g. binops between 7623 // scalars and vectors) the result is canonicalized as a vector. When the 7624 // LHS is also a vector, the lax is allowed by the condition above. Handle 7625 // the case where LHS is a scalar. 7626 if (LHSType->isScalarType()) { 7627 const VectorType *VecType = RHSType->getAs<VectorType>(); 7628 if (VecType && VecType->getNumElements() == 1 && 7629 isLaxVectorConversion(RHSType, LHSType)) { 7630 ExprResult *VecExpr = &RHS; 7631 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7632 Kind = CK_BitCast; 7633 return Compatible; 7634 } 7635 } 7636 7637 return Incompatible; 7638 } 7639 7640 // Diagnose attempts to convert between __float128 and long double where 7641 // such conversions currently can't be handled. 7642 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7643 return Incompatible; 7644 7645 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7646 // discards the imaginary part. 7647 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7648 !LHSType->getAs<ComplexType>()) 7649 return Incompatible; 7650 7651 // Arithmetic conversions. 7652 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7653 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7654 if (ConvertRHS) 7655 Kind = PrepareScalarCast(RHS, LHSType); 7656 return Compatible; 7657 } 7658 7659 // Conversions to normal pointers. 7660 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7661 // U* -> T* 7662 if (isa<PointerType>(RHSType)) { 7663 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7664 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7665 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7666 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7667 } 7668 7669 // int -> T* 7670 if (RHSType->isIntegerType()) { 7671 Kind = CK_IntegralToPointer; // FIXME: null? 7672 return IntToPointer; 7673 } 7674 7675 // C pointers are not compatible with ObjC object pointers, 7676 // with two exceptions: 7677 if (isa<ObjCObjectPointerType>(RHSType)) { 7678 // - conversions to void* 7679 if (LHSPointer->getPointeeType()->isVoidType()) { 7680 Kind = CK_BitCast; 7681 return Compatible; 7682 } 7683 7684 // - conversions from 'Class' to the redefinition type 7685 if (RHSType->isObjCClassType() && 7686 Context.hasSameType(LHSType, 7687 Context.getObjCClassRedefinitionType())) { 7688 Kind = CK_BitCast; 7689 return Compatible; 7690 } 7691 7692 Kind = CK_BitCast; 7693 return IncompatiblePointer; 7694 } 7695 7696 // U^ -> void* 7697 if (RHSType->getAs<BlockPointerType>()) { 7698 if (LHSPointer->getPointeeType()->isVoidType()) { 7699 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7700 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7701 ->getPointeeType() 7702 .getAddressSpace(); 7703 Kind = 7704 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7705 return Compatible; 7706 } 7707 } 7708 7709 return Incompatible; 7710 } 7711 7712 // Conversions to block pointers. 7713 if (isa<BlockPointerType>(LHSType)) { 7714 // U^ -> T^ 7715 if (RHSType->isBlockPointerType()) { 7716 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7717 ->getPointeeType() 7718 .getAddressSpace(); 7719 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7720 ->getPointeeType() 7721 .getAddressSpace(); 7722 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7723 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7724 } 7725 7726 // int or null -> T^ 7727 if (RHSType->isIntegerType()) { 7728 Kind = CK_IntegralToPointer; // FIXME: null 7729 return IntToBlockPointer; 7730 } 7731 7732 // id -> T^ 7733 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7734 Kind = CK_AnyPointerToBlockPointerCast; 7735 return Compatible; 7736 } 7737 7738 // void* -> T^ 7739 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7740 if (RHSPT->getPointeeType()->isVoidType()) { 7741 Kind = CK_AnyPointerToBlockPointerCast; 7742 return Compatible; 7743 } 7744 7745 return Incompatible; 7746 } 7747 7748 // Conversions to Objective-C pointers. 7749 if (isa<ObjCObjectPointerType>(LHSType)) { 7750 // A* -> B* 7751 if (RHSType->isObjCObjectPointerType()) { 7752 Kind = CK_BitCast; 7753 Sema::AssignConvertType result = 7754 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7755 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7756 result == Compatible && 7757 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7758 result = IncompatibleObjCWeakRef; 7759 return result; 7760 } 7761 7762 // int or null -> A* 7763 if (RHSType->isIntegerType()) { 7764 Kind = CK_IntegralToPointer; // FIXME: null 7765 return IntToPointer; 7766 } 7767 7768 // In general, C pointers are not compatible with ObjC object pointers, 7769 // with two exceptions: 7770 if (isa<PointerType>(RHSType)) { 7771 Kind = CK_CPointerToObjCPointerCast; 7772 7773 // - conversions from 'void*' 7774 if (RHSType->isVoidPointerType()) { 7775 return Compatible; 7776 } 7777 7778 // - conversions to 'Class' from its redefinition type 7779 if (LHSType->isObjCClassType() && 7780 Context.hasSameType(RHSType, 7781 Context.getObjCClassRedefinitionType())) { 7782 return Compatible; 7783 } 7784 7785 return IncompatiblePointer; 7786 } 7787 7788 // Only under strict condition T^ is compatible with an Objective-C pointer. 7789 if (RHSType->isBlockPointerType() && 7790 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7791 if (ConvertRHS) 7792 maybeExtendBlockObject(RHS); 7793 Kind = CK_BlockPointerToObjCPointerCast; 7794 return Compatible; 7795 } 7796 7797 return Incompatible; 7798 } 7799 7800 // Conversions from pointers that are not covered by the above. 7801 if (isa<PointerType>(RHSType)) { 7802 // T* -> _Bool 7803 if (LHSType == Context.BoolTy) { 7804 Kind = CK_PointerToBoolean; 7805 return Compatible; 7806 } 7807 7808 // T* -> int 7809 if (LHSType->isIntegerType()) { 7810 Kind = CK_PointerToIntegral; 7811 return PointerToInt; 7812 } 7813 7814 return Incompatible; 7815 } 7816 7817 // Conversions from Objective-C pointers that are not covered by the above. 7818 if (isa<ObjCObjectPointerType>(RHSType)) { 7819 // T* -> _Bool 7820 if (LHSType == Context.BoolTy) { 7821 Kind = CK_PointerToBoolean; 7822 return Compatible; 7823 } 7824 7825 // T* -> int 7826 if (LHSType->isIntegerType()) { 7827 Kind = CK_PointerToIntegral; 7828 return PointerToInt; 7829 } 7830 7831 return Incompatible; 7832 } 7833 7834 // struct A -> struct B 7835 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7836 if (Context.typesAreCompatible(LHSType, RHSType)) { 7837 Kind = CK_NoOp; 7838 return Compatible; 7839 } 7840 } 7841 7842 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7843 Kind = CK_IntToOCLSampler; 7844 return Compatible; 7845 } 7846 7847 return Incompatible; 7848 } 7849 7850 /// \brief Constructs a transparent union from an expression that is 7851 /// used to initialize the transparent union. 7852 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7853 ExprResult &EResult, QualType UnionType, 7854 FieldDecl *Field) { 7855 // Build an initializer list that designates the appropriate member 7856 // of the transparent union. 7857 Expr *E = EResult.get(); 7858 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7859 E, SourceLocation()); 7860 Initializer->setType(UnionType); 7861 Initializer->setInitializedFieldInUnion(Field); 7862 7863 // Build a compound literal constructing a value of the transparent 7864 // union type from this initializer list. 7865 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7866 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7867 VK_RValue, Initializer, false); 7868 } 7869 7870 Sema::AssignConvertType 7871 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7872 ExprResult &RHS) { 7873 QualType RHSType = RHS.get()->getType(); 7874 7875 // If the ArgType is a Union type, we want to handle a potential 7876 // transparent_union GCC extension. 7877 const RecordType *UT = ArgType->getAsUnionType(); 7878 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7879 return Incompatible; 7880 7881 // The field to initialize within the transparent union. 7882 RecordDecl *UD = UT->getDecl(); 7883 FieldDecl *InitField = nullptr; 7884 // It's compatible if the expression matches any of the fields. 7885 for (auto *it : UD->fields()) { 7886 if (it->getType()->isPointerType()) { 7887 // If the transparent union contains a pointer type, we allow: 7888 // 1) void pointer 7889 // 2) null pointer constant 7890 if (RHSType->isPointerType()) 7891 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7892 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7893 InitField = it; 7894 break; 7895 } 7896 7897 if (RHS.get()->isNullPointerConstant(Context, 7898 Expr::NPC_ValueDependentIsNull)) { 7899 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7900 CK_NullToPointer); 7901 InitField = it; 7902 break; 7903 } 7904 } 7905 7906 CastKind Kind; 7907 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7908 == Compatible) { 7909 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7910 InitField = it; 7911 break; 7912 } 7913 } 7914 7915 if (!InitField) 7916 return Incompatible; 7917 7918 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7919 return Compatible; 7920 } 7921 7922 Sema::AssignConvertType 7923 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7924 bool Diagnose, 7925 bool DiagnoseCFAudited, 7926 bool ConvertRHS) { 7927 // We need to be able to tell the caller whether we diagnosed a problem, if 7928 // they ask us to issue diagnostics. 7929 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7930 7931 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7932 // we can't avoid *all* modifications at the moment, so we need some somewhere 7933 // to put the updated value. 7934 ExprResult LocalRHS = CallerRHS; 7935 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7936 7937 if (getLangOpts().CPlusPlus) { 7938 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7939 // C++ 5.17p3: If the left operand is not of class type, the 7940 // expression is implicitly converted (C++ 4) to the 7941 // cv-unqualified type of the left operand. 7942 QualType RHSType = RHS.get()->getType(); 7943 if (Diagnose) { 7944 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7945 AA_Assigning); 7946 } else { 7947 ImplicitConversionSequence ICS = 7948 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7949 /*SuppressUserConversions=*/false, 7950 /*AllowExplicit=*/false, 7951 /*InOverloadResolution=*/false, 7952 /*CStyle=*/false, 7953 /*AllowObjCWritebackConversion=*/false); 7954 if (ICS.isFailure()) 7955 return Incompatible; 7956 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7957 ICS, AA_Assigning); 7958 } 7959 if (RHS.isInvalid()) 7960 return Incompatible; 7961 Sema::AssignConvertType result = Compatible; 7962 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7963 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7964 result = IncompatibleObjCWeakRef; 7965 return result; 7966 } 7967 7968 // FIXME: Currently, we fall through and treat C++ classes like C 7969 // structures. 7970 // FIXME: We also fall through for atomics; not sure what should 7971 // happen there, though. 7972 } else if (RHS.get()->getType() == Context.OverloadTy) { 7973 // As a set of extensions to C, we support overloading on functions. These 7974 // functions need to be resolved here. 7975 DeclAccessPair DAP; 7976 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7977 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7978 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7979 else 7980 return Incompatible; 7981 } 7982 7983 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7984 // a null pointer constant. 7985 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7986 LHSType->isBlockPointerType()) && 7987 RHS.get()->isNullPointerConstant(Context, 7988 Expr::NPC_ValueDependentIsNull)) { 7989 if (Diagnose || ConvertRHS) { 7990 CastKind Kind; 7991 CXXCastPath Path; 7992 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7993 /*IgnoreBaseAccess=*/false, Diagnose); 7994 if (ConvertRHS) 7995 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7996 } 7997 return Compatible; 7998 } 7999 8000 // This check seems unnatural, however it is necessary to ensure the proper 8001 // conversion of functions/arrays. If the conversion were done for all 8002 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8003 // expressions that suppress this implicit conversion (&, sizeof). 8004 // 8005 // Suppress this for references: C++ 8.5.3p5. 8006 if (!LHSType->isReferenceType()) { 8007 // FIXME: We potentially allocate here even if ConvertRHS is false. 8008 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8009 if (RHS.isInvalid()) 8010 return Incompatible; 8011 } 8012 8013 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8014 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8015 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8016 if (PDecl && !PDecl->hasDefinition()) { 8017 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 8018 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8019 } 8020 } 8021 8022 CastKind Kind; 8023 Sema::AssignConvertType result = 8024 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8025 8026 // C99 6.5.16.1p2: The value of the right operand is converted to the 8027 // type of the assignment expression. 8028 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8029 // so that we can use references in built-in functions even in C. 8030 // The getNonReferenceType() call makes sure that the resulting expression 8031 // does not have reference type. 8032 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8033 QualType Ty = LHSType.getNonLValueExprType(Context); 8034 Expr *E = RHS.get(); 8035 8036 // Check for various Objective-C errors. If we are not reporting 8037 // diagnostics and just checking for errors, e.g., during overload 8038 // resolution, return Incompatible to indicate the failure. 8039 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8040 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8041 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8042 if (!Diagnose) 8043 return Incompatible; 8044 } 8045 if (getLangOpts().ObjC1 && 8046 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8047 E->getType(), E, Diagnose) || 8048 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8049 if (!Diagnose) 8050 return Incompatible; 8051 // Replace the expression with a corrected version and continue so we 8052 // can find further errors. 8053 RHS = E; 8054 return Compatible; 8055 } 8056 8057 if (ConvertRHS) 8058 RHS = ImpCastExprToType(E, Ty, Kind); 8059 } 8060 return result; 8061 } 8062 8063 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8064 ExprResult &RHS) { 8065 Diag(Loc, diag::err_typecheck_invalid_operands) 8066 << LHS.get()->getType() << RHS.get()->getType() 8067 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8068 return QualType(); 8069 } 8070 8071 // Diagnose cases where a scalar was implicitly converted to a vector and 8072 // diagnose the underlying types. Otherwise, diagnose the error 8073 // as invalid vector logical operands for non-C++ cases. 8074 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8075 ExprResult &RHS) { 8076 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8077 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8078 8079 bool LHSNatVec = LHSType->isVectorType(); 8080 bool RHSNatVec = RHSType->isVectorType(); 8081 8082 if (!(LHSNatVec && RHSNatVec)) { 8083 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8084 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8085 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8086 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8087 << Vector->getSourceRange(); 8088 return QualType(); 8089 } 8090 8091 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8092 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8093 << RHS.get()->getSourceRange(); 8094 8095 return QualType(); 8096 } 8097 8098 /// Try to convert a value of non-vector type to a vector type by converting 8099 /// the type to the element type of the vector and then performing a splat. 8100 /// If the language is OpenCL, we only use conversions that promote scalar 8101 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8102 /// for float->int. 8103 /// 8104 /// OpenCL V2.0 6.2.6.p2: 8105 /// An error shall occur if any scalar operand type has greater rank 8106 /// than the type of the vector element. 8107 /// 8108 /// \param scalar - if non-null, actually perform the conversions 8109 /// \return true if the operation fails (but without diagnosing the failure) 8110 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8111 QualType scalarTy, 8112 QualType vectorEltTy, 8113 QualType vectorTy, 8114 unsigned &DiagID) { 8115 // The conversion to apply to the scalar before splatting it, 8116 // if necessary. 8117 CastKind scalarCast = CK_NoOp; 8118 8119 if (vectorEltTy->isIntegralType(S.Context)) { 8120 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8121 (scalarTy->isIntegerType() && 8122 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8123 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8124 return true; 8125 } 8126 if (!scalarTy->isIntegralType(S.Context)) 8127 return true; 8128 scalarCast = CK_IntegralCast; 8129 } else if (vectorEltTy->isRealFloatingType()) { 8130 if (scalarTy->isRealFloatingType()) { 8131 if (S.getLangOpts().OpenCL && 8132 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8133 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8134 return true; 8135 } 8136 scalarCast = CK_FloatingCast; 8137 } 8138 else if (scalarTy->isIntegralType(S.Context)) 8139 scalarCast = CK_IntegralToFloating; 8140 else 8141 return true; 8142 } else { 8143 return true; 8144 } 8145 8146 // Adjust scalar if desired. 8147 if (scalar) { 8148 if (scalarCast != CK_NoOp) 8149 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8150 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8151 } 8152 return false; 8153 } 8154 8155 /// Convert vector E to a vector with the same number of elements but different 8156 /// element type. 8157 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8158 const auto *VecTy = E->getType()->getAs<VectorType>(); 8159 assert(VecTy && "Expression E must be a vector"); 8160 QualType NewVecTy = S.Context.getVectorType(ElementType, 8161 VecTy->getNumElements(), 8162 VecTy->getVectorKind()); 8163 8164 // Look through the implicit cast. Return the subexpression if its type is 8165 // NewVecTy. 8166 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8167 if (ICE->getSubExpr()->getType() == NewVecTy) 8168 return ICE->getSubExpr(); 8169 8170 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8171 return S.ImpCastExprToType(E, NewVecTy, Cast); 8172 } 8173 8174 /// Test if a (constant) integer Int can be casted to another integer type 8175 /// IntTy without losing precision. 8176 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8177 QualType OtherIntTy) { 8178 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8179 8180 // Reject cases where the value of the Int is unknown as that would 8181 // possibly cause truncation, but accept cases where the scalar can be 8182 // demoted without loss of precision. 8183 llvm::APSInt Result; 8184 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8185 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8186 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8187 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8188 8189 if (CstInt) { 8190 // If the scalar is constant and is of a higher order and has more active 8191 // bits that the vector element type, reject it. 8192 unsigned NumBits = IntSigned 8193 ? (Result.isNegative() ? Result.getMinSignedBits() 8194 : Result.getActiveBits()) 8195 : Result.getActiveBits(); 8196 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8197 return true; 8198 8199 // If the signedness of the scalar type and the vector element type 8200 // differs and the number of bits is greater than that of the vector 8201 // element reject it. 8202 return (IntSigned != OtherIntSigned && 8203 NumBits > S.Context.getIntWidth(OtherIntTy)); 8204 } 8205 8206 // Reject cases where the value of the scalar is not constant and it's 8207 // order is greater than that of the vector element type. 8208 return (Order < 0); 8209 } 8210 8211 /// Test if a (constant) integer Int can be casted to floating point type 8212 /// FloatTy without losing precision. 8213 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8214 QualType FloatTy) { 8215 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8216 8217 // Determine if the integer constant can be expressed as a floating point 8218 // number of the appropiate type. 8219 llvm::APSInt Result; 8220 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8221 uint64_t Bits = 0; 8222 if (CstInt) { 8223 // Reject constants that would be truncated if they were converted to 8224 // the floating point type. Test by simple to/from conversion. 8225 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8226 // could be avoided if there was a convertFromAPInt method 8227 // which could signal back if implicit truncation occurred. 8228 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8229 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8230 llvm::APFloat::rmTowardZero); 8231 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8232 !IntTy->hasSignedIntegerRepresentation()); 8233 bool Ignored = false; 8234 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8235 &Ignored); 8236 if (Result != ConvertBack) 8237 return true; 8238 } else { 8239 // Reject types that cannot be fully encoded into the mantissa of 8240 // the float. 8241 Bits = S.Context.getTypeSize(IntTy); 8242 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8243 S.Context.getFloatTypeSemantics(FloatTy)); 8244 if (Bits > FloatPrec) 8245 return true; 8246 } 8247 8248 return false; 8249 } 8250 8251 /// Attempt to convert and splat Scalar into a vector whose types matches 8252 /// Vector following GCC conversion rules. The rule is that implicit 8253 /// conversion can occur when Scalar can be casted to match Vector's element 8254 /// type without causing truncation of Scalar. 8255 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8256 ExprResult *Vector) { 8257 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8258 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8259 const VectorType *VT = VectorTy->getAs<VectorType>(); 8260 8261 assert(!isa<ExtVectorType>(VT) && 8262 "ExtVectorTypes should not be handled here!"); 8263 8264 QualType VectorEltTy = VT->getElementType(); 8265 8266 // Reject cases where the vector element type or the scalar element type are 8267 // not integral or floating point types. 8268 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8269 return true; 8270 8271 // The conversion to apply to the scalar before splatting it, 8272 // if necessary. 8273 CastKind ScalarCast = CK_NoOp; 8274 8275 // Accept cases where the vector elements are integers and the scalar is 8276 // an integer. 8277 // FIXME: Notionally if the scalar was a floating point value with a precise 8278 // integral representation, we could cast it to an appropriate integer 8279 // type and then perform the rest of the checks here. GCC will perform 8280 // this conversion in some cases as determined by the input language. 8281 // We should accept it on a language independent basis. 8282 if (VectorEltTy->isIntegralType(S.Context) && 8283 ScalarTy->isIntegralType(S.Context) && 8284 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8285 8286 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8287 return true; 8288 8289 ScalarCast = CK_IntegralCast; 8290 } else if (VectorEltTy->isRealFloatingType()) { 8291 if (ScalarTy->isRealFloatingType()) { 8292 8293 // Reject cases where the scalar type is not a constant and has a higher 8294 // Order than the vector element type. 8295 llvm::APFloat Result(0.0); 8296 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8297 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8298 if (!CstScalar && Order < 0) 8299 return true; 8300 8301 // If the scalar cannot be safely casted to the vector element type, 8302 // reject it. 8303 if (CstScalar) { 8304 bool Truncated = false; 8305 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8306 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8307 if (Truncated) 8308 return true; 8309 } 8310 8311 ScalarCast = CK_FloatingCast; 8312 } else if (ScalarTy->isIntegralType(S.Context)) { 8313 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8314 return true; 8315 8316 ScalarCast = CK_IntegralToFloating; 8317 } else 8318 return true; 8319 } 8320 8321 // Adjust scalar if desired. 8322 if (Scalar) { 8323 if (ScalarCast != CK_NoOp) 8324 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8325 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8326 } 8327 return false; 8328 } 8329 8330 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8331 SourceLocation Loc, bool IsCompAssign, 8332 bool AllowBothBool, 8333 bool AllowBoolConversions) { 8334 if (!IsCompAssign) { 8335 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8336 if (LHS.isInvalid()) 8337 return QualType(); 8338 } 8339 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8340 if (RHS.isInvalid()) 8341 return QualType(); 8342 8343 // For conversion purposes, we ignore any qualifiers. 8344 // For example, "const float" and "float" are equivalent. 8345 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8346 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8347 8348 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8349 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8350 assert(LHSVecType || RHSVecType); 8351 8352 // AltiVec-style "vector bool op vector bool" combinations are allowed 8353 // for some operators but not others. 8354 if (!AllowBothBool && 8355 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8356 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8357 return InvalidOperands(Loc, LHS, RHS); 8358 8359 // If the vector types are identical, return. 8360 if (Context.hasSameType(LHSType, RHSType)) 8361 return LHSType; 8362 8363 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8364 if (LHSVecType && RHSVecType && 8365 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8366 if (isa<ExtVectorType>(LHSVecType)) { 8367 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8368 return LHSType; 8369 } 8370 8371 if (!IsCompAssign) 8372 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8373 return RHSType; 8374 } 8375 8376 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8377 // can be mixed, with the result being the non-bool type. The non-bool 8378 // operand must have integer element type. 8379 if (AllowBoolConversions && LHSVecType && RHSVecType && 8380 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8381 (Context.getTypeSize(LHSVecType->getElementType()) == 8382 Context.getTypeSize(RHSVecType->getElementType()))) { 8383 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8384 LHSVecType->getElementType()->isIntegerType() && 8385 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8386 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8387 return LHSType; 8388 } 8389 if (!IsCompAssign && 8390 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8391 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8392 RHSVecType->getElementType()->isIntegerType()) { 8393 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8394 return RHSType; 8395 } 8396 } 8397 8398 // If there's a vector type and a scalar, try to convert the scalar to 8399 // the vector element type and splat. 8400 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8401 if (!RHSVecType) { 8402 if (isa<ExtVectorType>(LHSVecType)) { 8403 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8404 LHSVecType->getElementType(), LHSType, 8405 DiagID)) 8406 return LHSType; 8407 } else { 8408 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8409 return LHSType; 8410 } 8411 } 8412 if (!LHSVecType) { 8413 if (isa<ExtVectorType>(RHSVecType)) { 8414 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8415 LHSType, RHSVecType->getElementType(), 8416 RHSType, DiagID)) 8417 return RHSType; 8418 } else { 8419 if (LHS.get()->getValueKind() == VK_LValue || 8420 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8421 return RHSType; 8422 } 8423 } 8424 8425 // FIXME: The code below also handles conversion between vectors and 8426 // non-scalars, we should break this down into fine grained specific checks 8427 // and emit proper diagnostics. 8428 QualType VecType = LHSVecType ? LHSType : RHSType; 8429 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8430 QualType OtherType = LHSVecType ? RHSType : LHSType; 8431 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8432 if (isLaxVectorConversion(OtherType, VecType)) { 8433 // If we're allowing lax vector conversions, only the total (data) size 8434 // needs to be the same. For non compound assignment, if one of the types is 8435 // scalar, the result is always the vector type. 8436 if (!IsCompAssign) { 8437 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8438 return VecType; 8439 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8440 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8441 // type. Note that this is already done by non-compound assignments in 8442 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8443 // <1 x T> -> T. The result is also a vector type. 8444 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8445 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8446 ExprResult *RHSExpr = &RHS; 8447 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8448 return VecType; 8449 } 8450 } 8451 8452 // Okay, the expression is invalid. 8453 8454 // If there's a non-vector, non-real operand, diagnose that. 8455 if ((!RHSVecType && !RHSType->isRealType()) || 8456 (!LHSVecType && !LHSType->isRealType())) { 8457 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8458 << LHSType << RHSType 8459 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8460 return QualType(); 8461 } 8462 8463 // OpenCL V1.1 6.2.6.p1: 8464 // If the operands are of more than one vector type, then an error shall 8465 // occur. Implicit conversions between vector types are not permitted, per 8466 // section 6.2.1. 8467 if (getLangOpts().OpenCL && 8468 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8469 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8470 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8471 << RHSType; 8472 return QualType(); 8473 } 8474 8475 8476 // If there is a vector type that is not a ExtVector and a scalar, we reach 8477 // this point if scalar could not be converted to the vector's element type 8478 // without truncation. 8479 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8480 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8481 QualType Scalar = LHSVecType ? RHSType : LHSType; 8482 QualType Vector = LHSVecType ? LHSType : RHSType; 8483 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8484 Diag(Loc, 8485 diag::err_typecheck_vector_not_convertable_implict_truncation) 8486 << ScalarOrVector << Scalar << Vector; 8487 8488 return QualType(); 8489 } 8490 8491 // Otherwise, use the generic diagnostic. 8492 Diag(Loc, DiagID) 8493 << LHSType << RHSType 8494 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8495 return QualType(); 8496 } 8497 8498 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8499 // expression. These are mainly cases where the null pointer is used as an 8500 // integer instead of a pointer. 8501 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8502 SourceLocation Loc, bool IsCompare) { 8503 // The canonical way to check for a GNU null is with isNullPointerConstant, 8504 // but we use a bit of a hack here for speed; this is a relatively 8505 // hot path, and isNullPointerConstant is slow. 8506 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8507 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8508 8509 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8510 8511 // Avoid analyzing cases where the result will either be invalid (and 8512 // diagnosed as such) or entirely valid and not something to warn about. 8513 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8514 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8515 return; 8516 8517 // Comparison operations would not make sense with a null pointer no matter 8518 // what the other expression is. 8519 if (!IsCompare) { 8520 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8521 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8522 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8523 return; 8524 } 8525 8526 // The rest of the operations only make sense with a null pointer 8527 // if the other expression is a pointer. 8528 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8529 NonNullType->canDecayToPointerType()) 8530 return; 8531 8532 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8533 << LHSNull /* LHS is NULL */ << NonNullType 8534 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8535 } 8536 8537 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8538 ExprResult &RHS, 8539 SourceLocation Loc, bool IsDiv) { 8540 // Check for division/remainder by zero. 8541 llvm::APSInt RHSValue; 8542 if (!RHS.get()->isValueDependent() && 8543 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8544 S.DiagRuntimeBehavior(Loc, RHS.get(), 8545 S.PDiag(diag::warn_remainder_division_by_zero) 8546 << IsDiv << RHS.get()->getSourceRange()); 8547 } 8548 8549 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8550 SourceLocation Loc, 8551 bool IsCompAssign, bool IsDiv) { 8552 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8553 8554 if (LHS.get()->getType()->isVectorType() || 8555 RHS.get()->getType()->isVectorType()) 8556 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8557 /*AllowBothBool*/getLangOpts().AltiVec, 8558 /*AllowBoolConversions*/false); 8559 8560 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8561 if (LHS.isInvalid() || RHS.isInvalid()) 8562 return QualType(); 8563 8564 8565 if (compType.isNull() || !compType->isArithmeticType()) 8566 return InvalidOperands(Loc, LHS, RHS); 8567 if (IsDiv) 8568 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8569 return compType; 8570 } 8571 8572 QualType Sema::CheckRemainderOperands( 8573 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8574 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8575 8576 if (LHS.get()->getType()->isVectorType() || 8577 RHS.get()->getType()->isVectorType()) { 8578 if (LHS.get()->getType()->hasIntegerRepresentation() && 8579 RHS.get()->getType()->hasIntegerRepresentation()) 8580 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8581 /*AllowBothBool*/getLangOpts().AltiVec, 8582 /*AllowBoolConversions*/false); 8583 return InvalidOperands(Loc, LHS, RHS); 8584 } 8585 8586 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8587 if (LHS.isInvalid() || RHS.isInvalid()) 8588 return QualType(); 8589 8590 if (compType.isNull() || !compType->isIntegerType()) 8591 return InvalidOperands(Loc, LHS, RHS); 8592 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8593 return compType; 8594 } 8595 8596 /// \brief Diagnose invalid arithmetic on two void pointers. 8597 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8598 Expr *LHSExpr, Expr *RHSExpr) { 8599 S.Diag(Loc, S.getLangOpts().CPlusPlus 8600 ? diag::err_typecheck_pointer_arith_void_type 8601 : diag::ext_gnu_void_ptr) 8602 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8603 << RHSExpr->getSourceRange(); 8604 } 8605 8606 /// \brief Diagnose invalid arithmetic on a void pointer. 8607 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8608 Expr *Pointer) { 8609 S.Diag(Loc, S.getLangOpts().CPlusPlus 8610 ? diag::err_typecheck_pointer_arith_void_type 8611 : diag::ext_gnu_void_ptr) 8612 << 0 /* one pointer */ << Pointer->getSourceRange(); 8613 } 8614 8615 /// \brief Diagnose invalid arithmetic on a null pointer. 8616 /// 8617 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8618 /// idiom, which we recognize as a GNU extension. 8619 /// 8620 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8621 Expr *Pointer, bool IsGNUIdiom) { 8622 if (IsGNUIdiom) 8623 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8624 << Pointer->getSourceRange(); 8625 else 8626 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8627 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8628 } 8629 8630 /// \brief Diagnose invalid arithmetic on two function pointers. 8631 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8632 Expr *LHS, Expr *RHS) { 8633 assert(LHS->getType()->isAnyPointerType()); 8634 assert(RHS->getType()->isAnyPointerType()); 8635 S.Diag(Loc, S.getLangOpts().CPlusPlus 8636 ? diag::err_typecheck_pointer_arith_function_type 8637 : diag::ext_gnu_ptr_func_arith) 8638 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8639 // We only show the second type if it differs from the first. 8640 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8641 RHS->getType()) 8642 << RHS->getType()->getPointeeType() 8643 << LHS->getSourceRange() << RHS->getSourceRange(); 8644 } 8645 8646 /// \brief Diagnose invalid arithmetic on a function pointer. 8647 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8648 Expr *Pointer) { 8649 assert(Pointer->getType()->isAnyPointerType()); 8650 S.Diag(Loc, S.getLangOpts().CPlusPlus 8651 ? diag::err_typecheck_pointer_arith_function_type 8652 : diag::ext_gnu_ptr_func_arith) 8653 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8654 << 0 /* one pointer, so only one type */ 8655 << Pointer->getSourceRange(); 8656 } 8657 8658 /// \brief Emit error if Operand is incomplete pointer type 8659 /// 8660 /// \returns True if pointer has incomplete type 8661 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8662 Expr *Operand) { 8663 QualType ResType = Operand->getType(); 8664 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8665 ResType = ResAtomicType->getValueType(); 8666 8667 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8668 QualType PointeeTy = ResType->getPointeeType(); 8669 return S.RequireCompleteType(Loc, PointeeTy, 8670 diag::err_typecheck_arithmetic_incomplete_type, 8671 PointeeTy, Operand->getSourceRange()); 8672 } 8673 8674 /// \brief Check the validity of an arithmetic pointer operand. 8675 /// 8676 /// If the operand has pointer type, this code will check for pointer types 8677 /// which are invalid in arithmetic operations. These will be diagnosed 8678 /// appropriately, including whether or not the use is supported as an 8679 /// extension. 8680 /// 8681 /// \returns True when the operand is valid to use (even if as an extension). 8682 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8683 Expr *Operand) { 8684 QualType ResType = Operand->getType(); 8685 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8686 ResType = ResAtomicType->getValueType(); 8687 8688 if (!ResType->isAnyPointerType()) return true; 8689 8690 QualType PointeeTy = ResType->getPointeeType(); 8691 if (PointeeTy->isVoidType()) { 8692 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8693 return !S.getLangOpts().CPlusPlus; 8694 } 8695 if (PointeeTy->isFunctionType()) { 8696 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8697 return !S.getLangOpts().CPlusPlus; 8698 } 8699 8700 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8701 8702 return true; 8703 } 8704 8705 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8706 /// operands. 8707 /// 8708 /// This routine will diagnose any invalid arithmetic on pointer operands much 8709 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8710 /// for emitting a single diagnostic even for operations where both LHS and RHS 8711 /// are (potentially problematic) pointers. 8712 /// 8713 /// \returns True when the operand is valid to use (even if as an extension). 8714 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8715 Expr *LHSExpr, Expr *RHSExpr) { 8716 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8717 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8718 if (!isLHSPointer && !isRHSPointer) return true; 8719 8720 QualType LHSPointeeTy, RHSPointeeTy; 8721 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8722 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8723 8724 // if both are pointers check if operation is valid wrt address spaces 8725 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8726 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8727 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8728 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8729 S.Diag(Loc, 8730 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8731 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8732 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8733 return false; 8734 } 8735 } 8736 8737 // Check for arithmetic on pointers to incomplete types. 8738 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8739 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8740 if (isLHSVoidPtr || isRHSVoidPtr) { 8741 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8742 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8743 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8744 8745 return !S.getLangOpts().CPlusPlus; 8746 } 8747 8748 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8749 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8750 if (isLHSFuncPtr || isRHSFuncPtr) { 8751 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8752 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8753 RHSExpr); 8754 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8755 8756 return !S.getLangOpts().CPlusPlus; 8757 } 8758 8759 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8760 return false; 8761 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8762 return false; 8763 8764 return true; 8765 } 8766 8767 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8768 /// literal. 8769 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8770 Expr *LHSExpr, Expr *RHSExpr) { 8771 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8772 Expr* IndexExpr = RHSExpr; 8773 if (!StrExpr) { 8774 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8775 IndexExpr = LHSExpr; 8776 } 8777 8778 bool IsStringPlusInt = StrExpr && 8779 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8780 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8781 return; 8782 8783 llvm::APSInt index; 8784 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8785 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8786 if (index.isNonNegative() && 8787 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8788 index.isUnsigned())) 8789 return; 8790 } 8791 8792 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8793 Self.Diag(OpLoc, diag::warn_string_plus_int) 8794 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8795 8796 // Only print a fixit for "str" + int, not for int + "str". 8797 if (IndexExpr == RHSExpr) { 8798 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8799 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8800 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8801 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8802 << FixItHint::CreateInsertion(EndLoc, "]"); 8803 } else 8804 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8805 } 8806 8807 /// \brief Emit a warning when adding a char literal to a string. 8808 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8809 Expr *LHSExpr, Expr *RHSExpr) { 8810 const Expr *StringRefExpr = LHSExpr; 8811 const CharacterLiteral *CharExpr = 8812 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8813 8814 if (!CharExpr) { 8815 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8816 StringRefExpr = RHSExpr; 8817 } 8818 8819 if (!CharExpr || !StringRefExpr) 8820 return; 8821 8822 const QualType StringType = StringRefExpr->getType(); 8823 8824 // Return if not a PointerType. 8825 if (!StringType->isAnyPointerType()) 8826 return; 8827 8828 // Return if not a CharacterType. 8829 if (!StringType->getPointeeType()->isAnyCharacterType()) 8830 return; 8831 8832 ASTContext &Ctx = Self.getASTContext(); 8833 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8834 8835 const QualType CharType = CharExpr->getType(); 8836 if (!CharType->isAnyCharacterType() && 8837 CharType->isIntegerType() && 8838 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8839 Self.Diag(OpLoc, diag::warn_string_plus_char) 8840 << DiagRange << Ctx.CharTy; 8841 } else { 8842 Self.Diag(OpLoc, diag::warn_string_plus_char) 8843 << DiagRange << CharExpr->getType(); 8844 } 8845 8846 // Only print a fixit for str + char, not for char + str. 8847 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8848 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8849 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8850 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8851 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8852 << FixItHint::CreateInsertion(EndLoc, "]"); 8853 } else { 8854 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8855 } 8856 } 8857 8858 /// \brief Emit error when two pointers are incompatible. 8859 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8860 Expr *LHSExpr, Expr *RHSExpr) { 8861 assert(LHSExpr->getType()->isAnyPointerType()); 8862 assert(RHSExpr->getType()->isAnyPointerType()); 8863 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8864 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8865 << RHSExpr->getSourceRange(); 8866 } 8867 8868 // C99 6.5.6 8869 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8870 SourceLocation Loc, BinaryOperatorKind Opc, 8871 QualType* CompLHSTy) { 8872 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8873 8874 if (LHS.get()->getType()->isVectorType() || 8875 RHS.get()->getType()->isVectorType()) { 8876 QualType compType = CheckVectorOperands( 8877 LHS, RHS, Loc, CompLHSTy, 8878 /*AllowBothBool*/getLangOpts().AltiVec, 8879 /*AllowBoolConversions*/getLangOpts().ZVector); 8880 if (CompLHSTy) *CompLHSTy = compType; 8881 return compType; 8882 } 8883 8884 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8885 if (LHS.isInvalid() || RHS.isInvalid()) 8886 return QualType(); 8887 8888 // Diagnose "string literal" '+' int and string '+' "char literal". 8889 if (Opc == BO_Add) { 8890 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8891 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8892 } 8893 8894 // handle the common case first (both operands are arithmetic). 8895 if (!compType.isNull() && compType->isArithmeticType()) { 8896 if (CompLHSTy) *CompLHSTy = compType; 8897 return compType; 8898 } 8899 8900 // Type-checking. Ultimately the pointer's going to be in PExp; 8901 // note that we bias towards the LHS being the pointer. 8902 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8903 8904 bool isObjCPointer; 8905 if (PExp->getType()->isPointerType()) { 8906 isObjCPointer = false; 8907 } else if (PExp->getType()->isObjCObjectPointerType()) { 8908 isObjCPointer = true; 8909 } else { 8910 std::swap(PExp, IExp); 8911 if (PExp->getType()->isPointerType()) { 8912 isObjCPointer = false; 8913 } else if (PExp->getType()->isObjCObjectPointerType()) { 8914 isObjCPointer = true; 8915 } else { 8916 return InvalidOperands(Loc, LHS, RHS); 8917 } 8918 } 8919 assert(PExp->getType()->isAnyPointerType()); 8920 8921 if (!IExp->getType()->isIntegerType()) 8922 return InvalidOperands(Loc, LHS, RHS); 8923 8924 // Adding to a null pointer results in undefined behavior. 8925 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8926 Context, Expr::NPC_ValueDependentIsNotNull)) { 8927 // In C++ adding zero to a null pointer is defined. 8928 llvm::APSInt KnownVal; 8929 if (!getLangOpts().CPlusPlus || 8930 (!IExp->isValueDependent() && 8931 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8932 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8933 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8934 Context, BO_Add, PExp, IExp); 8935 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8936 } 8937 } 8938 8939 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8940 return QualType(); 8941 8942 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8943 return QualType(); 8944 8945 // Check array bounds for pointer arithemtic 8946 CheckArrayAccess(PExp, IExp); 8947 8948 if (CompLHSTy) { 8949 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8950 if (LHSTy.isNull()) { 8951 LHSTy = LHS.get()->getType(); 8952 if (LHSTy->isPromotableIntegerType()) 8953 LHSTy = Context.getPromotedIntegerType(LHSTy); 8954 } 8955 *CompLHSTy = LHSTy; 8956 } 8957 8958 return PExp->getType(); 8959 } 8960 8961 // C99 6.5.6 8962 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8963 SourceLocation Loc, 8964 QualType* CompLHSTy) { 8965 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8966 8967 if (LHS.get()->getType()->isVectorType() || 8968 RHS.get()->getType()->isVectorType()) { 8969 QualType compType = CheckVectorOperands( 8970 LHS, RHS, Loc, CompLHSTy, 8971 /*AllowBothBool*/getLangOpts().AltiVec, 8972 /*AllowBoolConversions*/getLangOpts().ZVector); 8973 if (CompLHSTy) *CompLHSTy = compType; 8974 return compType; 8975 } 8976 8977 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8978 if (LHS.isInvalid() || RHS.isInvalid()) 8979 return QualType(); 8980 8981 // Enforce type constraints: C99 6.5.6p3. 8982 8983 // Handle the common case first (both operands are arithmetic). 8984 if (!compType.isNull() && compType->isArithmeticType()) { 8985 if (CompLHSTy) *CompLHSTy = compType; 8986 return compType; 8987 } 8988 8989 // Either ptr - int or ptr - ptr. 8990 if (LHS.get()->getType()->isAnyPointerType()) { 8991 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8992 8993 // Diagnose bad cases where we step over interface counts. 8994 if (LHS.get()->getType()->isObjCObjectPointerType() && 8995 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8996 return QualType(); 8997 8998 // The result type of a pointer-int computation is the pointer type. 8999 if (RHS.get()->getType()->isIntegerType()) { 9000 // Subtracting from a null pointer should produce a warning. 9001 // The last argument to the diagnose call says this doesn't match the 9002 // GNU int-to-pointer idiom. 9003 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9004 Expr::NPC_ValueDependentIsNotNull)) { 9005 // In C++ adding zero to a null pointer is defined. 9006 llvm::APSInt KnownVal; 9007 if (!getLangOpts().CPlusPlus || 9008 (!RHS.get()->isValueDependent() && 9009 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9010 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9011 } 9012 } 9013 9014 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9015 return QualType(); 9016 9017 // Check array bounds for pointer arithemtic 9018 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9019 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9020 9021 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9022 return LHS.get()->getType(); 9023 } 9024 9025 // Handle pointer-pointer subtractions. 9026 if (const PointerType *RHSPTy 9027 = RHS.get()->getType()->getAs<PointerType>()) { 9028 QualType rpointee = RHSPTy->getPointeeType(); 9029 9030 if (getLangOpts().CPlusPlus) { 9031 // Pointee types must be the same: C++ [expr.add] 9032 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9033 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9034 } 9035 } else { 9036 // Pointee types must be compatible C99 6.5.6p3 9037 if (!Context.typesAreCompatible( 9038 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9039 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9040 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9041 return QualType(); 9042 } 9043 } 9044 9045 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9046 LHS.get(), RHS.get())) 9047 return QualType(); 9048 9049 // FIXME: Add warnings for nullptr - ptr. 9050 9051 // The pointee type may have zero size. As an extension, a structure or 9052 // union may have zero size or an array may have zero length. In this 9053 // case subtraction does not make sense. 9054 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9055 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9056 if (ElementSize.isZero()) { 9057 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9058 << rpointee.getUnqualifiedType() 9059 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9060 } 9061 } 9062 9063 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9064 return Context.getPointerDiffType(); 9065 } 9066 } 9067 9068 return InvalidOperands(Loc, LHS, RHS); 9069 } 9070 9071 static bool isScopedEnumerationType(QualType T) { 9072 if (const EnumType *ET = T->getAs<EnumType>()) 9073 return ET->getDecl()->isScoped(); 9074 return false; 9075 } 9076 9077 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9078 SourceLocation Loc, BinaryOperatorKind Opc, 9079 QualType LHSType) { 9080 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9081 // so skip remaining warnings as we don't want to modify values within Sema. 9082 if (S.getLangOpts().OpenCL) 9083 return; 9084 9085 llvm::APSInt Right; 9086 // Check right/shifter operand 9087 if (RHS.get()->isValueDependent() || 9088 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9089 return; 9090 9091 if (Right.isNegative()) { 9092 S.DiagRuntimeBehavior(Loc, RHS.get(), 9093 S.PDiag(diag::warn_shift_negative) 9094 << RHS.get()->getSourceRange()); 9095 return; 9096 } 9097 llvm::APInt LeftBits(Right.getBitWidth(), 9098 S.Context.getTypeSize(LHS.get()->getType())); 9099 if (Right.uge(LeftBits)) { 9100 S.DiagRuntimeBehavior(Loc, RHS.get(), 9101 S.PDiag(diag::warn_shift_gt_typewidth) 9102 << RHS.get()->getSourceRange()); 9103 return; 9104 } 9105 if (Opc != BO_Shl) 9106 return; 9107 9108 // When left shifting an ICE which is signed, we can check for overflow which 9109 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9110 // integers have defined behavior modulo one more than the maximum value 9111 // representable in the result type, so never warn for those. 9112 llvm::APSInt Left; 9113 if (LHS.get()->isValueDependent() || 9114 LHSType->hasUnsignedIntegerRepresentation() || 9115 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9116 return; 9117 9118 // If LHS does not have a signed type and non-negative value 9119 // then, the behavior is undefined. Warn about it. 9120 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9121 S.DiagRuntimeBehavior(Loc, LHS.get(), 9122 S.PDiag(diag::warn_shift_lhs_negative) 9123 << LHS.get()->getSourceRange()); 9124 return; 9125 } 9126 9127 llvm::APInt ResultBits = 9128 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9129 if (LeftBits.uge(ResultBits)) 9130 return; 9131 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9132 Result = Result.shl(Right); 9133 9134 // Print the bit representation of the signed integer as an unsigned 9135 // hexadecimal number. 9136 SmallString<40> HexResult; 9137 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9138 9139 // If we are only missing a sign bit, this is less likely to result in actual 9140 // bugs -- if the result is cast back to an unsigned type, it will have the 9141 // expected value. Thus we place this behind a different warning that can be 9142 // turned off separately if needed. 9143 if (LeftBits == ResultBits - 1) { 9144 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9145 << HexResult << LHSType 9146 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9147 return; 9148 } 9149 9150 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9151 << HexResult.str() << Result.getMinSignedBits() << LHSType 9152 << Left.getBitWidth() << LHS.get()->getSourceRange() 9153 << RHS.get()->getSourceRange(); 9154 } 9155 9156 /// \brief Return the resulting type when a vector is shifted 9157 /// by a scalar or vector shift amount. 9158 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9159 SourceLocation Loc, bool IsCompAssign) { 9160 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9161 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9162 !LHS.get()->getType()->isVectorType()) { 9163 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9164 << RHS.get()->getType() << LHS.get()->getType() 9165 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9166 return QualType(); 9167 } 9168 9169 if (!IsCompAssign) { 9170 LHS = S.UsualUnaryConversions(LHS.get()); 9171 if (LHS.isInvalid()) return QualType(); 9172 } 9173 9174 RHS = S.UsualUnaryConversions(RHS.get()); 9175 if (RHS.isInvalid()) return QualType(); 9176 9177 QualType LHSType = LHS.get()->getType(); 9178 // Note that LHS might be a scalar because the routine calls not only in 9179 // OpenCL case. 9180 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9181 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9182 9183 // Note that RHS might not be a vector. 9184 QualType RHSType = RHS.get()->getType(); 9185 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9186 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9187 9188 // The operands need to be integers. 9189 if (!LHSEleType->isIntegerType()) { 9190 S.Diag(Loc, diag::err_typecheck_expect_int) 9191 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9192 return QualType(); 9193 } 9194 9195 if (!RHSEleType->isIntegerType()) { 9196 S.Diag(Loc, diag::err_typecheck_expect_int) 9197 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9198 return QualType(); 9199 } 9200 9201 if (!LHSVecTy) { 9202 assert(RHSVecTy); 9203 if (IsCompAssign) 9204 return RHSType; 9205 if (LHSEleType != RHSEleType) { 9206 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9207 LHSEleType = RHSEleType; 9208 } 9209 QualType VecTy = 9210 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9211 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9212 LHSType = VecTy; 9213 } else if (RHSVecTy) { 9214 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9215 // are applied component-wise. So if RHS is a vector, then ensure 9216 // that the number of elements is the same as LHS... 9217 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9218 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9219 << LHS.get()->getType() << RHS.get()->getType() 9220 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9221 return QualType(); 9222 } 9223 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9224 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9225 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9226 if (LHSBT != RHSBT && 9227 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9228 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9229 << LHS.get()->getType() << RHS.get()->getType() 9230 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9231 } 9232 } 9233 } else { 9234 // ...else expand RHS to match the number of elements in LHS. 9235 QualType VecTy = 9236 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9237 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9238 } 9239 9240 return LHSType; 9241 } 9242 9243 // C99 6.5.7 9244 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9245 SourceLocation Loc, BinaryOperatorKind Opc, 9246 bool IsCompAssign) { 9247 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9248 9249 // Vector shifts promote their scalar inputs to vector type. 9250 if (LHS.get()->getType()->isVectorType() || 9251 RHS.get()->getType()->isVectorType()) { 9252 if (LangOpts.ZVector) { 9253 // The shift operators for the z vector extensions work basically 9254 // like general shifts, except that neither the LHS nor the RHS is 9255 // allowed to be a "vector bool". 9256 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9257 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9258 return InvalidOperands(Loc, LHS, RHS); 9259 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9260 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9261 return InvalidOperands(Loc, LHS, RHS); 9262 } 9263 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9264 } 9265 9266 // Shifts don't perform usual arithmetic conversions, they just do integer 9267 // promotions on each operand. C99 6.5.7p3 9268 9269 // For the LHS, do usual unary conversions, but then reset them away 9270 // if this is a compound assignment. 9271 ExprResult OldLHS = LHS; 9272 LHS = UsualUnaryConversions(LHS.get()); 9273 if (LHS.isInvalid()) 9274 return QualType(); 9275 QualType LHSType = LHS.get()->getType(); 9276 if (IsCompAssign) LHS = OldLHS; 9277 9278 // The RHS is simpler. 9279 RHS = UsualUnaryConversions(RHS.get()); 9280 if (RHS.isInvalid()) 9281 return QualType(); 9282 QualType RHSType = RHS.get()->getType(); 9283 9284 // C99 6.5.7p2: Each of the operands shall have integer type. 9285 if (!LHSType->hasIntegerRepresentation() || 9286 !RHSType->hasIntegerRepresentation()) 9287 return InvalidOperands(Loc, LHS, RHS); 9288 9289 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9290 // hasIntegerRepresentation() above instead of this. 9291 if (isScopedEnumerationType(LHSType) || 9292 isScopedEnumerationType(RHSType)) { 9293 return InvalidOperands(Loc, LHS, RHS); 9294 } 9295 // Sanity-check shift operands 9296 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9297 9298 // "The type of the result is that of the promoted left operand." 9299 return LHSType; 9300 } 9301 9302 /// If two different enums are compared, raise a warning. 9303 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9304 Expr *RHS) { 9305 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9306 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9307 9308 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9309 if (!LHSEnumType) 9310 return; 9311 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9312 if (!RHSEnumType) 9313 return; 9314 9315 // Ignore anonymous enums. 9316 if (!LHSEnumType->getDecl()->getIdentifier() && 9317 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9318 return; 9319 if (!RHSEnumType->getDecl()->getIdentifier() && 9320 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9321 return; 9322 9323 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9324 return; 9325 9326 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9327 << LHSStrippedType << RHSStrippedType 9328 << LHS->getSourceRange() << RHS->getSourceRange(); 9329 } 9330 9331 /// \brief Diagnose bad pointer comparisons. 9332 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9333 ExprResult &LHS, ExprResult &RHS, 9334 bool IsError) { 9335 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9336 : diag::ext_typecheck_comparison_of_distinct_pointers) 9337 << LHS.get()->getType() << RHS.get()->getType() 9338 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9339 } 9340 9341 /// \brief Returns false if the pointers are converted to a composite type, 9342 /// true otherwise. 9343 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9344 ExprResult &LHS, ExprResult &RHS) { 9345 // C++ [expr.rel]p2: 9346 // [...] Pointer conversions (4.10) and qualification 9347 // conversions (4.4) are performed on pointer operands (or on 9348 // a pointer operand and a null pointer constant) to bring 9349 // them to their composite pointer type. [...] 9350 // 9351 // C++ [expr.eq]p1 uses the same notion for (in)equality 9352 // comparisons of pointers. 9353 9354 QualType LHSType = LHS.get()->getType(); 9355 QualType RHSType = RHS.get()->getType(); 9356 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9357 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9358 9359 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9360 if (T.isNull()) { 9361 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9362 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9363 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9364 else 9365 S.InvalidOperands(Loc, LHS, RHS); 9366 return true; 9367 } 9368 9369 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9370 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9371 return false; 9372 } 9373 9374 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9375 ExprResult &LHS, 9376 ExprResult &RHS, 9377 bool IsError) { 9378 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9379 : diag::ext_typecheck_comparison_of_fptr_to_void) 9380 << LHS.get()->getType() << RHS.get()->getType() 9381 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9382 } 9383 9384 static bool isObjCObjectLiteral(ExprResult &E) { 9385 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9386 case Stmt::ObjCArrayLiteralClass: 9387 case Stmt::ObjCDictionaryLiteralClass: 9388 case Stmt::ObjCStringLiteralClass: 9389 case Stmt::ObjCBoxedExprClass: 9390 return true; 9391 default: 9392 // Note that ObjCBoolLiteral is NOT an object literal! 9393 return false; 9394 } 9395 } 9396 9397 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9398 const ObjCObjectPointerType *Type = 9399 LHS->getType()->getAs<ObjCObjectPointerType>(); 9400 9401 // If this is not actually an Objective-C object, bail out. 9402 if (!Type) 9403 return false; 9404 9405 // Get the LHS object's interface type. 9406 QualType InterfaceType = Type->getPointeeType(); 9407 9408 // If the RHS isn't an Objective-C object, bail out. 9409 if (!RHS->getType()->isObjCObjectPointerType()) 9410 return false; 9411 9412 // Try to find the -isEqual: method. 9413 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9414 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9415 InterfaceType, 9416 /*instance=*/true); 9417 if (!Method) { 9418 if (Type->isObjCIdType()) { 9419 // For 'id', just check the global pool. 9420 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9421 /*receiverId=*/true); 9422 } else { 9423 // Check protocols. 9424 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9425 /*instance=*/true); 9426 } 9427 } 9428 9429 if (!Method) 9430 return false; 9431 9432 QualType T = Method->parameters()[0]->getType(); 9433 if (!T->isObjCObjectPointerType()) 9434 return false; 9435 9436 QualType R = Method->getReturnType(); 9437 if (!R->isScalarType()) 9438 return false; 9439 9440 return true; 9441 } 9442 9443 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9444 FromE = FromE->IgnoreParenImpCasts(); 9445 switch (FromE->getStmtClass()) { 9446 default: 9447 break; 9448 case Stmt::ObjCStringLiteralClass: 9449 // "string literal" 9450 return LK_String; 9451 case Stmt::ObjCArrayLiteralClass: 9452 // "array literal" 9453 return LK_Array; 9454 case Stmt::ObjCDictionaryLiteralClass: 9455 // "dictionary literal" 9456 return LK_Dictionary; 9457 case Stmt::BlockExprClass: 9458 return LK_Block; 9459 case Stmt::ObjCBoxedExprClass: { 9460 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9461 switch (Inner->getStmtClass()) { 9462 case Stmt::IntegerLiteralClass: 9463 case Stmt::FloatingLiteralClass: 9464 case Stmt::CharacterLiteralClass: 9465 case Stmt::ObjCBoolLiteralExprClass: 9466 case Stmt::CXXBoolLiteralExprClass: 9467 // "numeric literal" 9468 return LK_Numeric; 9469 case Stmt::ImplicitCastExprClass: { 9470 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9471 // Boolean literals can be represented by implicit casts. 9472 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9473 return LK_Numeric; 9474 break; 9475 } 9476 default: 9477 break; 9478 } 9479 return LK_Boxed; 9480 } 9481 } 9482 return LK_None; 9483 } 9484 9485 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9486 ExprResult &LHS, ExprResult &RHS, 9487 BinaryOperator::Opcode Opc){ 9488 Expr *Literal; 9489 Expr *Other; 9490 if (isObjCObjectLiteral(LHS)) { 9491 Literal = LHS.get(); 9492 Other = RHS.get(); 9493 } else { 9494 Literal = RHS.get(); 9495 Other = LHS.get(); 9496 } 9497 9498 // Don't warn on comparisons against nil. 9499 Other = Other->IgnoreParenCasts(); 9500 if (Other->isNullPointerConstant(S.getASTContext(), 9501 Expr::NPC_ValueDependentIsNotNull)) 9502 return; 9503 9504 // This should be kept in sync with warn_objc_literal_comparison. 9505 // LK_String should always be after the other literals, since it has its own 9506 // warning flag. 9507 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9508 assert(LiteralKind != Sema::LK_Block); 9509 if (LiteralKind == Sema::LK_None) { 9510 llvm_unreachable("Unknown Objective-C object literal kind"); 9511 } 9512 9513 if (LiteralKind == Sema::LK_String) 9514 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9515 << Literal->getSourceRange(); 9516 else 9517 S.Diag(Loc, diag::warn_objc_literal_comparison) 9518 << LiteralKind << Literal->getSourceRange(); 9519 9520 if (BinaryOperator::isEqualityOp(Opc) && 9521 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9522 SourceLocation Start = LHS.get()->getLocStart(); 9523 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9524 CharSourceRange OpRange = 9525 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9526 9527 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9528 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9529 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9530 << FixItHint::CreateInsertion(End, "]"); 9531 } 9532 } 9533 9534 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9535 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9536 ExprResult &RHS, SourceLocation Loc, 9537 BinaryOperatorKind Opc) { 9538 // Check that left hand side is !something. 9539 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9540 if (!UO || UO->getOpcode() != UO_LNot) return; 9541 9542 // Only check if the right hand side is non-bool arithmetic type. 9543 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9544 9545 // Make sure that the something in !something is not bool. 9546 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9547 if (SubExpr->isKnownToHaveBooleanValue()) return; 9548 9549 // Emit warning. 9550 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9551 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9552 << Loc << IsBitwiseOp; 9553 9554 // First note suggest !(x < y) 9555 SourceLocation FirstOpen = SubExpr->getLocStart(); 9556 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9557 FirstClose = S.getLocForEndOfToken(FirstClose); 9558 if (FirstClose.isInvalid()) 9559 FirstOpen = SourceLocation(); 9560 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9561 << IsBitwiseOp 9562 << FixItHint::CreateInsertion(FirstOpen, "(") 9563 << FixItHint::CreateInsertion(FirstClose, ")"); 9564 9565 // Second note suggests (!x) < y 9566 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9567 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9568 SecondClose = S.getLocForEndOfToken(SecondClose); 9569 if (SecondClose.isInvalid()) 9570 SecondOpen = SourceLocation(); 9571 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9572 << FixItHint::CreateInsertion(SecondOpen, "(") 9573 << FixItHint::CreateInsertion(SecondClose, ")"); 9574 } 9575 9576 // Get the decl for a simple expression: a reference to a variable, 9577 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9578 static ValueDecl *getCompareDecl(Expr *E) { 9579 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9580 return DR->getDecl(); 9581 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9582 if (Ivar->isFreeIvar()) 9583 return Ivar->getDecl(); 9584 } 9585 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9586 if (Mem->isImplicitAccess()) 9587 return Mem->getMemberDecl(); 9588 } 9589 return nullptr; 9590 } 9591 9592 /// Diagnose some forms of syntactically-obvious tautological comparison. 9593 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9594 Expr *LHS, Expr *RHS, 9595 BinaryOperatorKind Opc) { 9596 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9597 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9598 9599 QualType LHSType = LHS->getType(); 9600 if (LHSType->hasFloatingRepresentation() || 9601 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9602 LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() || 9603 S.inTemplateInstantiation()) 9604 return; 9605 9606 // For non-floating point types, check for self-comparisons of the form 9607 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9608 // often indicate logic errors in the program. 9609 // 9610 // NOTE: Don't warn about comparison expressions resulting from macro 9611 // expansion. Also don't warn about comparisons which are only self 9612 // comparisons within a template instantiation. The warnings should catch 9613 // obvious cases in the definition of the template anyways. The idea is to 9614 // warn when the typed comparison operator will always evaluate to the same 9615 // result. 9616 ValueDecl *DL = getCompareDecl(LHSStripped); 9617 ValueDecl *DR = getCompareDecl(RHSStripped); 9618 if (DL && DR && declaresSameEntity(DL, DR)) { 9619 StringRef Result; 9620 switch (Opc) { 9621 case BO_EQ: case BO_LE: case BO_GE: 9622 Result = "true"; 9623 break; 9624 case BO_NE: case BO_LT: case BO_GT: 9625 Result = "false"; 9626 break; 9627 case BO_Cmp: 9628 Result = "'std::strong_ordering::equal'"; 9629 break; 9630 default: 9631 break; 9632 } 9633 S.DiagRuntimeBehavior(Loc, nullptr, 9634 S.PDiag(diag::warn_comparison_always) 9635 << 0 /*self-comparison*/ << !Result.empty() 9636 << Result); 9637 } else if (DL && DR && 9638 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9639 !DL->isWeak() && !DR->isWeak()) { 9640 // What is it always going to evaluate to? 9641 StringRef Result; 9642 switch(Opc) { 9643 case BO_EQ: // e.g. array1 == array2 9644 Result = "false"; 9645 break; 9646 case BO_NE: // e.g. array1 != array2 9647 Result = "true"; 9648 break; 9649 default: // e.g. array1 <= array2 9650 // The best we can say is 'a constant' 9651 break; 9652 } 9653 S.DiagRuntimeBehavior(Loc, nullptr, 9654 S.PDiag(diag::warn_comparison_always) 9655 << 1 /*array comparison*/ 9656 << !Result.empty() << Result); 9657 } 9658 9659 if (isa<CastExpr>(LHSStripped)) 9660 LHSStripped = LHSStripped->IgnoreParenCasts(); 9661 if (isa<CastExpr>(RHSStripped)) 9662 RHSStripped = RHSStripped->IgnoreParenCasts(); 9663 9664 // Warn about comparisons against a string constant (unless the other 9665 // operand is null); the user probably wants strcmp. 9666 Expr *LiteralString = nullptr; 9667 Expr *LiteralStringStripped = nullptr; 9668 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9669 !RHSStripped->isNullPointerConstant(S.Context, 9670 Expr::NPC_ValueDependentIsNull)) { 9671 LiteralString = LHS; 9672 LiteralStringStripped = LHSStripped; 9673 } else if ((isa<StringLiteral>(RHSStripped) || 9674 isa<ObjCEncodeExpr>(RHSStripped)) && 9675 !LHSStripped->isNullPointerConstant(S.Context, 9676 Expr::NPC_ValueDependentIsNull)) { 9677 LiteralString = RHS; 9678 LiteralStringStripped = RHSStripped; 9679 } 9680 9681 if (LiteralString) { 9682 S.DiagRuntimeBehavior(Loc, nullptr, 9683 S.PDiag(diag::warn_stringcompare) 9684 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9685 << LiteralString->getSourceRange()); 9686 } 9687 } 9688 9689 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 9690 ExprResult &RHS, 9691 SourceLocation Loc, 9692 BinaryOperatorKind Opc) { 9693 // C99 6.5.8p3 / C99 6.5.9p4 9694 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9695 if (LHS.isInvalid() || RHS.isInvalid()) 9696 return QualType(); 9697 if (Type.isNull()) 9698 return S.InvalidOperands(Loc, LHS, RHS); 9699 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9700 9701 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 9702 9703 enum { StrongEquality, PartialOrdering, StrongOrdering } Ordering; 9704 if (Type->isAnyComplexType()) 9705 Ordering = StrongEquality; 9706 else if (Type->isFloatingType()) 9707 Ordering = PartialOrdering; 9708 else 9709 Ordering = StrongOrdering; 9710 9711 if (Ordering == StrongEquality && BinaryOperator::isRelationalOp(Opc)) 9712 return S.InvalidOperands(Loc, LHS, RHS); 9713 9714 // Check for comparisons of floating point operands using != and ==. 9715 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 9716 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9717 9718 // The result of comparisons is 'bool' in C++, 'int' in C. 9719 // FIXME: For BO_Cmp, return the relevant comparison category type. 9720 return S.Context.getLogicalOperationType(); 9721 } 9722 9723 // C99 6.5.8, C++ [expr.rel] 9724 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9725 SourceLocation Loc, BinaryOperatorKind Opc, 9726 bool IsRelational) { 9727 // Comparisons expect an rvalue, so convert to rvalue before any 9728 // type-related checks. 9729 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9730 if (LHS.isInvalid()) 9731 return QualType(); 9732 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9733 if (RHS.isInvalid()) 9734 return QualType(); 9735 9736 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9737 9738 // Handle vector comparisons separately. 9739 if (LHS.get()->getType()->isVectorType() || 9740 RHS.get()->getType()->isVectorType()) 9741 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 9742 9743 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9744 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 9745 9746 QualType LHSType = LHS.get()->getType(); 9747 QualType RHSType = RHS.get()->getType(); 9748 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 9749 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 9750 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 9751 9752 QualType ResultTy = Context.getLogicalOperationType(); 9753 9754 const Expr::NullPointerConstantKind LHSNullKind = 9755 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9756 const Expr::NullPointerConstantKind RHSNullKind = 9757 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9758 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9759 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9760 9761 if (!IsRelational && LHSIsNull != RHSIsNull) { 9762 bool IsEquality = Opc == BO_EQ; 9763 if (RHSIsNull) 9764 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9765 RHS.get()->getSourceRange()); 9766 else 9767 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9768 LHS.get()->getSourceRange()); 9769 } 9770 9771 if ((LHSType->isIntegerType() && !LHSIsNull) || 9772 (RHSType->isIntegerType() && !RHSIsNull)) { 9773 // Skip normal pointer conversion checks in this case; we have better 9774 // diagnostics for this below. 9775 } else if (getLangOpts().CPlusPlus) { 9776 // Equality comparison of a function pointer to a void pointer is invalid, 9777 // but we allow it as an extension. 9778 // FIXME: If we really want to allow this, should it be part of composite 9779 // pointer type computation so it works in conditionals too? 9780 if (!IsRelational && 9781 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9782 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9783 // This is a gcc extension compatibility comparison. 9784 // In a SFINAE context, we treat this as a hard error to maintain 9785 // conformance with the C++ standard. 9786 diagnoseFunctionPointerToVoidComparison( 9787 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9788 9789 if (isSFINAEContext()) 9790 return QualType(); 9791 9792 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9793 return ResultTy; 9794 } 9795 9796 // C++ [expr.eq]p2: 9797 // If at least one operand is a pointer [...] bring them to their 9798 // composite pointer type. 9799 // C++ [expr.rel]p2: 9800 // If both operands are pointers, [...] bring them to their composite 9801 // pointer type. 9802 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9803 (IsRelational ? 2 : 1) && 9804 (!LangOpts.ObjCAutoRefCount || 9805 !(LHSType->isObjCObjectPointerType() || 9806 RHSType->isObjCObjectPointerType()))) { 9807 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9808 return QualType(); 9809 else 9810 return ResultTy; 9811 } 9812 } else if (LHSType->isPointerType() && 9813 RHSType->isPointerType()) { // C99 6.5.8p2 9814 // All of the following pointer-related warnings are GCC extensions, except 9815 // when handling null pointer constants. 9816 QualType LCanPointeeTy = 9817 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9818 QualType RCanPointeeTy = 9819 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9820 9821 // C99 6.5.9p2 and C99 6.5.8p2 9822 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9823 RCanPointeeTy.getUnqualifiedType())) { 9824 // Valid unless a relational comparison of function pointers 9825 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9826 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9827 << LHSType << RHSType << LHS.get()->getSourceRange() 9828 << RHS.get()->getSourceRange(); 9829 } 9830 } else if (!IsRelational && 9831 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9832 // Valid unless comparison between non-null pointer and function pointer 9833 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9834 && !LHSIsNull && !RHSIsNull) 9835 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9836 /*isError*/false); 9837 } else { 9838 // Invalid 9839 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9840 } 9841 if (LCanPointeeTy != RCanPointeeTy) { 9842 // Treat NULL constant as a special case in OpenCL. 9843 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9844 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9845 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9846 Diag(Loc, 9847 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9848 << LHSType << RHSType << 0 /* comparison */ 9849 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9850 } 9851 } 9852 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9853 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9854 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9855 : CK_BitCast; 9856 if (LHSIsNull && !RHSIsNull) 9857 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9858 else 9859 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9860 } 9861 return ResultTy; 9862 } 9863 9864 if (getLangOpts().CPlusPlus) { 9865 // C++ [expr.eq]p4: 9866 // Two operands of type std::nullptr_t or one operand of type 9867 // std::nullptr_t and the other a null pointer constant compare equal. 9868 if (!IsRelational && LHSIsNull && RHSIsNull) { 9869 if (LHSType->isNullPtrType()) { 9870 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9871 return ResultTy; 9872 } 9873 if (RHSType->isNullPtrType()) { 9874 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9875 return ResultTy; 9876 } 9877 } 9878 9879 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9880 // These aren't covered by the composite pointer type rules. 9881 if (!IsRelational && RHSType->isNullPtrType() && 9882 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9883 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9884 return ResultTy; 9885 } 9886 if (!IsRelational && LHSType->isNullPtrType() && 9887 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9888 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9889 return ResultTy; 9890 } 9891 9892 if (IsRelational && 9893 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9894 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9895 // HACK: Relational comparison of nullptr_t against a pointer type is 9896 // invalid per DR583, but we allow it within std::less<> and friends, 9897 // since otherwise common uses of it break. 9898 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9899 // friends to have std::nullptr_t overload candidates. 9900 DeclContext *DC = CurContext; 9901 if (isa<FunctionDecl>(DC)) 9902 DC = DC->getParent(); 9903 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9904 if (CTSD->isInStdNamespace() && 9905 llvm::StringSwitch<bool>(CTSD->getName()) 9906 .Cases("less", "less_equal", "greater", "greater_equal", true) 9907 .Default(false)) { 9908 if (RHSType->isNullPtrType()) 9909 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9910 else 9911 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9912 return ResultTy; 9913 } 9914 } 9915 } 9916 9917 // C++ [expr.eq]p2: 9918 // If at least one operand is a pointer to member, [...] bring them to 9919 // their composite pointer type. 9920 if (!IsRelational && 9921 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9922 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9923 return QualType(); 9924 else 9925 return ResultTy; 9926 } 9927 } 9928 9929 // Handle block pointer types. 9930 if (!IsRelational && LHSType->isBlockPointerType() && 9931 RHSType->isBlockPointerType()) { 9932 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9933 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9934 9935 if (!LHSIsNull && !RHSIsNull && 9936 !Context.typesAreCompatible(lpointee, rpointee)) { 9937 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9938 << LHSType << RHSType << LHS.get()->getSourceRange() 9939 << RHS.get()->getSourceRange(); 9940 } 9941 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9942 return ResultTy; 9943 } 9944 9945 // Allow block pointers to be compared with null pointer constants. 9946 if (!IsRelational 9947 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9948 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9949 if (!LHSIsNull && !RHSIsNull) { 9950 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9951 ->getPointeeType()->isVoidType()) 9952 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9953 ->getPointeeType()->isVoidType()))) 9954 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9955 << LHSType << RHSType << LHS.get()->getSourceRange() 9956 << RHS.get()->getSourceRange(); 9957 } 9958 if (LHSIsNull && !RHSIsNull) 9959 LHS = ImpCastExprToType(LHS.get(), RHSType, 9960 RHSType->isPointerType() ? CK_BitCast 9961 : CK_AnyPointerToBlockPointerCast); 9962 else 9963 RHS = ImpCastExprToType(RHS.get(), LHSType, 9964 LHSType->isPointerType() ? CK_BitCast 9965 : CK_AnyPointerToBlockPointerCast); 9966 return ResultTy; 9967 } 9968 9969 if (LHSType->isObjCObjectPointerType() || 9970 RHSType->isObjCObjectPointerType()) { 9971 const PointerType *LPT = LHSType->getAs<PointerType>(); 9972 const PointerType *RPT = RHSType->getAs<PointerType>(); 9973 if (LPT || RPT) { 9974 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9975 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9976 9977 if (!LPtrToVoid && !RPtrToVoid && 9978 !Context.typesAreCompatible(LHSType, RHSType)) { 9979 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9980 /*isError*/false); 9981 } 9982 if (LHSIsNull && !RHSIsNull) { 9983 Expr *E = LHS.get(); 9984 if (getLangOpts().ObjCAutoRefCount) 9985 CheckObjCConversion(SourceRange(), RHSType, E, 9986 CCK_ImplicitConversion); 9987 LHS = ImpCastExprToType(E, RHSType, 9988 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9989 } 9990 else { 9991 Expr *E = RHS.get(); 9992 if (getLangOpts().ObjCAutoRefCount) 9993 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9994 /*Diagnose=*/true, 9995 /*DiagnoseCFAudited=*/false, Opc); 9996 RHS = ImpCastExprToType(E, LHSType, 9997 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9998 } 9999 return ResultTy; 10000 } 10001 if (LHSType->isObjCObjectPointerType() && 10002 RHSType->isObjCObjectPointerType()) { 10003 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10004 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10005 /*isError*/false); 10006 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10007 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10008 10009 if (LHSIsNull && !RHSIsNull) 10010 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10011 else 10012 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10013 return ResultTy; 10014 } 10015 } 10016 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10017 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10018 unsigned DiagID = 0; 10019 bool isError = false; 10020 if (LangOpts.DebuggerSupport) { 10021 // Under a debugger, allow the comparison of pointers to integers, 10022 // since users tend to want to compare addresses. 10023 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10024 (RHSIsNull && RHSType->isIntegerType())) { 10025 if (IsRelational) { 10026 isError = getLangOpts().CPlusPlus; 10027 DiagID = 10028 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10029 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10030 } 10031 } else if (getLangOpts().CPlusPlus) { 10032 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10033 isError = true; 10034 } else if (IsRelational) 10035 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10036 else 10037 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10038 10039 if (DiagID) { 10040 Diag(Loc, DiagID) 10041 << LHSType << RHSType << LHS.get()->getSourceRange() 10042 << RHS.get()->getSourceRange(); 10043 if (isError) 10044 return QualType(); 10045 } 10046 10047 if (LHSType->isIntegerType()) 10048 LHS = ImpCastExprToType(LHS.get(), RHSType, 10049 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10050 else 10051 RHS = ImpCastExprToType(RHS.get(), LHSType, 10052 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10053 return ResultTy; 10054 } 10055 10056 // Handle block pointers. 10057 if (!IsRelational && RHSIsNull 10058 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10059 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10060 return ResultTy; 10061 } 10062 if (!IsRelational && LHSIsNull 10063 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10064 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10065 return ResultTy; 10066 } 10067 10068 if (getLangOpts().OpenCLVersion >= 200) { 10069 if (LHSIsNull && RHSType->isQueueT()) { 10070 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10071 return ResultTy; 10072 } 10073 10074 if (LHSType->isQueueT() && RHSIsNull) { 10075 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10076 return ResultTy; 10077 } 10078 } 10079 10080 return InvalidOperands(Loc, LHS, RHS); 10081 } 10082 10083 // Return a signed ext_vector_type that is of identical size and number of 10084 // elements. For floating point vectors, return an integer type of identical 10085 // size and number of elements. In the non ext_vector_type case, search from 10086 // the largest type to the smallest type to avoid cases where long long == long, 10087 // where long gets picked over long long. 10088 QualType Sema::GetSignedVectorType(QualType V) { 10089 const VectorType *VTy = V->getAs<VectorType>(); 10090 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10091 10092 if (isa<ExtVectorType>(VTy)) { 10093 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10094 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10095 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10096 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10097 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10098 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10099 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10100 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10101 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10102 "Unhandled vector element size in vector compare"); 10103 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10104 } 10105 10106 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10107 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10108 VectorType::GenericVector); 10109 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10110 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10111 VectorType::GenericVector); 10112 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10113 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10114 VectorType::GenericVector); 10115 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10116 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10117 VectorType::GenericVector); 10118 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10119 "Unhandled vector element size in vector compare"); 10120 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10121 VectorType::GenericVector); 10122 } 10123 10124 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10125 /// operates on extended vector types. Instead of producing an IntTy result, 10126 /// like a scalar comparison, a vector comparison produces a vector of integer 10127 /// types. 10128 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10129 SourceLocation Loc, 10130 BinaryOperatorKind Opc) { 10131 // Check to make sure we're operating on vectors of the same type and width, 10132 // Allowing one side to be a scalar of element type. 10133 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10134 /*AllowBothBool*/true, 10135 /*AllowBoolConversions*/getLangOpts().ZVector); 10136 if (vType.isNull()) 10137 return vType; 10138 10139 QualType LHSType = LHS.get()->getType(); 10140 10141 // If AltiVec, the comparison results in a numeric type, i.e. 10142 // bool for C++, int for C 10143 if (getLangOpts().AltiVec && 10144 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10145 return Context.getLogicalOperationType(); 10146 10147 // For non-floating point types, check for self-comparisons of the form 10148 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10149 // often indicate logic errors in the program. 10150 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10151 10152 // Check for comparisons of floating point operands using != and ==. 10153 if (BinaryOperator::isEqualityOp(Opc) && 10154 LHSType->hasFloatingRepresentation()) { 10155 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10156 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10157 } 10158 10159 // Return a signed type for the vector. 10160 return GetSignedVectorType(vType); 10161 } 10162 10163 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10164 SourceLocation Loc) { 10165 // Ensure that either both operands are of the same vector type, or 10166 // one operand is of a vector type and the other is of its element type. 10167 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10168 /*AllowBothBool*/true, 10169 /*AllowBoolConversions*/false); 10170 if (vType.isNull()) 10171 return InvalidOperands(Loc, LHS, RHS); 10172 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10173 vType->hasFloatingRepresentation()) 10174 return InvalidOperands(Loc, LHS, RHS); 10175 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10176 // usage of the logical operators && and || with vectors in C. This 10177 // check could be notionally dropped. 10178 if (!getLangOpts().CPlusPlus && 10179 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10180 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10181 10182 return GetSignedVectorType(LHS.get()->getType()); 10183 } 10184 10185 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10186 SourceLocation Loc, 10187 BinaryOperatorKind Opc) { 10188 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10189 10190 bool IsCompAssign = 10191 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10192 10193 if (LHS.get()->getType()->isVectorType() || 10194 RHS.get()->getType()->isVectorType()) { 10195 if (LHS.get()->getType()->hasIntegerRepresentation() && 10196 RHS.get()->getType()->hasIntegerRepresentation()) 10197 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10198 /*AllowBothBool*/true, 10199 /*AllowBoolConversions*/getLangOpts().ZVector); 10200 return InvalidOperands(Loc, LHS, RHS); 10201 } 10202 10203 if (Opc == BO_And) 10204 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10205 10206 ExprResult LHSResult = LHS, RHSResult = RHS; 10207 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10208 IsCompAssign); 10209 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10210 return QualType(); 10211 LHS = LHSResult.get(); 10212 RHS = RHSResult.get(); 10213 10214 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10215 return compType; 10216 return InvalidOperands(Loc, LHS, RHS); 10217 } 10218 10219 // C99 6.5.[13,14] 10220 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10221 SourceLocation Loc, 10222 BinaryOperatorKind Opc) { 10223 // Check vector operands differently. 10224 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10225 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10226 10227 // Diagnose cases where the user write a logical and/or but probably meant a 10228 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10229 // is a constant. 10230 if (LHS.get()->getType()->isIntegerType() && 10231 !LHS.get()->getType()->isBooleanType() && 10232 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10233 // Don't warn in macros or template instantiations. 10234 !Loc.isMacroID() && !inTemplateInstantiation()) { 10235 // If the RHS can be constant folded, and if it constant folds to something 10236 // that isn't 0 or 1 (which indicate a potential logical operation that 10237 // happened to fold to true/false) then warn. 10238 // Parens on the RHS are ignored. 10239 llvm::APSInt Result; 10240 if (RHS.get()->EvaluateAsInt(Result, Context)) 10241 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10242 !RHS.get()->getExprLoc().isMacroID()) || 10243 (Result != 0 && Result != 1)) { 10244 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10245 << RHS.get()->getSourceRange() 10246 << (Opc == BO_LAnd ? "&&" : "||"); 10247 // Suggest replacing the logical operator with the bitwise version 10248 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10249 << (Opc == BO_LAnd ? "&" : "|") 10250 << FixItHint::CreateReplacement(SourceRange( 10251 Loc, getLocForEndOfToken(Loc)), 10252 Opc == BO_LAnd ? "&" : "|"); 10253 if (Opc == BO_LAnd) 10254 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10255 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10256 << FixItHint::CreateRemoval( 10257 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10258 RHS.get()->getLocEnd())); 10259 } 10260 } 10261 10262 if (!Context.getLangOpts().CPlusPlus) { 10263 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10264 // not operate on the built-in scalar and vector float types. 10265 if (Context.getLangOpts().OpenCL && 10266 Context.getLangOpts().OpenCLVersion < 120) { 10267 if (LHS.get()->getType()->isFloatingType() || 10268 RHS.get()->getType()->isFloatingType()) 10269 return InvalidOperands(Loc, LHS, RHS); 10270 } 10271 10272 LHS = UsualUnaryConversions(LHS.get()); 10273 if (LHS.isInvalid()) 10274 return QualType(); 10275 10276 RHS = UsualUnaryConversions(RHS.get()); 10277 if (RHS.isInvalid()) 10278 return QualType(); 10279 10280 if (!LHS.get()->getType()->isScalarType() || 10281 !RHS.get()->getType()->isScalarType()) 10282 return InvalidOperands(Loc, LHS, RHS); 10283 10284 return Context.IntTy; 10285 } 10286 10287 // The following is safe because we only use this method for 10288 // non-overloadable operands. 10289 10290 // C++ [expr.log.and]p1 10291 // C++ [expr.log.or]p1 10292 // The operands are both contextually converted to type bool. 10293 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10294 if (LHSRes.isInvalid()) 10295 return InvalidOperands(Loc, LHS, RHS); 10296 LHS = LHSRes; 10297 10298 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10299 if (RHSRes.isInvalid()) 10300 return InvalidOperands(Loc, LHS, RHS); 10301 RHS = RHSRes; 10302 10303 // C++ [expr.log.and]p2 10304 // C++ [expr.log.or]p2 10305 // The result is a bool. 10306 return Context.BoolTy; 10307 } 10308 10309 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10310 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10311 if (!ME) return false; 10312 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10313 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10314 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10315 if (!Base) return false; 10316 return Base->getMethodDecl() != nullptr; 10317 } 10318 10319 /// Is the given expression (which must be 'const') a reference to a 10320 /// variable which was originally non-const, but which has become 10321 /// 'const' due to being captured within a block? 10322 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10323 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10324 assert(E->isLValue() && E->getType().isConstQualified()); 10325 E = E->IgnoreParens(); 10326 10327 // Must be a reference to a declaration from an enclosing scope. 10328 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10329 if (!DRE) return NCCK_None; 10330 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10331 10332 // The declaration must be a variable which is not declared 'const'. 10333 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10334 if (!var) return NCCK_None; 10335 if (var->getType().isConstQualified()) return NCCK_None; 10336 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10337 10338 // Decide whether the first capture was for a block or a lambda. 10339 DeclContext *DC = S.CurContext, *Prev = nullptr; 10340 // Decide whether the first capture was for a block or a lambda. 10341 while (DC) { 10342 // For init-capture, it is possible that the variable belongs to the 10343 // template pattern of the current context. 10344 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10345 if (var->isInitCapture() && 10346 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10347 break; 10348 if (DC == var->getDeclContext()) 10349 break; 10350 Prev = DC; 10351 DC = DC->getParent(); 10352 } 10353 // Unless we have an init-capture, we've gone one step too far. 10354 if (!var->isInitCapture()) 10355 DC = Prev; 10356 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10357 } 10358 10359 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10360 Ty = Ty.getNonReferenceType(); 10361 if (IsDereference && Ty->isPointerType()) 10362 Ty = Ty->getPointeeType(); 10363 return !Ty.isConstQualified(); 10364 } 10365 10366 // Update err_typecheck_assign_const and note_typecheck_assign_const 10367 // when this enum is changed. 10368 enum { 10369 ConstFunction, 10370 ConstVariable, 10371 ConstMember, 10372 ConstMethod, 10373 NestedConstMember, 10374 ConstUnknown, // Keep as last element 10375 }; 10376 10377 /// Emit the "read-only variable not assignable" error and print notes to give 10378 /// more information about why the variable is not assignable, such as pointing 10379 /// to the declaration of a const variable, showing that a method is const, or 10380 /// that the function is returning a const reference. 10381 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10382 SourceLocation Loc) { 10383 SourceRange ExprRange = E->getSourceRange(); 10384 10385 // Only emit one error on the first const found. All other consts will emit 10386 // a note to the error. 10387 bool DiagnosticEmitted = false; 10388 10389 // Track if the current expression is the result of a dereference, and if the 10390 // next checked expression is the result of a dereference. 10391 bool IsDereference = false; 10392 bool NextIsDereference = false; 10393 10394 // Loop to process MemberExpr chains. 10395 while (true) { 10396 IsDereference = NextIsDereference; 10397 10398 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10399 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10400 NextIsDereference = ME->isArrow(); 10401 const ValueDecl *VD = ME->getMemberDecl(); 10402 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10403 // Mutable fields can be modified even if the class is const. 10404 if (Field->isMutable()) { 10405 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10406 break; 10407 } 10408 10409 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10410 if (!DiagnosticEmitted) { 10411 S.Diag(Loc, diag::err_typecheck_assign_const) 10412 << ExprRange << ConstMember << false /*static*/ << Field 10413 << Field->getType(); 10414 DiagnosticEmitted = true; 10415 } 10416 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10417 << ConstMember << false /*static*/ << Field << Field->getType() 10418 << Field->getSourceRange(); 10419 } 10420 E = ME->getBase(); 10421 continue; 10422 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10423 if (VDecl->getType().isConstQualified()) { 10424 if (!DiagnosticEmitted) { 10425 S.Diag(Loc, diag::err_typecheck_assign_const) 10426 << ExprRange << ConstMember << true /*static*/ << VDecl 10427 << VDecl->getType(); 10428 DiagnosticEmitted = true; 10429 } 10430 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10431 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10432 << VDecl->getSourceRange(); 10433 } 10434 // Static fields do not inherit constness from parents. 10435 break; 10436 } 10437 break; 10438 } // End MemberExpr 10439 break; 10440 } 10441 10442 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10443 // Function calls 10444 const FunctionDecl *FD = CE->getDirectCallee(); 10445 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10446 if (!DiagnosticEmitted) { 10447 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10448 << ConstFunction << FD; 10449 DiagnosticEmitted = true; 10450 } 10451 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10452 diag::note_typecheck_assign_const) 10453 << ConstFunction << FD << FD->getReturnType() 10454 << FD->getReturnTypeSourceRange(); 10455 } 10456 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10457 // Point to variable declaration. 10458 if (const ValueDecl *VD = DRE->getDecl()) { 10459 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10460 if (!DiagnosticEmitted) { 10461 S.Diag(Loc, diag::err_typecheck_assign_const) 10462 << ExprRange << ConstVariable << VD << VD->getType(); 10463 DiagnosticEmitted = true; 10464 } 10465 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10466 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10467 } 10468 } 10469 } else if (isa<CXXThisExpr>(E)) { 10470 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10471 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10472 if (MD->isConst()) { 10473 if (!DiagnosticEmitted) { 10474 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10475 << ConstMethod << MD; 10476 DiagnosticEmitted = true; 10477 } 10478 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10479 << ConstMethod << MD << MD->getSourceRange(); 10480 } 10481 } 10482 } 10483 } 10484 10485 if (DiagnosticEmitted) 10486 return; 10487 10488 // Can't determine a more specific message, so display the generic error. 10489 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10490 } 10491 10492 enum OriginalExprKind { 10493 OEK_Variable, 10494 OEK_Member, 10495 OEK_LValue 10496 }; 10497 10498 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10499 const RecordType *Ty, 10500 SourceLocation Loc, SourceRange Range, 10501 OriginalExprKind OEK, 10502 bool &DiagnosticEmitted, 10503 bool IsNested = false) { 10504 // We walk the record hierarchy breadth-first to ensure that we print 10505 // diagnostics in field nesting order. 10506 // First, check every field for constness. 10507 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10508 if (Field->getType().isConstQualified()) { 10509 if (!DiagnosticEmitted) { 10510 S.Diag(Loc, diag::err_typecheck_assign_const) 10511 << Range << NestedConstMember << OEK << VD 10512 << IsNested << Field; 10513 DiagnosticEmitted = true; 10514 } 10515 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10516 << NestedConstMember << IsNested << Field 10517 << Field->getType() << Field->getSourceRange(); 10518 } 10519 } 10520 // Then, recurse. 10521 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10522 QualType FTy = Field->getType(); 10523 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10524 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10525 OEK, DiagnosticEmitted, true); 10526 } 10527 } 10528 10529 /// Emit an error for the case where a record we are trying to assign to has a 10530 /// const-qualified field somewhere in its hierarchy. 10531 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10532 SourceLocation Loc) { 10533 QualType Ty = E->getType(); 10534 assert(Ty->isRecordType() && "lvalue was not record?"); 10535 SourceRange Range = E->getSourceRange(); 10536 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10537 bool DiagEmitted = false; 10538 10539 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10540 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10541 Range, OEK_Member, DiagEmitted); 10542 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10543 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10544 Range, OEK_Variable, DiagEmitted); 10545 else 10546 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10547 Range, OEK_LValue, DiagEmitted); 10548 if (!DiagEmitted) 10549 DiagnoseConstAssignment(S, E, Loc); 10550 } 10551 10552 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10553 /// emit an error and return true. If so, return false. 10554 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10555 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10556 10557 S.CheckShadowingDeclModification(E, Loc); 10558 10559 SourceLocation OrigLoc = Loc; 10560 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10561 &Loc); 10562 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10563 IsLV = Expr::MLV_InvalidMessageExpression; 10564 if (IsLV == Expr::MLV_Valid) 10565 return false; 10566 10567 unsigned DiagID = 0; 10568 bool NeedType = false; 10569 switch (IsLV) { // C99 6.5.16p2 10570 case Expr::MLV_ConstQualified: 10571 // Use a specialized diagnostic when we're assigning to an object 10572 // from an enclosing function or block. 10573 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10574 if (NCCK == NCCK_Block) 10575 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10576 else 10577 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10578 break; 10579 } 10580 10581 // In ARC, use some specialized diagnostics for occasions where we 10582 // infer 'const'. These are always pseudo-strong variables. 10583 if (S.getLangOpts().ObjCAutoRefCount) { 10584 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10585 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10586 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10587 10588 // Use the normal diagnostic if it's pseudo-__strong but the 10589 // user actually wrote 'const'. 10590 if (var->isARCPseudoStrong() && 10591 (!var->getTypeSourceInfo() || 10592 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10593 // There are two pseudo-strong cases: 10594 // - self 10595 ObjCMethodDecl *method = S.getCurMethodDecl(); 10596 if (method && var == method->getSelfDecl()) 10597 DiagID = method->isClassMethod() 10598 ? diag::err_typecheck_arc_assign_self_class_method 10599 : diag::err_typecheck_arc_assign_self; 10600 10601 // - fast enumeration variables 10602 else 10603 DiagID = diag::err_typecheck_arr_assign_enumeration; 10604 10605 SourceRange Assign; 10606 if (Loc != OrigLoc) 10607 Assign = SourceRange(OrigLoc, OrigLoc); 10608 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10609 // We need to preserve the AST regardless, so migration tool 10610 // can do its job. 10611 return false; 10612 } 10613 } 10614 } 10615 10616 // If none of the special cases above are triggered, then this is a 10617 // simple const assignment. 10618 if (DiagID == 0) { 10619 DiagnoseConstAssignment(S, E, Loc); 10620 return true; 10621 } 10622 10623 break; 10624 case Expr::MLV_ConstAddrSpace: 10625 DiagnoseConstAssignment(S, E, Loc); 10626 return true; 10627 case Expr::MLV_ConstQualifiedField: 10628 DiagnoseRecursiveConstFields(S, E, Loc); 10629 return true; 10630 case Expr::MLV_ArrayType: 10631 case Expr::MLV_ArrayTemporary: 10632 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10633 NeedType = true; 10634 break; 10635 case Expr::MLV_NotObjectType: 10636 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10637 NeedType = true; 10638 break; 10639 case Expr::MLV_LValueCast: 10640 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10641 break; 10642 case Expr::MLV_Valid: 10643 llvm_unreachable("did not take early return for MLV_Valid"); 10644 case Expr::MLV_InvalidExpression: 10645 case Expr::MLV_MemberFunction: 10646 case Expr::MLV_ClassTemporary: 10647 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10648 break; 10649 case Expr::MLV_IncompleteType: 10650 case Expr::MLV_IncompleteVoidType: 10651 return S.RequireCompleteType(Loc, E->getType(), 10652 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10653 case Expr::MLV_DuplicateVectorComponents: 10654 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10655 break; 10656 case Expr::MLV_NoSetterProperty: 10657 llvm_unreachable("readonly properties should be processed differently"); 10658 case Expr::MLV_InvalidMessageExpression: 10659 DiagID = diag::err_readonly_message_assignment; 10660 break; 10661 case Expr::MLV_SubObjCPropertySetting: 10662 DiagID = diag::err_no_subobject_property_setting; 10663 break; 10664 } 10665 10666 SourceRange Assign; 10667 if (Loc != OrigLoc) 10668 Assign = SourceRange(OrigLoc, OrigLoc); 10669 if (NeedType) 10670 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10671 else 10672 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10673 return true; 10674 } 10675 10676 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10677 SourceLocation Loc, 10678 Sema &Sema) { 10679 // C / C++ fields 10680 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10681 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10682 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10683 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10684 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10685 } 10686 10687 // Objective-C instance variables 10688 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10689 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10690 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10691 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10692 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10693 if (RL && RR && RL->getDecl() == RR->getDecl()) 10694 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10695 } 10696 } 10697 10698 // C99 6.5.16.1 10699 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10700 SourceLocation Loc, 10701 QualType CompoundType) { 10702 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10703 10704 // Verify that LHS is a modifiable lvalue, and emit error if not. 10705 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10706 return QualType(); 10707 10708 QualType LHSType = LHSExpr->getType(); 10709 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10710 CompoundType; 10711 // OpenCL v1.2 s6.1.1.1 p2: 10712 // The half data type can only be used to declare a pointer to a buffer that 10713 // contains half values 10714 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10715 LHSType->isHalfType()) { 10716 Diag(Loc, diag::err_opencl_half_load_store) << 1 10717 << LHSType.getUnqualifiedType(); 10718 return QualType(); 10719 } 10720 10721 AssignConvertType ConvTy; 10722 if (CompoundType.isNull()) { 10723 Expr *RHSCheck = RHS.get(); 10724 10725 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10726 10727 QualType LHSTy(LHSType); 10728 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10729 if (RHS.isInvalid()) 10730 return QualType(); 10731 // Special case of NSObject attributes on c-style pointer types. 10732 if (ConvTy == IncompatiblePointer && 10733 ((Context.isObjCNSObjectType(LHSType) && 10734 RHSType->isObjCObjectPointerType()) || 10735 (Context.isObjCNSObjectType(RHSType) && 10736 LHSType->isObjCObjectPointerType()))) 10737 ConvTy = Compatible; 10738 10739 if (ConvTy == Compatible && 10740 LHSType->isObjCObjectType()) 10741 Diag(Loc, diag::err_objc_object_assignment) 10742 << LHSType; 10743 10744 // If the RHS is a unary plus or minus, check to see if they = and + are 10745 // right next to each other. If so, the user may have typo'd "x =+ 4" 10746 // instead of "x += 4". 10747 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10748 RHSCheck = ICE->getSubExpr(); 10749 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10750 if ((UO->getOpcode() == UO_Plus || 10751 UO->getOpcode() == UO_Minus) && 10752 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10753 // Only if the two operators are exactly adjacent. 10754 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10755 // And there is a space or other character before the subexpr of the 10756 // unary +/-. We don't want to warn on "x=-1". 10757 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10758 UO->getSubExpr()->getLocStart().isFileID()) { 10759 Diag(Loc, diag::warn_not_compound_assign) 10760 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10761 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10762 } 10763 } 10764 10765 if (ConvTy == Compatible) { 10766 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10767 // Warn about retain cycles where a block captures the LHS, but 10768 // not if the LHS is a simple variable into which the block is 10769 // being stored...unless that variable can be captured by reference! 10770 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10771 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10772 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10773 checkRetainCycles(LHSExpr, RHS.get()); 10774 } 10775 10776 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10777 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10778 // It is safe to assign a weak reference into a strong variable. 10779 // Although this code can still have problems: 10780 // id x = self.weakProp; 10781 // id y = self.weakProp; 10782 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10783 // paths through the function. This should be revisited if 10784 // -Wrepeated-use-of-weak is made flow-sensitive. 10785 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10786 // variable, which will be valid for the current autorelease scope. 10787 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10788 RHS.get()->getLocStart())) 10789 getCurFunction()->markSafeWeakUse(RHS.get()); 10790 10791 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10792 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10793 } 10794 } 10795 } else { 10796 // Compound assignment "x += y" 10797 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10798 } 10799 10800 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10801 RHS.get(), AA_Assigning)) 10802 return QualType(); 10803 10804 CheckForNullPointerDereference(*this, LHSExpr); 10805 10806 // C99 6.5.16p3: The type of an assignment expression is the type of the 10807 // left operand unless the left operand has qualified type, in which case 10808 // it is the unqualified version of the type of the left operand. 10809 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10810 // is converted to the type of the assignment expression (above). 10811 // C++ 5.17p1: the type of the assignment expression is that of its left 10812 // operand. 10813 return (getLangOpts().CPlusPlus 10814 ? LHSType : LHSType.getUnqualifiedType()); 10815 } 10816 10817 // Only ignore explicit casts to void. 10818 static bool IgnoreCommaOperand(const Expr *E) { 10819 E = E->IgnoreParens(); 10820 10821 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10822 if (CE->getCastKind() == CK_ToVoid) { 10823 return true; 10824 } 10825 } 10826 10827 return false; 10828 } 10829 10830 // Look for instances where it is likely the comma operator is confused with 10831 // another operator. There is a whitelist of acceptable expressions for the 10832 // left hand side of the comma operator, otherwise emit a warning. 10833 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10834 // No warnings in macros 10835 if (Loc.isMacroID()) 10836 return; 10837 10838 // Don't warn in template instantiations. 10839 if (inTemplateInstantiation()) 10840 return; 10841 10842 // Scope isn't fine-grained enough to whitelist the specific cases, so 10843 // instead, skip more than needed, then call back into here with the 10844 // CommaVisitor in SemaStmt.cpp. 10845 // The whitelisted locations are the initialization and increment portions 10846 // of a for loop. The additional checks are on the condition of 10847 // if statements, do/while loops, and for loops. 10848 const unsigned ForIncrementFlags = 10849 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10850 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10851 const unsigned ScopeFlags = getCurScope()->getFlags(); 10852 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10853 (ScopeFlags & ForInitFlags) == ForInitFlags) 10854 return; 10855 10856 // If there are multiple comma operators used together, get the RHS of the 10857 // of the comma operator as the LHS. 10858 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10859 if (BO->getOpcode() != BO_Comma) 10860 break; 10861 LHS = BO->getRHS(); 10862 } 10863 10864 // Only allow some expressions on LHS to not warn. 10865 if (IgnoreCommaOperand(LHS)) 10866 return; 10867 10868 Diag(Loc, diag::warn_comma_operator); 10869 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10870 << LHS->getSourceRange() 10871 << FixItHint::CreateInsertion(LHS->getLocStart(), 10872 LangOpts.CPlusPlus ? "static_cast<void>(" 10873 : "(void)(") 10874 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10875 ")"); 10876 } 10877 10878 // C99 6.5.17 10879 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10880 SourceLocation Loc) { 10881 LHS = S.CheckPlaceholderExpr(LHS.get()); 10882 RHS = S.CheckPlaceholderExpr(RHS.get()); 10883 if (LHS.isInvalid() || RHS.isInvalid()) 10884 return QualType(); 10885 10886 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10887 // operands, but not unary promotions. 10888 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10889 10890 // So we treat the LHS as a ignored value, and in C++ we allow the 10891 // containing site to determine what should be done with the RHS. 10892 LHS = S.IgnoredValueConversions(LHS.get()); 10893 if (LHS.isInvalid()) 10894 return QualType(); 10895 10896 S.DiagnoseUnusedExprResult(LHS.get()); 10897 10898 if (!S.getLangOpts().CPlusPlus) { 10899 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10900 if (RHS.isInvalid()) 10901 return QualType(); 10902 if (!RHS.get()->getType()->isVoidType()) 10903 S.RequireCompleteType(Loc, RHS.get()->getType(), 10904 diag::err_incomplete_type); 10905 } 10906 10907 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10908 S.DiagnoseCommaOperator(LHS.get(), Loc); 10909 10910 return RHS.get()->getType(); 10911 } 10912 10913 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10914 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10915 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10916 ExprValueKind &VK, 10917 ExprObjectKind &OK, 10918 SourceLocation OpLoc, 10919 bool IsInc, bool IsPrefix) { 10920 if (Op->isTypeDependent()) 10921 return S.Context.DependentTy; 10922 10923 QualType ResType = Op->getType(); 10924 // Atomic types can be used for increment / decrement where the non-atomic 10925 // versions can, so ignore the _Atomic() specifier for the purpose of 10926 // checking. 10927 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10928 ResType = ResAtomicType->getValueType(); 10929 10930 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10931 10932 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10933 // Decrement of bool is not allowed. 10934 if (!IsInc) { 10935 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10936 return QualType(); 10937 } 10938 // Increment of bool sets it to true, but is deprecated. 10939 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 10940 : diag::warn_increment_bool) 10941 << Op->getSourceRange(); 10942 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10943 // Error on enum increments and decrements in C++ mode 10944 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10945 return QualType(); 10946 } else if (ResType->isRealType()) { 10947 // OK! 10948 } else if (ResType->isPointerType()) { 10949 // C99 6.5.2.4p2, 6.5.6p2 10950 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10951 return QualType(); 10952 } else if (ResType->isObjCObjectPointerType()) { 10953 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10954 // Otherwise, we just need a complete type. 10955 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10956 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10957 return QualType(); 10958 } else if (ResType->isAnyComplexType()) { 10959 // C99 does not support ++/-- on complex types, we allow as an extension. 10960 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10961 << ResType << Op->getSourceRange(); 10962 } else if (ResType->isPlaceholderType()) { 10963 ExprResult PR = S.CheckPlaceholderExpr(Op); 10964 if (PR.isInvalid()) return QualType(); 10965 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10966 IsInc, IsPrefix); 10967 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10968 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10969 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10970 (ResType->getAs<VectorType>()->getVectorKind() != 10971 VectorType::AltiVecBool)) { 10972 // The z vector extensions allow ++ and -- for non-bool vectors. 10973 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10974 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10975 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10976 } else { 10977 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10978 << ResType << int(IsInc) << Op->getSourceRange(); 10979 return QualType(); 10980 } 10981 // At this point, we know we have a real, complex or pointer type. 10982 // Now make sure the operand is a modifiable lvalue. 10983 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10984 return QualType(); 10985 // In C++, a prefix increment is the same type as the operand. Otherwise 10986 // (in C or with postfix), the increment is the unqualified type of the 10987 // operand. 10988 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10989 VK = VK_LValue; 10990 OK = Op->getObjectKind(); 10991 return ResType; 10992 } else { 10993 VK = VK_RValue; 10994 return ResType.getUnqualifiedType(); 10995 } 10996 } 10997 10998 10999 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11000 /// This routine allows us to typecheck complex/recursive expressions 11001 /// where the declaration is needed for type checking. We only need to 11002 /// handle cases when the expression references a function designator 11003 /// or is an lvalue. Here are some examples: 11004 /// - &(x) => x 11005 /// - &*****f => f for f a function designator. 11006 /// - &s.xx => s 11007 /// - &s.zz[1].yy -> s, if zz is an array 11008 /// - *(x + 1) -> x, if x is an array 11009 /// - &"123"[2] -> 0 11010 /// - & __real__ x -> x 11011 static ValueDecl *getPrimaryDecl(Expr *E) { 11012 switch (E->getStmtClass()) { 11013 case Stmt::DeclRefExprClass: 11014 return cast<DeclRefExpr>(E)->getDecl(); 11015 case Stmt::MemberExprClass: 11016 // If this is an arrow operator, the address is an offset from 11017 // the base's value, so the object the base refers to is 11018 // irrelevant. 11019 if (cast<MemberExpr>(E)->isArrow()) 11020 return nullptr; 11021 // Otherwise, the expression refers to a part of the base 11022 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11023 case Stmt::ArraySubscriptExprClass: { 11024 // FIXME: This code shouldn't be necessary! We should catch the implicit 11025 // promotion of register arrays earlier. 11026 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11027 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11028 if (ICE->getSubExpr()->getType()->isArrayType()) 11029 return getPrimaryDecl(ICE->getSubExpr()); 11030 } 11031 return nullptr; 11032 } 11033 case Stmt::UnaryOperatorClass: { 11034 UnaryOperator *UO = cast<UnaryOperator>(E); 11035 11036 switch(UO->getOpcode()) { 11037 case UO_Real: 11038 case UO_Imag: 11039 case UO_Extension: 11040 return getPrimaryDecl(UO->getSubExpr()); 11041 default: 11042 return nullptr; 11043 } 11044 } 11045 case Stmt::ParenExprClass: 11046 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11047 case Stmt::ImplicitCastExprClass: 11048 // If the result of an implicit cast is an l-value, we care about 11049 // the sub-expression; otherwise, the result here doesn't matter. 11050 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11051 default: 11052 return nullptr; 11053 } 11054 } 11055 11056 namespace { 11057 enum { 11058 AO_Bit_Field = 0, 11059 AO_Vector_Element = 1, 11060 AO_Property_Expansion = 2, 11061 AO_Register_Variable = 3, 11062 AO_No_Error = 4 11063 }; 11064 } 11065 /// \brief Diagnose invalid operand for address of operations. 11066 /// 11067 /// \param Type The type of operand which cannot have its address taken. 11068 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11069 Expr *E, unsigned Type) { 11070 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11071 } 11072 11073 /// CheckAddressOfOperand - The operand of & must be either a function 11074 /// designator or an lvalue designating an object. If it is an lvalue, the 11075 /// object cannot be declared with storage class register or be a bit field. 11076 /// Note: The usual conversions are *not* applied to the operand of the & 11077 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11078 /// In C++, the operand might be an overloaded function name, in which case 11079 /// we allow the '&' but retain the overloaded-function type. 11080 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11081 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11082 if (PTy->getKind() == BuiltinType::Overload) { 11083 Expr *E = OrigOp.get()->IgnoreParens(); 11084 if (!isa<OverloadExpr>(E)) { 11085 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11086 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11087 << OrigOp.get()->getSourceRange(); 11088 return QualType(); 11089 } 11090 11091 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11092 if (isa<UnresolvedMemberExpr>(Ovl)) 11093 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11094 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11095 << OrigOp.get()->getSourceRange(); 11096 return QualType(); 11097 } 11098 11099 return Context.OverloadTy; 11100 } 11101 11102 if (PTy->getKind() == BuiltinType::UnknownAny) 11103 return Context.UnknownAnyTy; 11104 11105 if (PTy->getKind() == BuiltinType::BoundMember) { 11106 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11107 << OrigOp.get()->getSourceRange(); 11108 return QualType(); 11109 } 11110 11111 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11112 if (OrigOp.isInvalid()) return QualType(); 11113 } 11114 11115 if (OrigOp.get()->isTypeDependent()) 11116 return Context.DependentTy; 11117 11118 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11119 11120 // Make sure to ignore parentheses in subsequent checks 11121 Expr *op = OrigOp.get()->IgnoreParens(); 11122 11123 // In OpenCL captures for blocks called as lambda functions 11124 // are located in the private address space. Blocks used in 11125 // enqueue_kernel can be located in a different address space 11126 // depending on a vendor implementation. Thus preventing 11127 // taking an address of the capture to avoid invalid AS casts. 11128 if (LangOpts.OpenCL) { 11129 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11130 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11131 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11132 return QualType(); 11133 } 11134 } 11135 11136 if (getLangOpts().C99) { 11137 // Implement C99-only parts of addressof rules. 11138 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11139 if (uOp->getOpcode() == UO_Deref) 11140 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11141 // (assuming the deref expression is valid). 11142 return uOp->getSubExpr()->getType(); 11143 } 11144 // Technically, there should be a check for array subscript 11145 // expressions here, but the result of one is always an lvalue anyway. 11146 } 11147 ValueDecl *dcl = getPrimaryDecl(op); 11148 11149 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11150 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11151 op->getLocStart())) 11152 return QualType(); 11153 11154 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11155 unsigned AddressOfError = AO_No_Error; 11156 11157 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11158 bool sfinae = (bool)isSFINAEContext(); 11159 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11160 : diag::ext_typecheck_addrof_temporary) 11161 << op->getType() << op->getSourceRange(); 11162 if (sfinae) 11163 return QualType(); 11164 // Materialize the temporary as an lvalue so that we can take its address. 11165 OrigOp = op = 11166 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11167 } else if (isa<ObjCSelectorExpr>(op)) { 11168 return Context.getPointerType(op->getType()); 11169 } else if (lval == Expr::LV_MemberFunction) { 11170 // If it's an instance method, make a member pointer. 11171 // The expression must have exactly the form &A::foo. 11172 11173 // If the underlying expression isn't a decl ref, give up. 11174 if (!isa<DeclRefExpr>(op)) { 11175 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11176 << OrigOp.get()->getSourceRange(); 11177 return QualType(); 11178 } 11179 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11180 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11181 11182 // The id-expression was parenthesized. 11183 if (OrigOp.get() != DRE) { 11184 Diag(OpLoc, diag::err_parens_pointer_member_function) 11185 << OrigOp.get()->getSourceRange(); 11186 11187 // The method was named without a qualifier. 11188 } else if (!DRE->getQualifier()) { 11189 if (MD->getParent()->getName().empty()) 11190 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11191 << op->getSourceRange(); 11192 else { 11193 SmallString<32> Str; 11194 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11195 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11196 << op->getSourceRange() 11197 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11198 } 11199 } 11200 11201 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11202 if (isa<CXXDestructorDecl>(MD)) 11203 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11204 11205 QualType MPTy = Context.getMemberPointerType( 11206 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11207 // Under the MS ABI, lock down the inheritance model now. 11208 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11209 (void)isCompleteType(OpLoc, MPTy); 11210 return MPTy; 11211 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11212 // C99 6.5.3.2p1 11213 // The operand must be either an l-value or a function designator 11214 if (!op->getType()->isFunctionType()) { 11215 // Use a special diagnostic for loads from property references. 11216 if (isa<PseudoObjectExpr>(op)) { 11217 AddressOfError = AO_Property_Expansion; 11218 } else { 11219 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11220 << op->getType() << op->getSourceRange(); 11221 return QualType(); 11222 } 11223 } 11224 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11225 // The operand cannot be a bit-field 11226 AddressOfError = AO_Bit_Field; 11227 } else if (op->getObjectKind() == OK_VectorComponent) { 11228 // The operand cannot be an element of a vector 11229 AddressOfError = AO_Vector_Element; 11230 } else if (dcl) { // C99 6.5.3.2p1 11231 // We have an lvalue with a decl. Make sure the decl is not declared 11232 // with the register storage-class specifier. 11233 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11234 // in C++ it is not error to take address of a register 11235 // variable (c++03 7.1.1P3) 11236 if (vd->getStorageClass() == SC_Register && 11237 !getLangOpts().CPlusPlus) { 11238 AddressOfError = AO_Register_Variable; 11239 } 11240 } else if (isa<MSPropertyDecl>(dcl)) { 11241 AddressOfError = AO_Property_Expansion; 11242 } else if (isa<FunctionTemplateDecl>(dcl)) { 11243 return Context.OverloadTy; 11244 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11245 // Okay: we can take the address of a field. 11246 // Could be a pointer to member, though, if there is an explicit 11247 // scope qualifier for the class. 11248 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11249 DeclContext *Ctx = dcl->getDeclContext(); 11250 if (Ctx && Ctx->isRecord()) { 11251 if (dcl->getType()->isReferenceType()) { 11252 Diag(OpLoc, 11253 diag::err_cannot_form_pointer_to_member_of_reference_type) 11254 << dcl->getDeclName() << dcl->getType(); 11255 return QualType(); 11256 } 11257 11258 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11259 Ctx = Ctx->getParent(); 11260 11261 QualType MPTy = Context.getMemberPointerType( 11262 op->getType(), 11263 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11264 // Under the MS ABI, lock down the inheritance model now. 11265 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11266 (void)isCompleteType(OpLoc, MPTy); 11267 return MPTy; 11268 } 11269 } 11270 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11271 !isa<BindingDecl>(dcl)) 11272 llvm_unreachable("Unknown/unexpected decl type"); 11273 } 11274 11275 if (AddressOfError != AO_No_Error) { 11276 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11277 return QualType(); 11278 } 11279 11280 if (lval == Expr::LV_IncompleteVoidType) { 11281 // Taking the address of a void variable is technically illegal, but we 11282 // allow it in cases which are otherwise valid. 11283 // Example: "extern void x; void* y = &x;". 11284 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11285 } 11286 11287 // If the operand has type "type", the result has type "pointer to type". 11288 if (op->getType()->isObjCObjectType()) 11289 return Context.getObjCObjectPointerType(op->getType()); 11290 11291 CheckAddressOfPackedMember(op); 11292 11293 return Context.getPointerType(op->getType()); 11294 } 11295 11296 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11297 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11298 if (!DRE) 11299 return; 11300 const Decl *D = DRE->getDecl(); 11301 if (!D) 11302 return; 11303 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11304 if (!Param) 11305 return; 11306 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11307 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11308 return; 11309 if (FunctionScopeInfo *FD = S.getCurFunction()) 11310 if (!FD->ModifiedNonNullParams.count(Param)) 11311 FD->ModifiedNonNullParams.insert(Param); 11312 } 11313 11314 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11315 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11316 SourceLocation OpLoc) { 11317 if (Op->isTypeDependent()) 11318 return S.Context.DependentTy; 11319 11320 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11321 if (ConvResult.isInvalid()) 11322 return QualType(); 11323 Op = ConvResult.get(); 11324 QualType OpTy = Op->getType(); 11325 QualType Result; 11326 11327 if (isa<CXXReinterpretCastExpr>(Op)) { 11328 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11329 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11330 Op->getSourceRange()); 11331 } 11332 11333 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11334 { 11335 Result = PT->getPointeeType(); 11336 } 11337 else if (const ObjCObjectPointerType *OPT = 11338 OpTy->getAs<ObjCObjectPointerType>()) 11339 Result = OPT->getPointeeType(); 11340 else { 11341 ExprResult PR = S.CheckPlaceholderExpr(Op); 11342 if (PR.isInvalid()) return QualType(); 11343 if (PR.get() != Op) 11344 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11345 } 11346 11347 if (Result.isNull()) { 11348 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11349 << OpTy << Op->getSourceRange(); 11350 return QualType(); 11351 } 11352 11353 // Note that per both C89 and C99, indirection is always legal, even if Result 11354 // is an incomplete type or void. It would be possible to warn about 11355 // dereferencing a void pointer, but it's completely well-defined, and such a 11356 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11357 // for pointers to 'void' but is fine for any other pointer type: 11358 // 11359 // C++ [expr.unary.op]p1: 11360 // [...] the expression to which [the unary * operator] is applied shall 11361 // be a pointer to an object type, or a pointer to a function type 11362 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11363 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11364 << OpTy << Op->getSourceRange(); 11365 11366 // Dereferences are usually l-values... 11367 VK = VK_LValue; 11368 11369 // ...except that certain expressions are never l-values in C. 11370 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11371 VK = VK_RValue; 11372 11373 return Result; 11374 } 11375 11376 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11377 BinaryOperatorKind Opc; 11378 switch (Kind) { 11379 default: llvm_unreachable("Unknown binop!"); 11380 case tok::periodstar: Opc = BO_PtrMemD; break; 11381 case tok::arrowstar: Opc = BO_PtrMemI; break; 11382 case tok::star: Opc = BO_Mul; break; 11383 case tok::slash: Opc = BO_Div; break; 11384 case tok::percent: Opc = BO_Rem; break; 11385 case tok::plus: Opc = BO_Add; break; 11386 case tok::minus: Opc = BO_Sub; break; 11387 case tok::lessless: Opc = BO_Shl; break; 11388 case tok::greatergreater: Opc = BO_Shr; break; 11389 case tok::lessequal: Opc = BO_LE; break; 11390 case tok::less: Opc = BO_LT; break; 11391 case tok::greaterequal: Opc = BO_GE; break; 11392 case tok::greater: Opc = BO_GT; break; 11393 case tok::exclaimequal: Opc = BO_NE; break; 11394 case tok::equalequal: Opc = BO_EQ; break; 11395 case tok::spaceship: Opc = BO_Cmp; break; 11396 case tok::amp: Opc = BO_And; break; 11397 case tok::caret: Opc = BO_Xor; break; 11398 case tok::pipe: Opc = BO_Or; break; 11399 case tok::ampamp: Opc = BO_LAnd; break; 11400 case tok::pipepipe: Opc = BO_LOr; break; 11401 case tok::equal: Opc = BO_Assign; break; 11402 case tok::starequal: Opc = BO_MulAssign; break; 11403 case tok::slashequal: Opc = BO_DivAssign; break; 11404 case tok::percentequal: Opc = BO_RemAssign; break; 11405 case tok::plusequal: Opc = BO_AddAssign; break; 11406 case tok::minusequal: Opc = BO_SubAssign; break; 11407 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11408 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11409 case tok::ampequal: Opc = BO_AndAssign; break; 11410 case tok::caretequal: Opc = BO_XorAssign; break; 11411 case tok::pipeequal: Opc = BO_OrAssign; break; 11412 case tok::comma: Opc = BO_Comma; break; 11413 } 11414 return Opc; 11415 } 11416 11417 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11418 tok::TokenKind Kind) { 11419 UnaryOperatorKind Opc; 11420 switch (Kind) { 11421 default: llvm_unreachable("Unknown unary op!"); 11422 case tok::plusplus: Opc = UO_PreInc; break; 11423 case tok::minusminus: Opc = UO_PreDec; break; 11424 case tok::amp: Opc = UO_AddrOf; break; 11425 case tok::star: Opc = UO_Deref; break; 11426 case tok::plus: Opc = UO_Plus; break; 11427 case tok::minus: Opc = UO_Minus; break; 11428 case tok::tilde: Opc = UO_Not; break; 11429 case tok::exclaim: Opc = UO_LNot; break; 11430 case tok::kw___real: Opc = UO_Real; break; 11431 case tok::kw___imag: Opc = UO_Imag; break; 11432 case tok::kw___extension__: Opc = UO_Extension; break; 11433 } 11434 return Opc; 11435 } 11436 11437 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11438 /// This warning is only emitted for builtin assignment operations. It is also 11439 /// suppressed in the event of macro expansions. 11440 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11441 SourceLocation OpLoc) { 11442 if (S.inTemplateInstantiation()) 11443 return; 11444 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11445 return; 11446 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11447 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11448 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11449 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11450 if (!LHSDeclRef || !RHSDeclRef || 11451 LHSDeclRef->getLocation().isMacroID() || 11452 RHSDeclRef->getLocation().isMacroID()) 11453 return; 11454 const ValueDecl *LHSDecl = 11455 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11456 const ValueDecl *RHSDecl = 11457 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11458 if (LHSDecl != RHSDecl) 11459 return; 11460 if (LHSDecl->getType().isVolatileQualified()) 11461 return; 11462 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11463 if (RefTy->getPointeeType().isVolatileQualified()) 11464 return; 11465 11466 S.Diag(OpLoc, diag::warn_self_assignment) 11467 << LHSDeclRef->getType() 11468 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11469 } 11470 11471 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11472 /// is usually indicative of introspection within the Objective-C pointer. 11473 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11474 SourceLocation OpLoc) { 11475 if (!S.getLangOpts().ObjC1) 11476 return; 11477 11478 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11479 const Expr *LHS = L.get(); 11480 const Expr *RHS = R.get(); 11481 11482 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11483 ObjCPointerExpr = LHS; 11484 OtherExpr = RHS; 11485 } 11486 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11487 ObjCPointerExpr = RHS; 11488 OtherExpr = LHS; 11489 } 11490 11491 // This warning is deliberately made very specific to reduce false 11492 // positives with logic that uses '&' for hashing. This logic mainly 11493 // looks for code trying to introspect into tagged pointers, which 11494 // code should generally never do. 11495 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11496 unsigned Diag = diag::warn_objc_pointer_masking; 11497 // Determine if we are introspecting the result of performSelectorXXX. 11498 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11499 // Special case messages to -performSelector and friends, which 11500 // can return non-pointer values boxed in a pointer value. 11501 // Some clients may wish to silence warnings in this subcase. 11502 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11503 Selector S = ME->getSelector(); 11504 StringRef SelArg0 = S.getNameForSlot(0); 11505 if (SelArg0.startswith("performSelector")) 11506 Diag = diag::warn_objc_pointer_masking_performSelector; 11507 } 11508 11509 S.Diag(OpLoc, Diag) 11510 << ObjCPointerExpr->getSourceRange(); 11511 } 11512 } 11513 11514 static NamedDecl *getDeclFromExpr(Expr *E) { 11515 if (!E) 11516 return nullptr; 11517 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11518 return DRE->getDecl(); 11519 if (auto *ME = dyn_cast<MemberExpr>(E)) 11520 return ME->getMemberDecl(); 11521 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11522 return IRE->getDecl(); 11523 return nullptr; 11524 } 11525 11526 // This helper function promotes a binary operator's operands (which are of a 11527 // half vector type) to a vector of floats and then truncates the result to 11528 // a vector of either half or short. 11529 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11530 BinaryOperatorKind Opc, QualType ResultTy, 11531 ExprValueKind VK, ExprObjectKind OK, 11532 bool IsCompAssign, SourceLocation OpLoc, 11533 FPOptions FPFeatures) { 11534 auto &Context = S.getASTContext(); 11535 assert((isVector(ResultTy, Context.HalfTy) || 11536 isVector(ResultTy, Context.ShortTy)) && 11537 "Result must be a vector of half or short"); 11538 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11539 isVector(RHS.get()->getType(), Context.HalfTy) && 11540 "both operands expected to be a half vector"); 11541 11542 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11543 QualType BinOpResTy = RHS.get()->getType(); 11544 11545 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11546 // change BinOpResTy to a vector of ints. 11547 if (isVector(ResultTy, Context.ShortTy)) 11548 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11549 11550 if (IsCompAssign) 11551 return new (Context) CompoundAssignOperator( 11552 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11553 OpLoc, FPFeatures); 11554 11555 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11556 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11557 VK, OK, OpLoc, FPFeatures); 11558 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11559 } 11560 11561 static std::pair<ExprResult, ExprResult> 11562 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11563 Expr *RHSExpr) { 11564 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11565 if (!S.getLangOpts().CPlusPlus) { 11566 // C cannot handle TypoExpr nodes on either side of a binop because it 11567 // doesn't handle dependent types properly, so make sure any TypoExprs have 11568 // been dealt with before checking the operands. 11569 LHS = S.CorrectDelayedTyposInExpr(LHS); 11570 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11571 if (Opc != BO_Assign) 11572 return ExprResult(E); 11573 // Avoid correcting the RHS to the same Expr as the LHS. 11574 Decl *D = getDeclFromExpr(E); 11575 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11576 }); 11577 } 11578 return std::make_pair(LHS, RHS); 11579 } 11580 11581 /// Returns true if conversion between vectors of halfs and vectors of floats 11582 /// is needed. 11583 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11584 QualType SrcType) { 11585 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11586 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11587 isVector(SrcType, Ctx.HalfTy); 11588 } 11589 11590 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11591 /// operator @p Opc at location @c TokLoc. This routine only supports 11592 /// built-in operations; ActOnBinOp handles overloaded operators. 11593 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11594 BinaryOperatorKind Opc, 11595 Expr *LHSExpr, Expr *RHSExpr) { 11596 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11597 // The syntax only allows initializer lists on the RHS of assignment, 11598 // so we don't need to worry about accepting invalid code for 11599 // non-assignment operators. 11600 // C++11 5.17p9: 11601 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11602 // of x = {} is x = T(). 11603 InitializationKind Kind = InitializationKind::CreateDirectList( 11604 RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11605 InitializedEntity Entity = 11606 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11607 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11608 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11609 if (Init.isInvalid()) 11610 return Init; 11611 RHSExpr = Init.get(); 11612 } 11613 11614 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11615 QualType ResultTy; // Result type of the binary operator. 11616 // The following two variables are used for compound assignment operators 11617 QualType CompLHSTy; // Type of LHS after promotions for computation 11618 QualType CompResultTy; // Type of computation result 11619 ExprValueKind VK = VK_RValue; 11620 ExprObjectKind OK = OK_Ordinary; 11621 bool ConvertHalfVec = false; 11622 11623 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11624 if (!LHS.isUsable() || !RHS.isUsable()) 11625 return ExprError(); 11626 11627 if (getLangOpts().OpenCL) { 11628 QualType LHSTy = LHSExpr->getType(); 11629 QualType RHSTy = RHSExpr->getType(); 11630 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11631 // the ATOMIC_VAR_INIT macro. 11632 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11633 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11634 if (BO_Assign == Opc) 11635 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11636 else 11637 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11638 return ExprError(); 11639 } 11640 11641 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11642 // only with a builtin functions and therefore should be disallowed here. 11643 if (LHSTy->isImageType() || RHSTy->isImageType() || 11644 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11645 LHSTy->isPipeType() || RHSTy->isPipeType() || 11646 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11647 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11648 return ExprError(); 11649 } 11650 } 11651 11652 switch (Opc) { 11653 case BO_Assign: 11654 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11655 if (getLangOpts().CPlusPlus && 11656 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11657 VK = LHS.get()->getValueKind(); 11658 OK = LHS.get()->getObjectKind(); 11659 } 11660 if (!ResultTy.isNull()) { 11661 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11662 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11663 } 11664 RecordModifiableNonNullParam(*this, LHS.get()); 11665 break; 11666 case BO_PtrMemD: 11667 case BO_PtrMemI: 11668 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11669 Opc == BO_PtrMemI); 11670 break; 11671 case BO_Mul: 11672 case BO_Div: 11673 ConvertHalfVec = true; 11674 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11675 Opc == BO_Div); 11676 break; 11677 case BO_Rem: 11678 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11679 break; 11680 case BO_Add: 11681 ConvertHalfVec = true; 11682 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11683 break; 11684 case BO_Sub: 11685 ConvertHalfVec = true; 11686 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11687 break; 11688 case BO_Shl: 11689 case BO_Shr: 11690 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11691 break; 11692 case BO_LE: 11693 case BO_LT: 11694 case BO_GE: 11695 case BO_GT: 11696 ConvertHalfVec = true; 11697 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11698 break; 11699 case BO_EQ: 11700 case BO_NE: 11701 ConvertHalfVec = true; 11702 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11703 break; 11704 case BO_Cmp: 11705 // FIXME: Implement proper semantic checking of '<=>'. 11706 ConvertHalfVec = true; 11707 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11708 if (!ResultTy.isNull()) 11709 ResultTy = Context.VoidTy; 11710 break; 11711 case BO_And: 11712 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11713 LLVM_FALLTHROUGH; 11714 case BO_Xor: 11715 case BO_Or: 11716 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11717 break; 11718 case BO_LAnd: 11719 case BO_LOr: 11720 ConvertHalfVec = true; 11721 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11722 break; 11723 case BO_MulAssign: 11724 case BO_DivAssign: 11725 ConvertHalfVec = true; 11726 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11727 Opc == BO_DivAssign); 11728 CompLHSTy = CompResultTy; 11729 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11730 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11731 break; 11732 case BO_RemAssign: 11733 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11734 CompLHSTy = CompResultTy; 11735 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11736 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11737 break; 11738 case BO_AddAssign: 11739 ConvertHalfVec = true; 11740 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11741 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11742 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11743 break; 11744 case BO_SubAssign: 11745 ConvertHalfVec = true; 11746 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11747 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11748 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11749 break; 11750 case BO_ShlAssign: 11751 case BO_ShrAssign: 11752 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11753 CompLHSTy = CompResultTy; 11754 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11755 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11756 break; 11757 case BO_AndAssign: 11758 case BO_OrAssign: // fallthrough 11759 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11760 LLVM_FALLTHROUGH; 11761 case BO_XorAssign: 11762 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11763 CompLHSTy = CompResultTy; 11764 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11765 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11766 break; 11767 case BO_Comma: 11768 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11769 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11770 VK = RHS.get()->getValueKind(); 11771 OK = RHS.get()->getObjectKind(); 11772 } 11773 break; 11774 } 11775 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11776 return ExprError(); 11777 11778 // Some of the binary operations require promoting operands of half vector to 11779 // float vectors and truncating the result back to half vector. For now, we do 11780 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 11781 // arm64). 11782 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 11783 isVector(LHS.get()->getType(), Context.HalfTy) && 11784 "both sides are half vectors or neither sides are"); 11785 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 11786 LHS.get()->getType()); 11787 11788 // Check for array bounds violations for both sides of the BinaryOperator 11789 CheckArrayAccess(LHS.get()); 11790 CheckArrayAccess(RHS.get()); 11791 11792 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11793 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11794 &Context.Idents.get("object_setClass"), 11795 SourceLocation(), LookupOrdinaryName); 11796 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11797 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11798 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11799 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11800 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11801 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11802 } 11803 else 11804 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11805 } 11806 else if (const ObjCIvarRefExpr *OIRE = 11807 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11808 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11809 11810 // Opc is not a compound assignment if CompResultTy is null. 11811 if (CompResultTy.isNull()) { 11812 if (ConvertHalfVec) 11813 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 11814 OpLoc, FPFeatures); 11815 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11816 OK, OpLoc, FPFeatures); 11817 } 11818 11819 // Handle compound assignments. 11820 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11821 OK_ObjCProperty) { 11822 VK = VK_LValue; 11823 OK = LHS.get()->getObjectKind(); 11824 } 11825 11826 if (ConvertHalfVec) 11827 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 11828 OpLoc, FPFeatures); 11829 11830 return new (Context) CompoundAssignOperator( 11831 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11832 OpLoc, FPFeatures); 11833 } 11834 11835 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11836 /// operators are mixed in a way that suggests that the programmer forgot that 11837 /// comparison operators have higher precedence. The most typical example of 11838 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11839 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11840 SourceLocation OpLoc, Expr *LHSExpr, 11841 Expr *RHSExpr) { 11842 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11843 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11844 11845 // Check that one of the sides is a comparison operator and the other isn't. 11846 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11847 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11848 if (isLeftComp == isRightComp) 11849 return; 11850 11851 // Bitwise operations are sometimes used as eager logical ops. 11852 // Don't diagnose this. 11853 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11854 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11855 if (isLeftBitwise || isRightBitwise) 11856 return; 11857 11858 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11859 OpLoc) 11860 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11861 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11862 SourceRange ParensRange = isLeftComp ? 11863 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11864 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11865 11866 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11867 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11868 SuggestParentheses(Self, OpLoc, 11869 Self.PDiag(diag::note_precedence_silence) << OpStr, 11870 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11871 SuggestParentheses(Self, OpLoc, 11872 Self.PDiag(diag::note_precedence_bitwise_first) 11873 << BinaryOperator::getOpcodeStr(Opc), 11874 ParensRange); 11875 } 11876 11877 /// \brief It accepts a '&&' expr that is inside a '||' one. 11878 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11879 /// in parentheses. 11880 static void 11881 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11882 BinaryOperator *Bop) { 11883 assert(Bop->getOpcode() == BO_LAnd); 11884 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11885 << Bop->getSourceRange() << OpLoc; 11886 SuggestParentheses(Self, Bop->getOperatorLoc(), 11887 Self.PDiag(diag::note_precedence_silence) 11888 << Bop->getOpcodeStr(), 11889 Bop->getSourceRange()); 11890 } 11891 11892 /// \brief Returns true if the given expression can be evaluated as a constant 11893 /// 'true'. 11894 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11895 bool Res; 11896 return !E->isValueDependent() && 11897 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11898 } 11899 11900 /// \brief Returns true if the given expression can be evaluated as a constant 11901 /// 'false'. 11902 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11903 bool Res; 11904 return !E->isValueDependent() && 11905 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11906 } 11907 11908 /// \brief Look for '&&' in the left hand of a '||' expr. 11909 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11910 Expr *LHSExpr, Expr *RHSExpr) { 11911 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11912 if (Bop->getOpcode() == BO_LAnd) { 11913 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11914 if (EvaluatesAsFalse(S, RHSExpr)) 11915 return; 11916 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11917 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11918 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11919 } else if (Bop->getOpcode() == BO_LOr) { 11920 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11921 // If it's "a || b && 1 || c" we didn't warn earlier for 11922 // "a || b && 1", but warn now. 11923 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11924 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11925 } 11926 } 11927 } 11928 } 11929 11930 /// \brief Look for '&&' in the right hand of a '||' expr. 11931 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11932 Expr *LHSExpr, Expr *RHSExpr) { 11933 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11934 if (Bop->getOpcode() == BO_LAnd) { 11935 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11936 if (EvaluatesAsFalse(S, LHSExpr)) 11937 return; 11938 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11939 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11940 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11941 } 11942 } 11943 } 11944 11945 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11946 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11947 /// the '&' expression in parentheses. 11948 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11949 SourceLocation OpLoc, Expr *SubExpr) { 11950 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11951 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11952 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11953 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11954 << Bop->getSourceRange() << OpLoc; 11955 SuggestParentheses(S, Bop->getOperatorLoc(), 11956 S.PDiag(diag::note_precedence_silence) 11957 << Bop->getOpcodeStr(), 11958 Bop->getSourceRange()); 11959 } 11960 } 11961 } 11962 11963 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11964 Expr *SubExpr, StringRef Shift) { 11965 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11966 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11967 StringRef Op = Bop->getOpcodeStr(); 11968 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11969 << Bop->getSourceRange() << OpLoc << Shift << Op; 11970 SuggestParentheses(S, Bop->getOperatorLoc(), 11971 S.PDiag(diag::note_precedence_silence) << Op, 11972 Bop->getSourceRange()); 11973 } 11974 } 11975 } 11976 11977 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11978 Expr *LHSExpr, Expr *RHSExpr) { 11979 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11980 if (!OCE) 11981 return; 11982 11983 FunctionDecl *FD = OCE->getDirectCallee(); 11984 if (!FD || !FD->isOverloadedOperator()) 11985 return; 11986 11987 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11988 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11989 return; 11990 11991 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11992 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11993 << (Kind == OO_LessLess); 11994 SuggestParentheses(S, OCE->getOperatorLoc(), 11995 S.PDiag(diag::note_precedence_silence) 11996 << (Kind == OO_LessLess ? "<<" : ">>"), 11997 OCE->getSourceRange()); 11998 SuggestParentheses(S, OpLoc, 11999 S.PDiag(diag::note_evaluate_comparison_first), 12000 SourceRange(OCE->getArg(1)->getLocStart(), 12001 RHSExpr->getLocEnd())); 12002 } 12003 12004 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12005 /// precedence. 12006 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12007 SourceLocation OpLoc, Expr *LHSExpr, 12008 Expr *RHSExpr){ 12009 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12010 if (BinaryOperator::isBitwiseOp(Opc)) 12011 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12012 12013 // Diagnose "arg1 & arg2 | arg3" 12014 if ((Opc == BO_Or || Opc == BO_Xor) && 12015 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12016 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12017 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12018 } 12019 12020 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12021 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12022 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12023 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12024 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12025 } 12026 12027 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12028 || Opc == BO_Shr) { 12029 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12030 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12031 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12032 } 12033 12034 // Warn on overloaded shift operators and comparisons, such as: 12035 // cout << 5 == 4; 12036 if (BinaryOperator::isComparisonOp(Opc)) 12037 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12038 } 12039 12040 // Binary Operators. 'Tok' is the token for the operator. 12041 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12042 tok::TokenKind Kind, 12043 Expr *LHSExpr, Expr *RHSExpr) { 12044 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12045 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12046 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12047 12048 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12049 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12050 12051 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12052 } 12053 12054 /// Build an overloaded binary operator expression in the given scope. 12055 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12056 BinaryOperatorKind Opc, 12057 Expr *LHS, Expr *RHS) { 12058 // Find all of the overloaded operators visible from this 12059 // point. We perform both an operator-name lookup from the local 12060 // scope and an argument-dependent lookup based on the types of 12061 // the arguments. 12062 UnresolvedSet<16> Functions; 12063 OverloadedOperatorKind OverOp 12064 = BinaryOperator::getOverloadedOperator(Opc); 12065 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12066 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12067 RHS->getType(), Functions); 12068 12069 // Build the (potentially-overloaded, potentially-dependent) 12070 // binary operation. 12071 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12072 } 12073 12074 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12075 BinaryOperatorKind Opc, 12076 Expr *LHSExpr, Expr *RHSExpr) { 12077 ExprResult LHS, RHS; 12078 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12079 if (!LHS.isUsable() || !RHS.isUsable()) 12080 return ExprError(); 12081 LHSExpr = LHS.get(); 12082 RHSExpr = RHS.get(); 12083 12084 // We want to end up calling one of checkPseudoObjectAssignment 12085 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12086 // both expressions are overloadable or either is type-dependent), 12087 // or CreateBuiltinBinOp (in any other case). We also want to get 12088 // any placeholder types out of the way. 12089 12090 // Handle pseudo-objects in the LHS. 12091 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12092 // Assignments with a pseudo-object l-value need special analysis. 12093 if (pty->getKind() == BuiltinType::PseudoObject && 12094 BinaryOperator::isAssignmentOp(Opc)) 12095 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12096 12097 // Don't resolve overloads if the other type is overloadable. 12098 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12099 // We can't actually test that if we still have a placeholder, 12100 // though. Fortunately, none of the exceptions we see in that 12101 // code below are valid when the LHS is an overload set. Note 12102 // that an overload set can be dependently-typed, but it never 12103 // instantiates to having an overloadable type. 12104 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12105 if (resolvedRHS.isInvalid()) return ExprError(); 12106 RHSExpr = resolvedRHS.get(); 12107 12108 if (RHSExpr->isTypeDependent() || 12109 RHSExpr->getType()->isOverloadableType()) 12110 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12111 } 12112 12113 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12114 // template, diagnose the missing 'template' keyword instead of diagnosing 12115 // an invalid use of a bound member function. 12116 // 12117 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12118 // to C++1z [over.over]/1.4, but we already checked for that case above. 12119 if (Opc == BO_LT && inTemplateInstantiation() && 12120 (pty->getKind() == BuiltinType::BoundMember || 12121 pty->getKind() == BuiltinType::Overload)) { 12122 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12123 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12124 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12125 return isa<FunctionTemplateDecl>(ND); 12126 })) { 12127 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12128 : OE->getNameLoc(), 12129 diag::err_template_kw_missing) 12130 << OE->getName().getAsString() << ""; 12131 return ExprError(); 12132 } 12133 } 12134 12135 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12136 if (LHS.isInvalid()) return ExprError(); 12137 LHSExpr = LHS.get(); 12138 } 12139 12140 // Handle pseudo-objects in the RHS. 12141 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12142 // An overload in the RHS can potentially be resolved by the type 12143 // being assigned to. 12144 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12145 if (getLangOpts().CPlusPlus && 12146 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12147 LHSExpr->getType()->isOverloadableType())) 12148 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12149 12150 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12151 } 12152 12153 // Don't resolve overloads if the other type is overloadable. 12154 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12155 LHSExpr->getType()->isOverloadableType()) 12156 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12157 12158 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12159 if (!resolvedRHS.isUsable()) return ExprError(); 12160 RHSExpr = resolvedRHS.get(); 12161 } 12162 12163 if (getLangOpts().CPlusPlus) { 12164 // If either expression is type-dependent, always build an 12165 // overloaded op. 12166 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12167 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12168 12169 // Otherwise, build an overloaded op if either expression has an 12170 // overloadable type. 12171 if (LHSExpr->getType()->isOverloadableType() || 12172 RHSExpr->getType()->isOverloadableType()) 12173 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12174 } 12175 12176 // Build a built-in binary operation. 12177 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12178 } 12179 12180 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12181 if (T.isNull() || T->isDependentType()) 12182 return false; 12183 12184 if (!T->isPromotableIntegerType()) 12185 return true; 12186 12187 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12188 } 12189 12190 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12191 UnaryOperatorKind Opc, 12192 Expr *InputExpr) { 12193 ExprResult Input = InputExpr; 12194 ExprValueKind VK = VK_RValue; 12195 ExprObjectKind OK = OK_Ordinary; 12196 QualType resultType; 12197 bool CanOverflow = false; 12198 12199 bool ConvertHalfVec = false; 12200 if (getLangOpts().OpenCL) { 12201 QualType Ty = InputExpr->getType(); 12202 // The only legal unary operation for atomics is '&'. 12203 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12204 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12205 // only with a builtin functions and therefore should be disallowed here. 12206 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12207 || Ty->isBlockPointerType())) { 12208 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12209 << InputExpr->getType() 12210 << Input.get()->getSourceRange()); 12211 } 12212 } 12213 switch (Opc) { 12214 case UO_PreInc: 12215 case UO_PreDec: 12216 case UO_PostInc: 12217 case UO_PostDec: 12218 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12219 OpLoc, 12220 Opc == UO_PreInc || 12221 Opc == UO_PostInc, 12222 Opc == UO_PreInc || 12223 Opc == UO_PreDec); 12224 CanOverflow = isOverflowingIntegerType(Context, resultType); 12225 break; 12226 case UO_AddrOf: 12227 resultType = CheckAddressOfOperand(Input, OpLoc); 12228 RecordModifiableNonNullParam(*this, InputExpr); 12229 break; 12230 case UO_Deref: { 12231 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12232 if (Input.isInvalid()) return ExprError(); 12233 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12234 break; 12235 } 12236 case UO_Plus: 12237 case UO_Minus: 12238 CanOverflow = Opc == UO_Minus && 12239 isOverflowingIntegerType(Context, Input.get()->getType()); 12240 Input = UsualUnaryConversions(Input.get()); 12241 if (Input.isInvalid()) return ExprError(); 12242 // Unary plus and minus require promoting an operand of half vector to a 12243 // float vector and truncating the result back to a half vector. For now, we 12244 // do this only when HalfArgsAndReturns is set (that is, when the target is 12245 // arm or arm64). 12246 ConvertHalfVec = 12247 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12248 12249 // If the operand is a half vector, promote it to a float vector. 12250 if (ConvertHalfVec) 12251 Input = convertVector(Input.get(), Context.FloatTy, *this); 12252 resultType = Input.get()->getType(); 12253 if (resultType->isDependentType()) 12254 break; 12255 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12256 break; 12257 else if (resultType->isVectorType() && 12258 // The z vector extensions don't allow + or - with bool vectors. 12259 (!Context.getLangOpts().ZVector || 12260 resultType->getAs<VectorType>()->getVectorKind() != 12261 VectorType::AltiVecBool)) 12262 break; 12263 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12264 Opc == UO_Plus && 12265 resultType->isPointerType()) 12266 break; 12267 12268 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12269 << resultType << Input.get()->getSourceRange()); 12270 12271 case UO_Not: // bitwise complement 12272 Input = UsualUnaryConversions(Input.get()); 12273 if (Input.isInvalid()) 12274 return ExprError(); 12275 resultType = Input.get()->getType(); 12276 12277 if (resultType->isDependentType()) 12278 break; 12279 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12280 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12281 // C99 does not support '~' for complex conjugation. 12282 Diag(OpLoc, diag::ext_integer_complement_complex) 12283 << resultType << Input.get()->getSourceRange(); 12284 else if (resultType->hasIntegerRepresentation()) 12285 break; 12286 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12287 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12288 // on vector float types. 12289 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12290 if (!T->isIntegerType()) 12291 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12292 << resultType << Input.get()->getSourceRange()); 12293 } else { 12294 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12295 << resultType << Input.get()->getSourceRange()); 12296 } 12297 break; 12298 12299 case UO_LNot: // logical negation 12300 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12301 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12302 if (Input.isInvalid()) return ExprError(); 12303 resultType = Input.get()->getType(); 12304 12305 // Though we still have to promote half FP to float... 12306 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12307 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12308 resultType = Context.FloatTy; 12309 } 12310 12311 if (resultType->isDependentType()) 12312 break; 12313 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12314 // C99 6.5.3.3p1: ok, fallthrough; 12315 if (Context.getLangOpts().CPlusPlus) { 12316 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12317 // operand contextually converted to bool. 12318 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12319 ScalarTypeToBooleanCastKind(resultType)); 12320 } else if (Context.getLangOpts().OpenCL && 12321 Context.getLangOpts().OpenCLVersion < 120) { 12322 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12323 // operate on scalar float types. 12324 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12325 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12326 << resultType << Input.get()->getSourceRange()); 12327 } 12328 } else if (resultType->isExtVectorType()) { 12329 if (Context.getLangOpts().OpenCL && 12330 Context.getLangOpts().OpenCLVersion < 120) { 12331 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12332 // operate on vector float types. 12333 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12334 if (!T->isIntegerType()) 12335 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12336 << resultType << Input.get()->getSourceRange()); 12337 } 12338 // Vector logical not returns the signed variant of the operand type. 12339 resultType = GetSignedVectorType(resultType); 12340 break; 12341 } else { 12342 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12343 // type in C++. We should allow that here too. 12344 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12345 << resultType << Input.get()->getSourceRange()); 12346 } 12347 12348 // LNot always has type int. C99 6.5.3.3p5. 12349 // In C++, it's bool. C++ 5.3.1p8 12350 resultType = Context.getLogicalOperationType(); 12351 break; 12352 case UO_Real: 12353 case UO_Imag: 12354 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12355 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12356 // complex l-values to ordinary l-values and all other values to r-values. 12357 if (Input.isInvalid()) return ExprError(); 12358 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12359 if (Input.get()->getValueKind() != VK_RValue && 12360 Input.get()->getObjectKind() == OK_Ordinary) 12361 VK = Input.get()->getValueKind(); 12362 } else if (!getLangOpts().CPlusPlus) { 12363 // In C, a volatile scalar is read by __imag. In C++, it is not. 12364 Input = DefaultLvalueConversion(Input.get()); 12365 } 12366 break; 12367 case UO_Extension: 12368 resultType = Input.get()->getType(); 12369 VK = Input.get()->getValueKind(); 12370 OK = Input.get()->getObjectKind(); 12371 break; 12372 case UO_Coawait: 12373 // It's unnessesary to represent the pass-through operator co_await in the 12374 // AST; just return the input expression instead. 12375 assert(!Input.get()->getType()->isDependentType() && 12376 "the co_await expression must be non-dependant before " 12377 "building operator co_await"); 12378 return Input; 12379 } 12380 if (resultType.isNull() || Input.isInvalid()) 12381 return ExprError(); 12382 12383 // Check for array bounds violations in the operand of the UnaryOperator, 12384 // except for the '*' and '&' operators that have to be handled specially 12385 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12386 // that are explicitly defined as valid by the standard). 12387 if (Opc != UO_AddrOf && Opc != UO_Deref) 12388 CheckArrayAccess(Input.get()); 12389 12390 auto *UO = new (Context) 12391 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12392 // Convert the result back to a half vector. 12393 if (ConvertHalfVec) 12394 return convertVector(UO, Context.HalfTy, *this); 12395 return UO; 12396 } 12397 12398 /// \brief Determine whether the given expression is a qualified member 12399 /// access expression, of a form that could be turned into a pointer to member 12400 /// with the address-of operator. 12401 static bool isQualifiedMemberAccess(Expr *E) { 12402 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12403 if (!DRE->getQualifier()) 12404 return false; 12405 12406 ValueDecl *VD = DRE->getDecl(); 12407 if (!VD->isCXXClassMember()) 12408 return false; 12409 12410 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12411 return true; 12412 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12413 return Method->isInstance(); 12414 12415 return false; 12416 } 12417 12418 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12419 if (!ULE->getQualifier()) 12420 return false; 12421 12422 for (NamedDecl *D : ULE->decls()) { 12423 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12424 if (Method->isInstance()) 12425 return true; 12426 } else { 12427 // Overload set does not contain methods. 12428 break; 12429 } 12430 } 12431 12432 return false; 12433 } 12434 12435 return false; 12436 } 12437 12438 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12439 UnaryOperatorKind Opc, Expr *Input) { 12440 // First things first: handle placeholders so that the 12441 // overloaded-operator check considers the right type. 12442 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12443 // Increment and decrement of pseudo-object references. 12444 if (pty->getKind() == BuiltinType::PseudoObject && 12445 UnaryOperator::isIncrementDecrementOp(Opc)) 12446 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12447 12448 // extension is always a builtin operator. 12449 if (Opc == UO_Extension) 12450 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12451 12452 // & gets special logic for several kinds of placeholder. 12453 // The builtin code knows what to do. 12454 if (Opc == UO_AddrOf && 12455 (pty->getKind() == BuiltinType::Overload || 12456 pty->getKind() == BuiltinType::UnknownAny || 12457 pty->getKind() == BuiltinType::BoundMember)) 12458 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12459 12460 // Anything else needs to be handled now. 12461 ExprResult Result = CheckPlaceholderExpr(Input); 12462 if (Result.isInvalid()) return ExprError(); 12463 Input = Result.get(); 12464 } 12465 12466 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12467 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12468 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12469 // Find all of the overloaded operators visible from this 12470 // point. We perform both an operator-name lookup from the local 12471 // scope and an argument-dependent lookup based on the types of 12472 // the arguments. 12473 UnresolvedSet<16> Functions; 12474 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12475 if (S && OverOp != OO_None) 12476 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12477 Functions); 12478 12479 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12480 } 12481 12482 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12483 } 12484 12485 // Unary Operators. 'Tok' is the token for the operator. 12486 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12487 tok::TokenKind Op, Expr *Input) { 12488 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12489 } 12490 12491 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12492 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12493 LabelDecl *TheDecl) { 12494 TheDecl->markUsed(Context); 12495 // Create the AST node. The address of a label always has type 'void*'. 12496 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12497 Context.getPointerType(Context.VoidTy)); 12498 } 12499 12500 /// Given the last statement in a statement-expression, check whether 12501 /// the result is a producing expression (like a call to an 12502 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12503 /// release out of the full-expression. Otherwise, return null. 12504 /// Cannot fail. 12505 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12506 // Should always be wrapped with one of these. 12507 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12508 if (!cleanups) return nullptr; 12509 12510 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12511 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12512 return nullptr; 12513 12514 // Splice out the cast. This shouldn't modify any interesting 12515 // features of the statement. 12516 Expr *producer = cast->getSubExpr(); 12517 assert(producer->getType() == cast->getType()); 12518 assert(producer->getValueKind() == cast->getValueKind()); 12519 cleanups->setSubExpr(producer); 12520 return cleanups; 12521 } 12522 12523 void Sema::ActOnStartStmtExpr() { 12524 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12525 } 12526 12527 void Sema::ActOnStmtExprError() { 12528 // Note that function is also called by TreeTransform when leaving a 12529 // StmtExpr scope without rebuilding anything. 12530 12531 DiscardCleanupsInEvaluationContext(); 12532 PopExpressionEvaluationContext(); 12533 } 12534 12535 ExprResult 12536 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12537 SourceLocation RPLoc) { // "({..})" 12538 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12539 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12540 12541 if (hasAnyUnrecoverableErrorsInThisFunction()) 12542 DiscardCleanupsInEvaluationContext(); 12543 assert(!Cleanup.exprNeedsCleanups() && 12544 "cleanups within StmtExpr not correctly bound!"); 12545 PopExpressionEvaluationContext(); 12546 12547 // FIXME: there are a variety of strange constraints to enforce here, for 12548 // example, it is not possible to goto into a stmt expression apparently. 12549 // More semantic analysis is needed. 12550 12551 // If there are sub-stmts in the compound stmt, take the type of the last one 12552 // as the type of the stmtexpr. 12553 QualType Ty = Context.VoidTy; 12554 bool StmtExprMayBindToTemp = false; 12555 if (!Compound->body_empty()) { 12556 Stmt *LastStmt = Compound->body_back(); 12557 LabelStmt *LastLabelStmt = nullptr; 12558 // If LastStmt is a label, skip down through into the body. 12559 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12560 LastLabelStmt = Label; 12561 LastStmt = Label->getSubStmt(); 12562 } 12563 12564 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12565 // Do function/array conversion on the last expression, but not 12566 // lvalue-to-rvalue. However, initialize an unqualified type. 12567 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12568 if (LastExpr.isInvalid()) 12569 return ExprError(); 12570 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12571 12572 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12573 // In ARC, if the final expression ends in a consume, splice 12574 // the consume out and bind it later. In the alternate case 12575 // (when dealing with a retainable type), the result 12576 // initialization will create a produce. In both cases the 12577 // result will be +1, and we'll need to balance that out with 12578 // a bind. 12579 if (Expr *rebuiltLastStmt 12580 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12581 LastExpr = rebuiltLastStmt; 12582 } else { 12583 LastExpr = PerformCopyInitialization( 12584 InitializedEntity::InitializeResult(LPLoc, 12585 Ty, 12586 false), 12587 SourceLocation(), 12588 LastExpr); 12589 } 12590 12591 if (LastExpr.isInvalid()) 12592 return ExprError(); 12593 if (LastExpr.get() != nullptr) { 12594 if (!LastLabelStmt) 12595 Compound->setLastStmt(LastExpr.get()); 12596 else 12597 LastLabelStmt->setSubStmt(LastExpr.get()); 12598 StmtExprMayBindToTemp = true; 12599 } 12600 } 12601 } 12602 } 12603 12604 // FIXME: Check that expression type is complete/non-abstract; statement 12605 // expressions are not lvalues. 12606 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12607 if (StmtExprMayBindToTemp) 12608 return MaybeBindToTemporary(ResStmtExpr); 12609 return ResStmtExpr; 12610 } 12611 12612 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12613 TypeSourceInfo *TInfo, 12614 ArrayRef<OffsetOfComponent> Components, 12615 SourceLocation RParenLoc) { 12616 QualType ArgTy = TInfo->getType(); 12617 bool Dependent = ArgTy->isDependentType(); 12618 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12619 12620 // We must have at least one component that refers to the type, and the first 12621 // one is known to be a field designator. Verify that the ArgTy represents 12622 // a struct/union/class. 12623 if (!Dependent && !ArgTy->isRecordType()) 12624 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12625 << ArgTy << TypeRange); 12626 12627 // Type must be complete per C99 7.17p3 because a declaring a variable 12628 // with an incomplete type would be ill-formed. 12629 if (!Dependent 12630 && RequireCompleteType(BuiltinLoc, ArgTy, 12631 diag::err_offsetof_incomplete_type, TypeRange)) 12632 return ExprError(); 12633 12634 bool DidWarnAboutNonPOD = false; 12635 QualType CurrentType = ArgTy; 12636 SmallVector<OffsetOfNode, 4> Comps; 12637 SmallVector<Expr*, 4> Exprs; 12638 for (const OffsetOfComponent &OC : Components) { 12639 if (OC.isBrackets) { 12640 // Offset of an array sub-field. TODO: Should we allow vector elements? 12641 if (!CurrentType->isDependentType()) { 12642 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12643 if(!AT) 12644 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12645 << CurrentType); 12646 CurrentType = AT->getElementType(); 12647 } else 12648 CurrentType = Context.DependentTy; 12649 12650 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12651 if (IdxRval.isInvalid()) 12652 return ExprError(); 12653 Expr *Idx = IdxRval.get(); 12654 12655 // The expression must be an integral expression. 12656 // FIXME: An integral constant expression? 12657 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12658 !Idx->getType()->isIntegerType()) 12659 return ExprError(Diag(Idx->getLocStart(), 12660 diag::err_typecheck_subscript_not_integer) 12661 << Idx->getSourceRange()); 12662 12663 // Record this array index. 12664 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12665 Exprs.push_back(Idx); 12666 continue; 12667 } 12668 12669 // Offset of a field. 12670 if (CurrentType->isDependentType()) { 12671 // We have the offset of a field, but we can't look into the dependent 12672 // type. Just record the identifier of the field. 12673 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12674 CurrentType = Context.DependentTy; 12675 continue; 12676 } 12677 12678 // We need to have a complete type to look into. 12679 if (RequireCompleteType(OC.LocStart, CurrentType, 12680 diag::err_offsetof_incomplete_type)) 12681 return ExprError(); 12682 12683 // Look for the designated field. 12684 const RecordType *RC = CurrentType->getAs<RecordType>(); 12685 if (!RC) 12686 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12687 << CurrentType); 12688 RecordDecl *RD = RC->getDecl(); 12689 12690 // C++ [lib.support.types]p5: 12691 // The macro offsetof accepts a restricted set of type arguments in this 12692 // International Standard. type shall be a POD structure or a POD union 12693 // (clause 9). 12694 // C++11 [support.types]p4: 12695 // If type is not a standard-layout class (Clause 9), the results are 12696 // undefined. 12697 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12698 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12699 unsigned DiagID = 12700 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12701 : diag::ext_offsetof_non_pod_type; 12702 12703 if (!IsSafe && !DidWarnAboutNonPOD && 12704 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12705 PDiag(DiagID) 12706 << SourceRange(Components[0].LocStart, OC.LocEnd) 12707 << CurrentType)) 12708 DidWarnAboutNonPOD = true; 12709 } 12710 12711 // Look for the field. 12712 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12713 LookupQualifiedName(R, RD); 12714 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12715 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12716 if (!MemberDecl) { 12717 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12718 MemberDecl = IndirectMemberDecl->getAnonField(); 12719 } 12720 12721 if (!MemberDecl) 12722 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12723 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12724 OC.LocEnd)); 12725 12726 // C99 7.17p3: 12727 // (If the specified member is a bit-field, the behavior is undefined.) 12728 // 12729 // We diagnose this as an error. 12730 if (MemberDecl->isBitField()) { 12731 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12732 << MemberDecl->getDeclName() 12733 << SourceRange(BuiltinLoc, RParenLoc); 12734 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12735 return ExprError(); 12736 } 12737 12738 RecordDecl *Parent = MemberDecl->getParent(); 12739 if (IndirectMemberDecl) 12740 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12741 12742 // If the member was found in a base class, introduce OffsetOfNodes for 12743 // the base class indirections. 12744 CXXBasePaths Paths; 12745 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12746 Paths)) { 12747 if (Paths.getDetectedVirtual()) { 12748 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12749 << MemberDecl->getDeclName() 12750 << SourceRange(BuiltinLoc, RParenLoc); 12751 return ExprError(); 12752 } 12753 12754 CXXBasePath &Path = Paths.front(); 12755 for (const CXXBasePathElement &B : Path) 12756 Comps.push_back(OffsetOfNode(B.Base)); 12757 } 12758 12759 if (IndirectMemberDecl) { 12760 for (auto *FI : IndirectMemberDecl->chain()) { 12761 assert(isa<FieldDecl>(FI)); 12762 Comps.push_back(OffsetOfNode(OC.LocStart, 12763 cast<FieldDecl>(FI), OC.LocEnd)); 12764 } 12765 } else 12766 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12767 12768 CurrentType = MemberDecl->getType().getNonReferenceType(); 12769 } 12770 12771 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12772 Comps, Exprs, RParenLoc); 12773 } 12774 12775 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12776 SourceLocation BuiltinLoc, 12777 SourceLocation TypeLoc, 12778 ParsedType ParsedArgTy, 12779 ArrayRef<OffsetOfComponent> Components, 12780 SourceLocation RParenLoc) { 12781 12782 TypeSourceInfo *ArgTInfo; 12783 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12784 if (ArgTy.isNull()) 12785 return ExprError(); 12786 12787 if (!ArgTInfo) 12788 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12789 12790 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12791 } 12792 12793 12794 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12795 Expr *CondExpr, 12796 Expr *LHSExpr, Expr *RHSExpr, 12797 SourceLocation RPLoc) { 12798 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12799 12800 ExprValueKind VK = VK_RValue; 12801 ExprObjectKind OK = OK_Ordinary; 12802 QualType resType; 12803 bool ValueDependent = false; 12804 bool CondIsTrue = false; 12805 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12806 resType = Context.DependentTy; 12807 ValueDependent = true; 12808 } else { 12809 // The conditional expression is required to be a constant expression. 12810 llvm::APSInt condEval(32); 12811 ExprResult CondICE 12812 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12813 diag::err_typecheck_choose_expr_requires_constant, false); 12814 if (CondICE.isInvalid()) 12815 return ExprError(); 12816 CondExpr = CondICE.get(); 12817 CondIsTrue = condEval.getZExtValue(); 12818 12819 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12820 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12821 12822 resType = ActiveExpr->getType(); 12823 ValueDependent = ActiveExpr->isValueDependent(); 12824 VK = ActiveExpr->getValueKind(); 12825 OK = ActiveExpr->getObjectKind(); 12826 } 12827 12828 return new (Context) 12829 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12830 CondIsTrue, resType->isDependentType(), ValueDependent); 12831 } 12832 12833 //===----------------------------------------------------------------------===// 12834 // Clang Extensions. 12835 //===----------------------------------------------------------------------===// 12836 12837 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12838 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12839 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12840 12841 if (LangOpts.CPlusPlus) { 12842 Decl *ManglingContextDecl; 12843 if (MangleNumberingContext *MCtx = 12844 getCurrentMangleNumberContext(Block->getDeclContext(), 12845 ManglingContextDecl)) { 12846 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12847 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12848 } 12849 } 12850 12851 PushBlockScope(CurScope, Block); 12852 CurContext->addDecl(Block); 12853 if (CurScope) 12854 PushDeclContext(CurScope, Block); 12855 else 12856 CurContext = Block; 12857 12858 getCurBlock()->HasImplicitReturnType = true; 12859 12860 // Enter a new evaluation context to insulate the block from any 12861 // cleanups from the enclosing full-expression. 12862 PushExpressionEvaluationContext( 12863 ExpressionEvaluationContext::PotentiallyEvaluated); 12864 } 12865 12866 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12867 Scope *CurScope) { 12868 assert(ParamInfo.getIdentifier() == nullptr && 12869 "block-id should have no identifier!"); 12870 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 12871 BlockScopeInfo *CurBlock = getCurBlock(); 12872 12873 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12874 QualType T = Sig->getType(); 12875 12876 // FIXME: We should allow unexpanded parameter packs here, but that would, 12877 // in turn, make the block expression contain unexpanded parameter packs. 12878 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12879 // Drop the parameters. 12880 FunctionProtoType::ExtProtoInfo EPI; 12881 EPI.HasTrailingReturn = false; 12882 EPI.TypeQuals |= DeclSpec::TQ_const; 12883 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12884 Sig = Context.getTrivialTypeSourceInfo(T); 12885 } 12886 12887 // GetTypeForDeclarator always produces a function type for a block 12888 // literal signature. Furthermore, it is always a FunctionProtoType 12889 // unless the function was written with a typedef. 12890 assert(T->isFunctionType() && 12891 "GetTypeForDeclarator made a non-function block signature"); 12892 12893 // Look for an explicit signature in that function type. 12894 FunctionProtoTypeLoc ExplicitSignature; 12895 12896 if ((ExplicitSignature = 12897 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 12898 12899 // Check whether that explicit signature was synthesized by 12900 // GetTypeForDeclarator. If so, don't save that as part of the 12901 // written signature. 12902 if (ExplicitSignature.getLocalRangeBegin() == 12903 ExplicitSignature.getLocalRangeEnd()) { 12904 // This would be much cheaper if we stored TypeLocs instead of 12905 // TypeSourceInfos. 12906 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12907 unsigned Size = Result.getFullDataSize(); 12908 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12909 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12910 12911 ExplicitSignature = FunctionProtoTypeLoc(); 12912 } 12913 } 12914 12915 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12916 CurBlock->FunctionType = T; 12917 12918 const FunctionType *Fn = T->getAs<FunctionType>(); 12919 QualType RetTy = Fn->getReturnType(); 12920 bool isVariadic = 12921 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12922 12923 CurBlock->TheDecl->setIsVariadic(isVariadic); 12924 12925 // Context.DependentTy is used as a placeholder for a missing block 12926 // return type. TODO: what should we do with declarators like: 12927 // ^ * { ... } 12928 // If the answer is "apply template argument deduction".... 12929 if (RetTy != Context.DependentTy) { 12930 CurBlock->ReturnType = RetTy; 12931 CurBlock->TheDecl->setBlockMissingReturnType(false); 12932 CurBlock->HasImplicitReturnType = false; 12933 } 12934 12935 // Push block parameters from the declarator if we had them. 12936 SmallVector<ParmVarDecl*, 8> Params; 12937 if (ExplicitSignature) { 12938 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12939 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12940 if (Param->getIdentifier() == nullptr && 12941 !Param->isImplicit() && 12942 !Param->isInvalidDecl() && 12943 !getLangOpts().CPlusPlus) 12944 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12945 Params.push_back(Param); 12946 } 12947 12948 // Fake up parameter variables if we have a typedef, like 12949 // ^ fntype { ... } 12950 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12951 for (const auto &I : Fn->param_types()) { 12952 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12953 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12954 Params.push_back(Param); 12955 } 12956 } 12957 12958 // Set the parameters on the block decl. 12959 if (!Params.empty()) { 12960 CurBlock->TheDecl->setParams(Params); 12961 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12962 /*CheckParameterNames=*/false); 12963 } 12964 12965 // Finally we can process decl attributes. 12966 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12967 12968 // Put the parameter variables in scope. 12969 for (auto AI : CurBlock->TheDecl->parameters()) { 12970 AI->setOwningFunction(CurBlock->TheDecl); 12971 12972 // If this has an identifier, add it to the scope stack. 12973 if (AI->getIdentifier()) { 12974 CheckShadow(CurBlock->TheScope, AI); 12975 12976 PushOnScopeChains(AI, CurBlock->TheScope); 12977 } 12978 } 12979 } 12980 12981 /// ActOnBlockError - If there is an error parsing a block, this callback 12982 /// is invoked to pop the information about the block from the action impl. 12983 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12984 // Leave the expression-evaluation context. 12985 DiscardCleanupsInEvaluationContext(); 12986 PopExpressionEvaluationContext(); 12987 12988 // Pop off CurBlock, handle nested blocks. 12989 PopDeclContext(); 12990 PopFunctionScopeInfo(); 12991 } 12992 12993 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12994 /// literal was successfully completed. ^(int x){...} 12995 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12996 Stmt *Body, Scope *CurScope) { 12997 // If blocks are disabled, emit an error. 12998 if (!LangOpts.Blocks) 12999 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13000 13001 // Leave the expression-evaluation context. 13002 if (hasAnyUnrecoverableErrorsInThisFunction()) 13003 DiscardCleanupsInEvaluationContext(); 13004 assert(!Cleanup.exprNeedsCleanups() && 13005 "cleanups within block not correctly bound!"); 13006 PopExpressionEvaluationContext(); 13007 13008 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13009 13010 if (BSI->HasImplicitReturnType) 13011 deduceClosureReturnType(*BSI); 13012 13013 PopDeclContext(); 13014 13015 QualType RetTy = Context.VoidTy; 13016 if (!BSI->ReturnType.isNull()) 13017 RetTy = BSI->ReturnType; 13018 13019 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 13020 QualType BlockTy; 13021 13022 // Set the captured variables on the block. 13023 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13024 SmallVector<BlockDecl::Capture, 4> Captures; 13025 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 13026 if (Cap.isThisCapture()) 13027 continue; 13028 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13029 Cap.isNested(), Cap.getInitExpr()); 13030 Captures.push_back(NewCap); 13031 } 13032 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13033 13034 // If the user wrote a function type in some form, try to use that. 13035 if (!BSI->FunctionType.isNull()) { 13036 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13037 13038 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13039 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13040 13041 // Turn protoless block types into nullary block types. 13042 if (isa<FunctionNoProtoType>(FTy)) { 13043 FunctionProtoType::ExtProtoInfo EPI; 13044 EPI.ExtInfo = Ext; 13045 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13046 13047 // Otherwise, if we don't need to change anything about the function type, 13048 // preserve its sugar structure. 13049 } else if (FTy->getReturnType() == RetTy && 13050 (!NoReturn || FTy->getNoReturnAttr())) { 13051 BlockTy = BSI->FunctionType; 13052 13053 // Otherwise, make the minimal modifications to the function type. 13054 } else { 13055 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13056 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13057 EPI.TypeQuals = 0; // FIXME: silently? 13058 EPI.ExtInfo = Ext; 13059 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13060 } 13061 13062 // If we don't have a function type, just build one from nothing. 13063 } else { 13064 FunctionProtoType::ExtProtoInfo EPI; 13065 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13066 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13067 } 13068 13069 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13070 BlockTy = Context.getBlockPointerType(BlockTy); 13071 13072 // If needed, diagnose invalid gotos and switches in the block. 13073 if (getCurFunction()->NeedsScopeChecking() && 13074 !PP.isCodeCompletionEnabled()) 13075 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13076 13077 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13078 13079 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13080 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13081 13082 // Try to apply the named return value optimization. We have to check again 13083 // if we can do this, though, because blocks keep return statements around 13084 // to deduce an implicit return type. 13085 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13086 !BSI->TheDecl->isDependentContext()) 13087 computeNRVO(Body, BSI); 13088 13089 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13090 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13091 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13092 13093 // If the block isn't obviously global, i.e. it captures anything at 13094 // all, then we need to do a few things in the surrounding context: 13095 if (Result->getBlockDecl()->hasCaptures()) { 13096 // First, this expression has a new cleanup object. 13097 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13098 Cleanup.setExprNeedsCleanups(true); 13099 13100 // It also gets a branch-protected scope if any of the captured 13101 // variables needs destruction. 13102 for (const auto &CI : Result->getBlockDecl()->captures()) { 13103 const VarDecl *var = CI.getVariable(); 13104 if (var->getType().isDestructedType() != QualType::DK_none) { 13105 getCurFunction()->setHasBranchProtectedScope(); 13106 break; 13107 } 13108 } 13109 } 13110 13111 return Result; 13112 } 13113 13114 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13115 SourceLocation RPLoc) { 13116 TypeSourceInfo *TInfo; 13117 GetTypeFromParser(Ty, &TInfo); 13118 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13119 } 13120 13121 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13122 Expr *E, TypeSourceInfo *TInfo, 13123 SourceLocation RPLoc) { 13124 Expr *OrigExpr = E; 13125 bool IsMS = false; 13126 13127 // CUDA device code does not support varargs. 13128 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13129 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13130 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13131 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13132 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13133 } 13134 } 13135 13136 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13137 // as Microsoft ABI on an actual Microsoft platform, where 13138 // __builtin_ms_va_list and __builtin_va_list are the same.) 13139 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13140 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13141 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13142 if (Context.hasSameType(MSVaListType, E->getType())) { 13143 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13144 return ExprError(); 13145 IsMS = true; 13146 } 13147 } 13148 13149 // Get the va_list type 13150 QualType VaListType = Context.getBuiltinVaListType(); 13151 if (!IsMS) { 13152 if (VaListType->isArrayType()) { 13153 // Deal with implicit array decay; for example, on x86-64, 13154 // va_list is an array, but it's supposed to decay to 13155 // a pointer for va_arg. 13156 VaListType = Context.getArrayDecayedType(VaListType); 13157 // Make sure the input expression also decays appropriately. 13158 ExprResult Result = UsualUnaryConversions(E); 13159 if (Result.isInvalid()) 13160 return ExprError(); 13161 E = Result.get(); 13162 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13163 // If va_list is a record type and we are compiling in C++ mode, 13164 // check the argument using reference binding. 13165 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13166 Context, Context.getLValueReferenceType(VaListType), false); 13167 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13168 if (Init.isInvalid()) 13169 return ExprError(); 13170 E = Init.getAs<Expr>(); 13171 } else { 13172 // Otherwise, the va_list argument must be an l-value because 13173 // it is modified by va_arg. 13174 if (!E->isTypeDependent() && 13175 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13176 return ExprError(); 13177 } 13178 } 13179 13180 if (!IsMS && !E->isTypeDependent() && 13181 !Context.hasSameType(VaListType, E->getType())) 13182 return ExprError(Diag(E->getLocStart(), 13183 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13184 << OrigExpr->getType() << E->getSourceRange()); 13185 13186 if (!TInfo->getType()->isDependentType()) { 13187 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13188 diag::err_second_parameter_to_va_arg_incomplete, 13189 TInfo->getTypeLoc())) 13190 return ExprError(); 13191 13192 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13193 TInfo->getType(), 13194 diag::err_second_parameter_to_va_arg_abstract, 13195 TInfo->getTypeLoc())) 13196 return ExprError(); 13197 13198 if (!TInfo->getType().isPODType(Context)) { 13199 Diag(TInfo->getTypeLoc().getBeginLoc(), 13200 TInfo->getType()->isObjCLifetimeType() 13201 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13202 : diag::warn_second_parameter_to_va_arg_not_pod) 13203 << TInfo->getType() 13204 << TInfo->getTypeLoc().getSourceRange(); 13205 } 13206 13207 // Check for va_arg where arguments of the given type will be promoted 13208 // (i.e. this va_arg is guaranteed to have undefined behavior). 13209 QualType PromoteType; 13210 if (TInfo->getType()->isPromotableIntegerType()) { 13211 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13212 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13213 PromoteType = QualType(); 13214 } 13215 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13216 PromoteType = Context.DoubleTy; 13217 if (!PromoteType.isNull()) 13218 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13219 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13220 << TInfo->getType() 13221 << PromoteType 13222 << TInfo->getTypeLoc().getSourceRange()); 13223 } 13224 13225 QualType T = TInfo->getType().getNonLValueExprType(Context); 13226 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13227 } 13228 13229 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13230 // The type of __null will be int or long, depending on the size of 13231 // pointers on the target. 13232 QualType Ty; 13233 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13234 if (pw == Context.getTargetInfo().getIntWidth()) 13235 Ty = Context.IntTy; 13236 else if (pw == Context.getTargetInfo().getLongWidth()) 13237 Ty = Context.LongTy; 13238 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13239 Ty = Context.LongLongTy; 13240 else { 13241 llvm_unreachable("I don't know size of pointer!"); 13242 } 13243 13244 return new (Context) GNUNullExpr(Ty, TokenLoc); 13245 } 13246 13247 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13248 bool Diagnose) { 13249 if (!getLangOpts().ObjC1) 13250 return false; 13251 13252 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13253 if (!PT) 13254 return false; 13255 13256 if (!PT->isObjCIdType()) { 13257 // Check if the destination is the 'NSString' interface. 13258 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13259 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13260 return false; 13261 } 13262 13263 // Ignore any parens, implicit casts (should only be 13264 // array-to-pointer decays), and not-so-opaque values. The last is 13265 // important for making this trigger for property assignments. 13266 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13267 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13268 if (OV->getSourceExpr()) 13269 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13270 13271 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13272 if (!SL || !SL->isAscii()) 13273 return false; 13274 if (Diagnose) { 13275 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13276 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13277 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13278 } 13279 return true; 13280 } 13281 13282 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13283 const Expr *SrcExpr) { 13284 if (!DstType->isFunctionPointerType() || 13285 !SrcExpr->getType()->isFunctionType()) 13286 return false; 13287 13288 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13289 if (!DRE) 13290 return false; 13291 13292 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13293 if (!FD) 13294 return false; 13295 13296 return !S.checkAddressOfFunctionIsAvailable(FD, 13297 /*Complain=*/true, 13298 SrcExpr->getLocStart()); 13299 } 13300 13301 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13302 SourceLocation Loc, 13303 QualType DstType, QualType SrcType, 13304 Expr *SrcExpr, AssignmentAction Action, 13305 bool *Complained) { 13306 if (Complained) 13307 *Complained = false; 13308 13309 // Decode the result (notice that AST's are still created for extensions). 13310 bool CheckInferredResultType = false; 13311 bool isInvalid = false; 13312 unsigned DiagKind = 0; 13313 FixItHint Hint; 13314 ConversionFixItGenerator ConvHints; 13315 bool MayHaveConvFixit = false; 13316 bool MayHaveFunctionDiff = false; 13317 const ObjCInterfaceDecl *IFace = nullptr; 13318 const ObjCProtocolDecl *PDecl = nullptr; 13319 13320 switch (ConvTy) { 13321 case Compatible: 13322 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13323 return false; 13324 13325 case PointerToInt: 13326 DiagKind = diag::ext_typecheck_convert_pointer_int; 13327 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13328 MayHaveConvFixit = true; 13329 break; 13330 case IntToPointer: 13331 DiagKind = diag::ext_typecheck_convert_int_pointer; 13332 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13333 MayHaveConvFixit = true; 13334 break; 13335 case IncompatiblePointer: 13336 if (Action == AA_Passing_CFAudited) 13337 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13338 else if (SrcType->isFunctionPointerType() && 13339 DstType->isFunctionPointerType()) 13340 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13341 else 13342 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13343 13344 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13345 SrcType->isObjCObjectPointerType(); 13346 if (Hint.isNull() && !CheckInferredResultType) { 13347 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13348 } 13349 else if (CheckInferredResultType) { 13350 SrcType = SrcType.getUnqualifiedType(); 13351 DstType = DstType.getUnqualifiedType(); 13352 } 13353 MayHaveConvFixit = true; 13354 break; 13355 case IncompatiblePointerSign: 13356 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13357 break; 13358 case FunctionVoidPointer: 13359 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13360 break; 13361 case IncompatiblePointerDiscardsQualifiers: { 13362 // Perform array-to-pointer decay if necessary. 13363 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13364 13365 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13366 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13367 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13368 DiagKind = diag::err_typecheck_incompatible_address_space; 13369 break; 13370 13371 13372 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13373 DiagKind = diag::err_typecheck_incompatible_ownership; 13374 break; 13375 } 13376 13377 llvm_unreachable("unknown error case for discarding qualifiers!"); 13378 // fallthrough 13379 } 13380 case CompatiblePointerDiscardsQualifiers: 13381 // If the qualifiers lost were because we were applying the 13382 // (deprecated) C++ conversion from a string literal to a char* 13383 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13384 // Ideally, this check would be performed in 13385 // checkPointerTypesForAssignment. However, that would require a 13386 // bit of refactoring (so that the second argument is an 13387 // expression, rather than a type), which should be done as part 13388 // of a larger effort to fix checkPointerTypesForAssignment for 13389 // C++ semantics. 13390 if (getLangOpts().CPlusPlus && 13391 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13392 return false; 13393 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13394 break; 13395 case IncompatibleNestedPointerQualifiers: 13396 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13397 break; 13398 case IntToBlockPointer: 13399 DiagKind = diag::err_int_to_block_pointer; 13400 break; 13401 case IncompatibleBlockPointer: 13402 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13403 break; 13404 case IncompatibleObjCQualifiedId: { 13405 if (SrcType->isObjCQualifiedIdType()) { 13406 const ObjCObjectPointerType *srcOPT = 13407 SrcType->getAs<ObjCObjectPointerType>(); 13408 for (auto *srcProto : srcOPT->quals()) { 13409 PDecl = srcProto; 13410 break; 13411 } 13412 if (const ObjCInterfaceType *IFaceT = 13413 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13414 IFace = IFaceT->getDecl(); 13415 } 13416 else if (DstType->isObjCQualifiedIdType()) { 13417 const ObjCObjectPointerType *dstOPT = 13418 DstType->getAs<ObjCObjectPointerType>(); 13419 for (auto *dstProto : dstOPT->quals()) { 13420 PDecl = dstProto; 13421 break; 13422 } 13423 if (const ObjCInterfaceType *IFaceT = 13424 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13425 IFace = IFaceT->getDecl(); 13426 } 13427 DiagKind = diag::warn_incompatible_qualified_id; 13428 break; 13429 } 13430 case IncompatibleVectors: 13431 DiagKind = diag::warn_incompatible_vectors; 13432 break; 13433 case IncompatibleObjCWeakRef: 13434 DiagKind = diag::err_arc_weak_unavailable_assign; 13435 break; 13436 case Incompatible: 13437 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13438 if (Complained) 13439 *Complained = true; 13440 return true; 13441 } 13442 13443 DiagKind = diag::err_typecheck_convert_incompatible; 13444 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13445 MayHaveConvFixit = true; 13446 isInvalid = true; 13447 MayHaveFunctionDiff = true; 13448 break; 13449 } 13450 13451 QualType FirstType, SecondType; 13452 switch (Action) { 13453 case AA_Assigning: 13454 case AA_Initializing: 13455 // The destination type comes first. 13456 FirstType = DstType; 13457 SecondType = SrcType; 13458 break; 13459 13460 case AA_Returning: 13461 case AA_Passing: 13462 case AA_Passing_CFAudited: 13463 case AA_Converting: 13464 case AA_Sending: 13465 case AA_Casting: 13466 // The source type comes first. 13467 FirstType = SrcType; 13468 SecondType = DstType; 13469 break; 13470 } 13471 13472 PartialDiagnostic FDiag = PDiag(DiagKind); 13473 if (Action == AA_Passing_CFAudited) 13474 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13475 else 13476 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13477 13478 // If we can fix the conversion, suggest the FixIts. 13479 assert(ConvHints.isNull() || Hint.isNull()); 13480 if (!ConvHints.isNull()) { 13481 for (FixItHint &H : ConvHints.Hints) 13482 FDiag << H; 13483 } else { 13484 FDiag << Hint; 13485 } 13486 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13487 13488 if (MayHaveFunctionDiff) 13489 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13490 13491 Diag(Loc, FDiag); 13492 if (DiagKind == diag::warn_incompatible_qualified_id && 13493 PDecl && IFace && !IFace->hasDefinition()) 13494 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13495 << IFace->getName() << PDecl->getName(); 13496 13497 if (SecondType == Context.OverloadTy) 13498 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13499 FirstType, /*TakingAddress=*/true); 13500 13501 if (CheckInferredResultType) 13502 EmitRelatedResultTypeNote(SrcExpr); 13503 13504 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13505 EmitRelatedResultTypeNoteForReturn(DstType); 13506 13507 if (Complained) 13508 *Complained = true; 13509 return isInvalid; 13510 } 13511 13512 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13513 llvm::APSInt *Result) { 13514 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13515 public: 13516 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13517 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13518 } 13519 } Diagnoser; 13520 13521 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13522 } 13523 13524 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13525 llvm::APSInt *Result, 13526 unsigned DiagID, 13527 bool AllowFold) { 13528 class IDDiagnoser : public VerifyICEDiagnoser { 13529 unsigned DiagID; 13530 13531 public: 13532 IDDiagnoser(unsigned DiagID) 13533 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13534 13535 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13536 S.Diag(Loc, DiagID) << SR; 13537 } 13538 } Diagnoser(DiagID); 13539 13540 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13541 } 13542 13543 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13544 SourceRange SR) { 13545 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13546 } 13547 13548 ExprResult 13549 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13550 VerifyICEDiagnoser &Diagnoser, 13551 bool AllowFold) { 13552 SourceLocation DiagLoc = E->getLocStart(); 13553 13554 if (getLangOpts().CPlusPlus11) { 13555 // C++11 [expr.const]p5: 13556 // If an expression of literal class type is used in a context where an 13557 // integral constant expression is required, then that class type shall 13558 // have a single non-explicit conversion function to an integral or 13559 // unscoped enumeration type 13560 ExprResult Converted; 13561 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13562 public: 13563 CXX11ConvertDiagnoser(bool Silent) 13564 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13565 Silent, true) {} 13566 13567 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13568 QualType T) override { 13569 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13570 } 13571 13572 SemaDiagnosticBuilder diagnoseIncomplete( 13573 Sema &S, SourceLocation Loc, QualType T) override { 13574 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13575 } 13576 13577 SemaDiagnosticBuilder diagnoseExplicitConv( 13578 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13579 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13580 } 13581 13582 SemaDiagnosticBuilder noteExplicitConv( 13583 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13584 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13585 << ConvTy->isEnumeralType() << ConvTy; 13586 } 13587 13588 SemaDiagnosticBuilder diagnoseAmbiguous( 13589 Sema &S, SourceLocation Loc, QualType T) override { 13590 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13591 } 13592 13593 SemaDiagnosticBuilder noteAmbiguous( 13594 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13595 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13596 << ConvTy->isEnumeralType() << ConvTy; 13597 } 13598 13599 SemaDiagnosticBuilder diagnoseConversion( 13600 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13601 llvm_unreachable("conversion functions are permitted"); 13602 } 13603 } ConvertDiagnoser(Diagnoser.Suppress); 13604 13605 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13606 ConvertDiagnoser); 13607 if (Converted.isInvalid()) 13608 return Converted; 13609 E = Converted.get(); 13610 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13611 return ExprError(); 13612 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13613 // An ICE must be of integral or unscoped enumeration type. 13614 if (!Diagnoser.Suppress) 13615 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13616 return ExprError(); 13617 } 13618 13619 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13620 // in the non-ICE case. 13621 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13622 if (Result) 13623 *Result = E->EvaluateKnownConstInt(Context); 13624 return E; 13625 } 13626 13627 Expr::EvalResult EvalResult; 13628 SmallVector<PartialDiagnosticAt, 8> Notes; 13629 EvalResult.Diag = &Notes; 13630 13631 // Try to evaluate the expression, and produce diagnostics explaining why it's 13632 // not a constant expression as a side-effect. 13633 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13634 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13635 13636 // In C++11, we can rely on diagnostics being produced for any expression 13637 // which is not a constant expression. If no diagnostics were produced, then 13638 // this is a constant expression. 13639 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13640 if (Result) 13641 *Result = EvalResult.Val.getInt(); 13642 return E; 13643 } 13644 13645 // If our only note is the usual "invalid subexpression" note, just point 13646 // the caret at its location rather than producing an essentially 13647 // redundant note. 13648 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13649 diag::note_invalid_subexpr_in_const_expr) { 13650 DiagLoc = Notes[0].first; 13651 Notes.clear(); 13652 } 13653 13654 if (!Folded || !AllowFold) { 13655 if (!Diagnoser.Suppress) { 13656 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13657 for (const PartialDiagnosticAt &Note : Notes) 13658 Diag(Note.first, Note.second); 13659 } 13660 13661 return ExprError(); 13662 } 13663 13664 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13665 for (const PartialDiagnosticAt &Note : Notes) 13666 Diag(Note.first, Note.second); 13667 13668 if (Result) 13669 *Result = EvalResult.Val.getInt(); 13670 return E; 13671 } 13672 13673 namespace { 13674 // Handle the case where we conclude a expression which we speculatively 13675 // considered to be unevaluated is actually evaluated. 13676 class TransformToPE : public TreeTransform<TransformToPE> { 13677 typedef TreeTransform<TransformToPE> BaseTransform; 13678 13679 public: 13680 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13681 13682 // Make sure we redo semantic analysis 13683 bool AlwaysRebuild() { return true; } 13684 13685 // Make sure we handle LabelStmts correctly. 13686 // FIXME: This does the right thing, but maybe we need a more general 13687 // fix to TreeTransform? 13688 StmtResult TransformLabelStmt(LabelStmt *S) { 13689 S->getDecl()->setStmt(nullptr); 13690 return BaseTransform::TransformLabelStmt(S); 13691 } 13692 13693 // We need to special-case DeclRefExprs referring to FieldDecls which 13694 // are not part of a member pointer formation; normal TreeTransforming 13695 // doesn't catch this case because of the way we represent them in the AST. 13696 // FIXME: This is a bit ugly; is it really the best way to handle this 13697 // case? 13698 // 13699 // Error on DeclRefExprs referring to FieldDecls. 13700 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13701 if (isa<FieldDecl>(E->getDecl()) && 13702 !SemaRef.isUnevaluatedContext()) 13703 return SemaRef.Diag(E->getLocation(), 13704 diag::err_invalid_non_static_member_use) 13705 << E->getDecl() << E->getSourceRange(); 13706 13707 return BaseTransform::TransformDeclRefExpr(E); 13708 } 13709 13710 // Exception: filter out member pointer formation 13711 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13712 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13713 return E; 13714 13715 return BaseTransform::TransformUnaryOperator(E); 13716 } 13717 13718 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13719 // Lambdas never need to be transformed. 13720 return E; 13721 } 13722 }; 13723 } 13724 13725 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13726 assert(isUnevaluatedContext() && 13727 "Should only transform unevaluated expressions"); 13728 ExprEvalContexts.back().Context = 13729 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13730 if (isUnevaluatedContext()) 13731 return E; 13732 return TransformToPE(*this).TransformExpr(E); 13733 } 13734 13735 void 13736 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13737 Decl *LambdaContextDecl, 13738 bool IsDecltype) { 13739 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13740 LambdaContextDecl, IsDecltype); 13741 Cleanup.reset(); 13742 if (!MaybeODRUseExprs.empty()) 13743 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13744 } 13745 13746 void 13747 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13748 ReuseLambdaContextDecl_t, 13749 bool IsDecltype) { 13750 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13751 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13752 } 13753 13754 void Sema::PopExpressionEvaluationContext() { 13755 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13756 unsigned NumTypos = Rec.NumTypos; 13757 13758 if (!Rec.Lambdas.empty()) { 13759 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13760 unsigned D; 13761 if (Rec.isUnevaluated()) { 13762 // C++11 [expr.prim.lambda]p2: 13763 // A lambda-expression shall not appear in an unevaluated operand 13764 // (Clause 5). 13765 D = diag::err_lambda_unevaluated_operand; 13766 } else { 13767 // C++1y [expr.const]p2: 13768 // A conditional-expression e is a core constant expression unless the 13769 // evaluation of e, following the rules of the abstract machine, would 13770 // evaluate [...] a lambda-expression. 13771 D = diag::err_lambda_in_constant_expression; 13772 } 13773 13774 // C++1z allows lambda expressions as core constant expressions. 13775 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13776 // 1607) from appearing within template-arguments and array-bounds that 13777 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13778 // unevaluated contexts) might lift some of these restrictions in a 13779 // future version. 13780 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17) 13781 for (const auto *L : Rec.Lambdas) 13782 Diag(L->getLocStart(), D); 13783 } else { 13784 // Mark the capture expressions odr-used. This was deferred 13785 // during lambda expression creation. 13786 for (auto *Lambda : Rec.Lambdas) { 13787 for (auto *C : Lambda->capture_inits()) 13788 MarkDeclarationsReferencedInExpr(C); 13789 } 13790 } 13791 } 13792 13793 // When are coming out of an unevaluated context, clear out any 13794 // temporaries that we may have created as part of the evaluation of 13795 // the expression in that context: they aren't relevant because they 13796 // will never be constructed. 13797 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13798 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13799 ExprCleanupObjects.end()); 13800 Cleanup = Rec.ParentCleanup; 13801 CleanupVarDeclMarking(); 13802 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13803 // Otherwise, merge the contexts together. 13804 } else { 13805 Cleanup.mergeFrom(Rec.ParentCleanup); 13806 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13807 Rec.SavedMaybeODRUseExprs.end()); 13808 } 13809 13810 // Pop the current expression evaluation context off the stack. 13811 ExprEvalContexts.pop_back(); 13812 13813 if (!ExprEvalContexts.empty()) 13814 ExprEvalContexts.back().NumTypos += NumTypos; 13815 else 13816 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13817 "last ExpressionEvaluationContextRecord"); 13818 } 13819 13820 void Sema::DiscardCleanupsInEvaluationContext() { 13821 ExprCleanupObjects.erase( 13822 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13823 ExprCleanupObjects.end()); 13824 Cleanup.reset(); 13825 MaybeODRUseExprs.clear(); 13826 } 13827 13828 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13829 if (!E->getType()->isVariablyModifiedType()) 13830 return E; 13831 return TransformToPotentiallyEvaluated(E); 13832 } 13833 13834 /// Are we within a context in which some evaluation could be performed (be it 13835 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13836 /// captured by C++'s idea of an "unevaluated context". 13837 static bool isEvaluatableContext(Sema &SemaRef) { 13838 switch (SemaRef.ExprEvalContexts.back().Context) { 13839 case Sema::ExpressionEvaluationContext::Unevaluated: 13840 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13841 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13842 // Expressions in this context are never evaluated. 13843 return false; 13844 13845 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13846 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13847 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13848 // Expressions in this context could be evaluated. 13849 return true; 13850 13851 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13852 // Referenced declarations will only be used if the construct in the 13853 // containing expression is used, at which point we'll be given another 13854 // turn to mark them. 13855 return false; 13856 } 13857 llvm_unreachable("Invalid context"); 13858 } 13859 13860 /// Are we within a context in which references to resolved functions or to 13861 /// variables result in odr-use? 13862 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13863 // An expression in a template is not really an expression until it's been 13864 // instantiated, so it doesn't trigger odr-use. 13865 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13866 return false; 13867 13868 switch (SemaRef.ExprEvalContexts.back().Context) { 13869 case Sema::ExpressionEvaluationContext::Unevaluated: 13870 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13871 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13872 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13873 return false; 13874 13875 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13876 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13877 return true; 13878 13879 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13880 return false; 13881 } 13882 llvm_unreachable("Invalid context"); 13883 } 13884 13885 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13886 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13887 return Func->isConstexpr() && 13888 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13889 } 13890 13891 /// \brief Mark a function referenced, and check whether it is odr-used 13892 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13893 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13894 bool MightBeOdrUse) { 13895 assert(Func && "No function?"); 13896 13897 Func->setReferenced(); 13898 13899 // C++11 [basic.def.odr]p3: 13900 // A function whose name appears as a potentially-evaluated expression is 13901 // odr-used if it is the unique lookup result or the selected member of a 13902 // set of overloaded functions [...]. 13903 // 13904 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13905 // can just check that here. 13906 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13907 13908 // Determine whether we require a function definition to exist, per 13909 // C++11 [temp.inst]p3: 13910 // Unless a function template specialization has been explicitly 13911 // instantiated or explicitly specialized, the function template 13912 // specialization is implicitly instantiated when the specialization is 13913 // referenced in a context that requires a function definition to exist. 13914 // 13915 // That is either when this is an odr-use, or when a usage of a constexpr 13916 // function occurs within an evaluatable context. 13917 bool NeedDefinition = 13918 OdrUse || (isEvaluatableContext(*this) && 13919 isImplicitlyDefinableConstexprFunction(Func)); 13920 13921 // C++14 [temp.expl.spec]p6: 13922 // If a template [...] is explicitly specialized then that specialization 13923 // shall be declared before the first use of that specialization that would 13924 // cause an implicit instantiation to take place, in every translation unit 13925 // in which such a use occurs 13926 if (NeedDefinition && 13927 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13928 Func->getMemberSpecializationInfo())) 13929 checkSpecializationVisibility(Loc, Func); 13930 13931 // C++14 [except.spec]p17: 13932 // An exception-specification is considered to be needed when: 13933 // - the function is odr-used or, if it appears in an unevaluated operand, 13934 // would be odr-used if the expression were potentially-evaluated; 13935 // 13936 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13937 // function is a pure virtual function we're calling, and in that case the 13938 // function was selected by overload resolution and we need to resolve its 13939 // exception specification for a different reason. 13940 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13941 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13942 ResolveExceptionSpec(Loc, FPT); 13943 13944 // If we don't need to mark the function as used, and we don't need to 13945 // try to provide a definition, there's nothing more to do. 13946 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13947 (!NeedDefinition || Func->getBody())) 13948 return; 13949 13950 // Note that this declaration has been used. 13951 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13952 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13953 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13954 if (Constructor->isDefaultConstructor()) { 13955 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13956 return; 13957 DefineImplicitDefaultConstructor(Loc, Constructor); 13958 } else if (Constructor->isCopyConstructor()) { 13959 DefineImplicitCopyConstructor(Loc, Constructor); 13960 } else if (Constructor->isMoveConstructor()) { 13961 DefineImplicitMoveConstructor(Loc, Constructor); 13962 } 13963 } else if (Constructor->getInheritedConstructor()) { 13964 DefineInheritingConstructor(Loc, Constructor); 13965 } 13966 } else if (CXXDestructorDecl *Destructor = 13967 dyn_cast<CXXDestructorDecl>(Func)) { 13968 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13969 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13970 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13971 return; 13972 DefineImplicitDestructor(Loc, Destructor); 13973 } 13974 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13975 MarkVTableUsed(Loc, Destructor->getParent()); 13976 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13977 if (MethodDecl->isOverloadedOperator() && 13978 MethodDecl->getOverloadedOperator() == OO_Equal) { 13979 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13980 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13981 if (MethodDecl->isCopyAssignmentOperator()) 13982 DefineImplicitCopyAssignment(Loc, MethodDecl); 13983 else if (MethodDecl->isMoveAssignmentOperator()) 13984 DefineImplicitMoveAssignment(Loc, MethodDecl); 13985 } 13986 } else if (isa<CXXConversionDecl>(MethodDecl) && 13987 MethodDecl->getParent()->isLambda()) { 13988 CXXConversionDecl *Conversion = 13989 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13990 if (Conversion->isLambdaToBlockPointerConversion()) 13991 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13992 else 13993 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13994 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13995 MarkVTableUsed(Loc, MethodDecl->getParent()); 13996 } 13997 13998 // Recursive functions should be marked when used from another function. 13999 // FIXME: Is this really right? 14000 if (CurContext == Func) return; 14001 14002 // Implicit instantiation of function templates and member functions of 14003 // class templates. 14004 if (Func->isImplicitlyInstantiable()) { 14005 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14006 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14007 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14008 if (FirstInstantiation) { 14009 PointOfInstantiation = Loc; 14010 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14011 } else if (TSK != TSK_ImplicitInstantiation) { 14012 // Use the point of use as the point of instantiation, instead of the 14013 // point of explicit instantiation (which we track as the actual point of 14014 // instantiation). This gives better backtraces in diagnostics. 14015 PointOfInstantiation = Loc; 14016 } 14017 14018 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14019 Func->isConstexpr()) { 14020 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14021 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14022 CodeSynthesisContexts.size()) 14023 PendingLocalImplicitInstantiations.push_back( 14024 std::make_pair(Func, PointOfInstantiation)); 14025 else if (Func->isConstexpr()) 14026 // Do not defer instantiations of constexpr functions, to avoid the 14027 // expression evaluator needing to call back into Sema if it sees a 14028 // call to such a function. 14029 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14030 else { 14031 Func->setInstantiationIsPending(true); 14032 PendingInstantiations.push_back(std::make_pair(Func, 14033 PointOfInstantiation)); 14034 // Notify the consumer that a function was implicitly instantiated. 14035 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14036 } 14037 } 14038 } else { 14039 // Walk redefinitions, as some of them may be instantiable. 14040 for (auto i : Func->redecls()) { 14041 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14042 MarkFunctionReferenced(Loc, i, OdrUse); 14043 } 14044 } 14045 14046 if (!OdrUse) return; 14047 14048 // Keep track of used but undefined functions. 14049 if (!Func->isDefined()) { 14050 if (mightHaveNonExternalLinkage(Func)) 14051 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14052 else if (Func->getMostRecentDecl()->isInlined() && 14053 !LangOpts.GNUInline && 14054 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14055 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14056 else if (isExternalWithNoLinkageType(Func)) 14057 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14058 } 14059 14060 Func->markUsed(Context); 14061 } 14062 14063 static void 14064 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14065 ValueDecl *var, DeclContext *DC) { 14066 DeclContext *VarDC = var->getDeclContext(); 14067 14068 // If the parameter still belongs to the translation unit, then 14069 // we're actually just using one parameter in the declaration of 14070 // the next. 14071 if (isa<ParmVarDecl>(var) && 14072 isa<TranslationUnitDecl>(VarDC)) 14073 return; 14074 14075 // For C code, don't diagnose about capture if we're not actually in code 14076 // right now; it's impossible to write a non-constant expression outside of 14077 // function context, so we'll get other (more useful) diagnostics later. 14078 // 14079 // For C++, things get a bit more nasty... it would be nice to suppress this 14080 // diagnostic for certain cases like using a local variable in an array bound 14081 // for a member of a local class, but the correct predicate is not obvious. 14082 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14083 return; 14084 14085 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14086 unsigned ContextKind = 3; // unknown 14087 if (isa<CXXMethodDecl>(VarDC) && 14088 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14089 ContextKind = 2; 14090 } else if (isa<FunctionDecl>(VarDC)) { 14091 ContextKind = 0; 14092 } else if (isa<BlockDecl>(VarDC)) { 14093 ContextKind = 1; 14094 } 14095 14096 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14097 << var << ValueKind << ContextKind << VarDC; 14098 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14099 << var; 14100 14101 // FIXME: Add additional diagnostic info about class etc. which prevents 14102 // capture. 14103 } 14104 14105 14106 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14107 bool &SubCapturesAreNested, 14108 QualType &CaptureType, 14109 QualType &DeclRefType) { 14110 // Check whether we've already captured it. 14111 if (CSI->CaptureMap.count(Var)) { 14112 // If we found a capture, any subcaptures are nested. 14113 SubCapturesAreNested = true; 14114 14115 // Retrieve the capture type for this variable. 14116 CaptureType = CSI->getCapture(Var).getCaptureType(); 14117 14118 // Compute the type of an expression that refers to this variable. 14119 DeclRefType = CaptureType.getNonReferenceType(); 14120 14121 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14122 // are mutable in the sense that user can change their value - they are 14123 // private instances of the captured declarations. 14124 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 14125 if (Cap.isCopyCapture() && 14126 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14127 !(isa<CapturedRegionScopeInfo>(CSI) && 14128 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14129 DeclRefType.addConst(); 14130 return true; 14131 } 14132 return false; 14133 } 14134 14135 // Only block literals, captured statements, and lambda expressions can 14136 // capture; other scopes don't work. 14137 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14138 SourceLocation Loc, 14139 const bool Diagnose, Sema &S) { 14140 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14141 return getLambdaAwareParentOfDeclContext(DC); 14142 else if (Var->hasLocalStorage()) { 14143 if (Diagnose) 14144 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14145 } 14146 return nullptr; 14147 } 14148 14149 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14150 // certain types of variables (unnamed, variably modified types etc.) 14151 // so check for eligibility. 14152 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14153 SourceLocation Loc, 14154 const bool Diagnose, Sema &S) { 14155 14156 bool IsBlock = isa<BlockScopeInfo>(CSI); 14157 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14158 14159 // Lambdas are not allowed to capture unnamed variables 14160 // (e.g. anonymous unions). 14161 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14162 // assuming that's the intent. 14163 if (IsLambda && !Var->getDeclName()) { 14164 if (Diagnose) { 14165 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14166 S.Diag(Var->getLocation(), diag::note_declared_at); 14167 } 14168 return false; 14169 } 14170 14171 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14172 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14173 if (Diagnose) { 14174 S.Diag(Loc, diag::err_ref_vm_type); 14175 S.Diag(Var->getLocation(), diag::note_previous_decl) 14176 << Var->getDeclName(); 14177 } 14178 return false; 14179 } 14180 // Prohibit structs with flexible array members too. 14181 // We cannot capture what is in the tail end of the struct. 14182 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14183 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14184 if (Diagnose) { 14185 if (IsBlock) 14186 S.Diag(Loc, diag::err_ref_flexarray_type); 14187 else 14188 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14189 << Var->getDeclName(); 14190 S.Diag(Var->getLocation(), diag::note_previous_decl) 14191 << Var->getDeclName(); 14192 } 14193 return false; 14194 } 14195 } 14196 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14197 // Lambdas and captured statements are not allowed to capture __block 14198 // variables; they don't support the expected semantics. 14199 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14200 if (Diagnose) { 14201 S.Diag(Loc, diag::err_capture_block_variable) 14202 << Var->getDeclName() << !IsLambda; 14203 S.Diag(Var->getLocation(), diag::note_previous_decl) 14204 << Var->getDeclName(); 14205 } 14206 return false; 14207 } 14208 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14209 if (S.getLangOpts().OpenCL && IsBlock && 14210 Var->getType()->isBlockPointerType()) { 14211 if (Diagnose) 14212 S.Diag(Loc, diag::err_opencl_block_ref_block); 14213 return false; 14214 } 14215 14216 return true; 14217 } 14218 14219 // Returns true if the capture by block was successful. 14220 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14221 SourceLocation Loc, 14222 const bool BuildAndDiagnose, 14223 QualType &CaptureType, 14224 QualType &DeclRefType, 14225 const bool Nested, 14226 Sema &S) { 14227 Expr *CopyExpr = nullptr; 14228 bool ByRef = false; 14229 14230 // Blocks are not allowed to capture arrays. 14231 if (CaptureType->isArrayType()) { 14232 if (BuildAndDiagnose) { 14233 S.Diag(Loc, diag::err_ref_array_type); 14234 S.Diag(Var->getLocation(), diag::note_previous_decl) 14235 << Var->getDeclName(); 14236 } 14237 return false; 14238 } 14239 14240 // Forbid the block-capture of autoreleasing variables. 14241 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14242 if (BuildAndDiagnose) { 14243 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14244 << /*block*/ 0; 14245 S.Diag(Var->getLocation(), diag::note_previous_decl) 14246 << Var->getDeclName(); 14247 } 14248 return false; 14249 } 14250 14251 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14252 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14253 // This function finds out whether there is an AttributedType of kind 14254 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14255 // attr_objc_ownership implies __autoreleasing was explicitly specified 14256 // rather than being added implicitly by the compiler. 14257 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14258 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14259 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14260 return true; 14261 14262 // Peel off AttributedTypes that are not of kind objc_ownership. 14263 Ty = AttrTy->getModifiedType(); 14264 } 14265 14266 return false; 14267 }; 14268 14269 QualType PointeeTy = PT->getPointeeType(); 14270 14271 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14272 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14273 !IsObjCOwnershipAttributedType(PointeeTy)) { 14274 if (BuildAndDiagnose) { 14275 SourceLocation VarLoc = Var->getLocation(); 14276 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14277 { 14278 auto AddAutoreleaseNote = 14279 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14280 // Provide a fix-it for the '__autoreleasing' keyword at the 14281 // appropriate location in the variable's type. 14282 if (const auto *TSI = Var->getTypeSourceInfo()) { 14283 PointerTypeLoc PTL = 14284 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14285 if (PTL) { 14286 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14287 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14288 S.getLangOpts()); 14289 if (Loc.isValid()) { 14290 StringRef CharAtLoc = Lexer::getSourceText( 14291 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14292 S.getSourceManager(), S.getLangOpts()); 14293 AddAutoreleaseNote << FixItHint::CreateInsertion( 14294 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14295 ? " __autoreleasing " 14296 : " __autoreleasing"); 14297 } 14298 } 14299 } 14300 } 14301 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14302 } 14303 } 14304 } 14305 14306 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14307 if (HasBlocksAttr || CaptureType->isReferenceType() || 14308 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 14309 // Block capture by reference does not change the capture or 14310 // declaration reference types. 14311 ByRef = true; 14312 } else { 14313 // Block capture by copy introduces 'const'. 14314 CaptureType = CaptureType.getNonReferenceType().withConst(); 14315 DeclRefType = CaptureType; 14316 14317 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14318 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14319 // The capture logic needs the destructor, so make sure we mark it. 14320 // Usually this is unnecessary because most local variables have 14321 // their destructors marked at declaration time, but parameters are 14322 // an exception because it's technically only the call site that 14323 // actually requires the destructor. 14324 if (isa<ParmVarDecl>(Var)) 14325 S.FinalizeVarWithDestructor(Var, Record); 14326 14327 // Enter a new evaluation context to insulate the copy 14328 // full-expression. 14329 EnterExpressionEvaluationContext scope( 14330 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14331 14332 // According to the blocks spec, the capture of a variable from 14333 // the stack requires a const copy constructor. This is not true 14334 // of the copy/move done to move a __block variable to the heap. 14335 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14336 DeclRefType.withConst(), 14337 VK_LValue, Loc); 14338 14339 ExprResult Result 14340 = S.PerformCopyInitialization( 14341 InitializedEntity::InitializeBlock(Var->getLocation(), 14342 CaptureType, false), 14343 Loc, DeclRef); 14344 14345 // Build a full-expression copy expression if initialization 14346 // succeeded and used a non-trivial constructor. Recover from 14347 // errors by pretending that the copy isn't necessary. 14348 if (!Result.isInvalid() && 14349 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14350 ->isTrivial()) { 14351 Result = S.MaybeCreateExprWithCleanups(Result); 14352 CopyExpr = Result.get(); 14353 } 14354 } 14355 } 14356 } 14357 14358 // Actually capture the variable. 14359 if (BuildAndDiagnose) 14360 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14361 SourceLocation(), CaptureType, CopyExpr); 14362 14363 return true; 14364 14365 } 14366 14367 14368 /// \brief Capture the given variable in the captured region. 14369 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14370 VarDecl *Var, 14371 SourceLocation Loc, 14372 const bool BuildAndDiagnose, 14373 QualType &CaptureType, 14374 QualType &DeclRefType, 14375 const bool RefersToCapturedVariable, 14376 Sema &S) { 14377 // By default, capture variables by reference. 14378 bool ByRef = true; 14379 // Using an LValue reference type is consistent with Lambdas (see below). 14380 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14381 if (S.IsOpenMPCapturedDecl(Var)) { 14382 bool HasConst = DeclRefType.isConstQualified(); 14383 DeclRefType = DeclRefType.getUnqualifiedType(); 14384 // Don't lose diagnostics about assignments to const. 14385 if (HasConst) 14386 DeclRefType.addConst(); 14387 } 14388 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14389 } 14390 14391 if (ByRef) 14392 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14393 else 14394 CaptureType = DeclRefType; 14395 14396 Expr *CopyExpr = nullptr; 14397 if (BuildAndDiagnose) { 14398 // The current implementation assumes that all variables are captured 14399 // by references. Since there is no capture by copy, no expression 14400 // evaluation will be needed. 14401 RecordDecl *RD = RSI->TheRecordDecl; 14402 14403 FieldDecl *Field 14404 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14405 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14406 nullptr, false, ICIS_NoInit); 14407 Field->setImplicit(true); 14408 Field->setAccess(AS_private); 14409 RD->addDecl(Field); 14410 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14411 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14412 14413 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14414 DeclRefType, VK_LValue, Loc); 14415 Var->setReferenced(true); 14416 Var->markUsed(S.Context); 14417 } 14418 14419 // Actually capture the variable. 14420 if (BuildAndDiagnose) 14421 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14422 SourceLocation(), CaptureType, CopyExpr); 14423 14424 14425 return true; 14426 } 14427 14428 /// \brief Create a field within the lambda class for the variable 14429 /// being captured. 14430 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14431 QualType FieldType, QualType DeclRefType, 14432 SourceLocation Loc, 14433 bool RefersToCapturedVariable) { 14434 CXXRecordDecl *Lambda = LSI->Lambda; 14435 14436 // Build the non-static data member. 14437 FieldDecl *Field 14438 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14439 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14440 nullptr, false, ICIS_NoInit); 14441 Field->setImplicit(true); 14442 Field->setAccess(AS_private); 14443 Lambda->addDecl(Field); 14444 } 14445 14446 /// \brief Capture the given variable in the lambda. 14447 static bool captureInLambda(LambdaScopeInfo *LSI, 14448 VarDecl *Var, 14449 SourceLocation Loc, 14450 const bool BuildAndDiagnose, 14451 QualType &CaptureType, 14452 QualType &DeclRefType, 14453 const bool RefersToCapturedVariable, 14454 const Sema::TryCaptureKind Kind, 14455 SourceLocation EllipsisLoc, 14456 const bool IsTopScope, 14457 Sema &S) { 14458 14459 // Determine whether we are capturing by reference or by value. 14460 bool ByRef = false; 14461 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14462 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14463 } else { 14464 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14465 } 14466 14467 // Compute the type of the field that will capture this variable. 14468 if (ByRef) { 14469 // C++11 [expr.prim.lambda]p15: 14470 // An entity is captured by reference if it is implicitly or 14471 // explicitly captured but not captured by copy. It is 14472 // unspecified whether additional unnamed non-static data 14473 // members are declared in the closure type for entities 14474 // captured by reference. 14475 // 14476 // FIXME: It is not clear whether we want to build an lvalue reference 14477 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14478 // to do the former, while EDG does the latter. Core issue 1249 will 14479 // clarify, but for now we follow GCC because it's a more permissive and 14480 // easily defensible position. 14481 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14482 } else { 14483 // C++11 [expr.prim.lambda]p14: 14484 // For each entity captured by copy, an unnamed non-static 14485 // data member is declared in the closure type. The 14486 // declaration order of these members is unspecified. The type 14487 // of such a data member is the type of the corresponding 14488 // captured entity if the entity is not a reference to an 14489 // object, or the referenced type otherwise. [Note: If the 14490 // captured entity is a reference to a function, the 14491 // corresponding data member is also a reference to a 14492 // function. - end note ] 14493 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14494 if (!RefType->getPointeeType()->isFunctionType()) 14495 CaptureType = RefType->getPointeeType(); 14496 } 14497 14498 // Forbid the lambda copy-capture of autoreleasing variables. 14499 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14500 if (BuildAndDiagnose) { 14501 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14502 S.Diag(Var->getLocation(), diag::note_previous_decl) 14503 << Var->getDeclName(); 14504 } 14505 return false; 14506 } 14507 14508 // Make sure that by-copy captures are of a complete and non-abstract type. 14509 if (BuildAndDiagnose) { 14510 if (!CaptureType->isDependentType() && 14511 S.RequireCompleteType(Loc, CaptureType, 14512 diag::err_capture_of_incomplete_type, 14513 Var->getDeclName())) 14514 return false; 14515 14516 if (S.RequireNonAbstractType(Loc, CaptureType, 14517 diag::err_capture_of_abstract_type)) 14518 return false; 14519 } 14520 } 14521 14522 // Capture this variable in the lambda. 14523 if (BuildAndDiagnose) 14524 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14525 RefersToCapturedVariable); 14526 14527 // Compute the type of a reference to this captured variable. 14528 if (ByRef) 14529 DeclRefType = CaptureType.getNonReferenceType(); 14530 else { 14531 // C++ [expr.prim.lambda]p5: 14532 // The closure type for a lambda-expression has a public inline 14533 // function call operator [...]. This function call operator is 14534 // declared const (9.3.1) if and only if the lambda-expression's 14535 // parameter-declaration-clause is not followed by mutable. 14536 DeclRefType = CaptureType.getNonReferenceType(); 14537 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14538 DeclRefType.addConst(); 14539 } 14540 14541 // Add the capture. 14542 if (BuildAndDiagnose) 14543 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14544 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14545 14546 return true; 14547 } 14548 14549 bool Sema::tryCaptureVariable( 14550 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14551 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14552 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14553 // An init-capture is notionally from the context surrounding its 14554 // declaration, but its parent DC is the lambda class. 14555 DeclContext *VarDC = Var->getDeclContext(); 14556 if (Var->isInitCapture()) 14557 VarDC = VarDC->getParent(); 14558 14559 DeclContext *DC = CurContext; 14560 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14561 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14562 // We need to sync up the Declaration Context with the 14563 // FunctionScopeIndexToStopAt 14564 if (FunctionScopeIndexToStopAt) { 14565 unsigned FSIndex = FunctionScopes.size() - 1; 14566 while (FSIndex != MaxFunctionScopesIndex) { 14567 DC = getLambdaAwareParentOfDeclContext(DC); 14568 --FSIndex; 14569 } 14570 } 14571 14572 14573 // If the variable is declared in the current context, there is no need to 14574 // capture it. 14575 if (VarDC == DC) return true; 14576 14577 // Capture global variables if it is required to use private copy of this 14578 // variable. 14579 bool IsGlobal = !Var->hasLocalStorage(); 14580 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14581 return true; 14582 Var = Var->getCanonicalDecl(); 14583 14584 // Walk up the stack to determine whether we can capture the variable, 14585 // performing the "simple" checks that don't depend on type. We stop when 14586 // we've either hit the declared scope of the variable or find an existing 14587 // capture of that variable. We start from the innermost capturing-entity 14588 // (the DC) and ensure that all intervening capturing-entities 14589 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14590 // declcontext can either capture the variable or have already captured 14591 // the variable. 14592 CaptureType = Var->getType(); 14593 DeclRefType = CaptureType.getNonReferenceType(); 14594 bool Nested = false; 14595 bool Explicit = (Kind != TryCapture_Implicit); 14596 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14597 do { 14598 // Only block literals, captured statements, and lambda expressions can 14599 // capture; other scopes don't work. 14600 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14601 ExprLoc, 14602 BuildAndDiagnose, 14603 *this); 14604 // We need to check for the parent *first* because, if we *have* 14605 // private-captured a global variable, we need to recursively capture it in 14606 // intermediate blocks, lambdas, etc. 14607 if (!ParentDC) { 14608 if (IsGlobal) { 14609 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14610 break; 14611 } 14612 return true; 14613 } 14614 14615 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14616 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14617 14618 14619 // Check whether we've already captured it. 14620 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14621 DeclRefType)) { 14622 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14623 break; 14624 } 14625 // If we are instantiating a generic lambda call operator body, 14626 // we do not want to capture new variables. What was captured 14627 // during either a lambdas transformation or initial parsing 14628 // should be used. 14629 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14630 if (BuildAndDiagnose) { 14631 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14632 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14633 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14634 Diag(Var->getLocation(), diag::note_previous_decl) 14635 << Var->getDeclName(); 14636 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14637 } else 14638 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14639 } 14640 return true; 14641 } 14642 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14643 // certain types of variables (unnamed, variably modified types etc.) 14644 // so check for eligibility. 14645 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14646 return true; 14647 14648 // Try to capture variable-length arrays types. 14649 if (Var->getType()->isVariablyModifiedType()) { 14650 // We're going to walk down into the type and look for VLA 14651 // expressions. 14652 QualType QTy = Var->getType(); 14653 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14654 QTy = PVD->getOriginalType(); 14655 captureVariablyModifiedType(Context, QTy, CSI); 14656 } 14657 14658 if (getLangOpts().OpenMP) { 14659 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14660 // OpenMP private variables should not be captured in outer scope, so 14661 // just break here. Similarly, global variables that are captured in a 14662 // target region should not be captured outside the scope of the region. 14663 if (RSI->CapRegionKind == CR_OpenMP) { 14664 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 14665 auto IsTargetCap = !IsOpenMPPrivateDecl && 14666 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14667 // When we detect target captures we are looking from inside the 14668 // target region, therefore we need to propagate the capture from the 14669 // enclosing region. Therefore, the capture is not initially nested. 14670 if (IsTargetCap) 14671 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 14672 14673 if (IsTargetCap || IsOpenMPPrivateDecl) { 14674 Nested = !IsTargetCap; 14675 DeclRefType = DeclRefType.getUnqualifiedType(); 14676 CaptureType = Context.getLValueReferenceType(DeclRefType); 14677 break; 14678 } 14679 } 14680 } 14681 } 14682 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14683 // No capture-default, and this is not an explicit capture 14684 // so cannot capture this variable. 14685 if (BuildAndDiagnose) { 14686 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14687 Diag(Var->getLocation(), diag::note_previous_decl) 14688 << Var->getDeclName(); 14689 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14690 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14691 diag::note_lambda_decl); 14692 // FIXME: If we error out because an outer lambda can not implicitly 14693 // capture a variable that an inner lambda explicitly captures, we 14694 // should have the inner lambda do the explicit capture - because 14695 // it makes for cleaner diagnostics later. This would purely be done 14696 // so that the diagnostic does not misleadingly claim that a variable 14697 // can not be captured by a lambda implicitly even though it is captured 14698 // explicitly. Suggestion: 14699 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14700 // at the function head 14701 // - cache the StartingDeclContext - this must be a lambda 14702 // - captureInLambda in the innermost lambda the variable. 14703 } 14704 return true; 14705 } 14706 14707 FunctionScopesIndex--; 14708 DC = ParentDC; 14709 Explicit = false; 14710 } while (!VarDC->Equals(DC)); 14711 14712 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14713 // computing the type of the capture at each step, checking type-specific 14714 // requirements, and adding captures if requested. 14715 // If the variable had already been captured previously, we start capturing 14716 // at the lambda nested within that one. 14717 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14718 ++I) { 14719 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14720 14721 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14722 if (!captureInBlock(BSI, Var, ExprLoc, 14723 BuildAndDiagnose, CaptureType, 14724 DeclRefType, Nested, *this)) 14725 return true; 14726 Nested = true; 14727 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14728 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14729 BuildAndDiagnose, CaptureType, 14730 DeclRefType, Nested, *this)) 14731 return true; 14732 Nested = true; 14733 } else { 14734 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14735 if (!captureInLambda(LSI, Var, ExprLoc, 14736 BuildAndDiagnose, CaptureType, 14737 DeclRefType, Nested, Kind, EllipsisLoc, 14738 /*IsTopScope*/I == N - 1, *this)) 14739 return true; 14740 Nested = true; 14741 } 14742 } 14743 return false; 14744 } 14745 14746 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14747 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14748 QualType CaptureType; 14749 QualType DeclRefType; 14750 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14751 /*BuildAndDiagnose=*/true, CaptureType, 14752 DeclRefType, nullptr); 14753 } 14754 14755 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14756 QualType CaptureType; 14757 QualType DeclRefType; 14758 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14759 /*BuildAndDiagnose=*/false, CaptureType, 14760 DeclRefType, nullptr); 14761 } 14762 14763 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14764 QualType CaptureType; 14765 QualType DeclRefType; 14766 14767 // Determine whether we can capture this variable. 14768 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14769 /*BuildAndDiagnose=*/false, CaptureType, 14770 DeclRefType, nullptr)) 14771 return QualType(); 14772 14773 return DeclRefType; 14774 } 14775 14776 14777 14778 // If either the type of the variable or the initializer is dependent, 14779 // return false. Otherwise, determine whether the variable is a constant 14780 // expression. Use this if you need to know if a variable that might or 14781 // might not be dependent is truly a constant expression. 14782 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14783 ASTContext &Context) { 14784 14785 if (Var->getType()->isDependentType()) 14786 return false; 14787 const VarDecl *DefVD = nullptr; 14788 Var->getAnyInitializer(DefVD); 14789 if (!DefVD) 14790 return false; 14791 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14792 Expr *Init = cast<Expr>(Eval->Value); 14793 if (Init->isValueDependent()) 14794 return false; 14795 return IsVariableAConstantExpression(Var, Context); 14796 } 14797 14798 14799 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14800 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14801 // an object that satisfies the requirements for appearing in a 14802 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14803 // is immediately applied." This function handles the lvalue-to-rvalue 14804 // conversion part. 14805 MaybeODRUseExprs.erase(E->IgnoreParens()); 14806 14807 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14808 // to a variable that is a constant expression, and if so, identify it as 14809 // a reference to a variable that does not involve an odr-use of that 14810 // variable. 14811 if (LambdaScopeInfo *LSI = getCurLambda()) { 14812 Expr *SansParensExpr = E->IgnoreParens(); 14813 VarDecl *Var = nullptr; 14814 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14815 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14816 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14817 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14818 14819 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14820 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14821 } 14822 } 14823 14824 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14825 Res = CorrectDelayedTyposInExpr(Res); 14826 14827 if (!Res.isUsable()) 14828 return Res; 14829 14830 // If a constant-expression is a reference to a variable where we delay 14831 // deciding whether it is an odr-use, just assume we will apply the 14832 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14833 // (a non-type template argument), we have special handling anyway. 14834 UpdateMarkingForLValueToRValue(Res.get()); 14835 return Res; 14836 } 14837 14838 void Sema::CleanupVarDeclMarking() { 14839 for (Expr *E : MaybeODRUseExprs) { 14840 VarDecl *Var; 14841 SourceLocation Loc; 14842 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14843 Var = cast<VarDecl>(DRE->getDecl()); 14844 Loc = DRE->getLocation(); 14845 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14846 Var = cast<VarDecl>(ME->getMemberDecl()); 14847 Loc = ME->getMemberLoc(); 14848 } else { 14849 llvm_unreachable("Unexpected expression"); 14850 } 14851 14852 MarkVarDeclODRUsed(Var, Loc, *this, 14853 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14854 } 14855 14856 MaybeODRUseExprs.clear(); 14857 } 14858 14859 14860 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14861 VarDecl *Var, Expr *E) { 14862 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14863 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14864 Var->setReferenced(); 14865 14866 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14867 14868 bool OdrUseContext = isOdrUseContext(SemaRef); 14869 bool UsableInConstantExpr = 14870 Var->isUsableInConstantExpressions(SemaRef.Context); 14871 bool NeedDefinition = 14872 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 14873 14874 VarTemplateSpecializationDecl *VarSpec = 14875 dyn_cast<VarTemplateSpecializationDecl>(Var); 14876 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14877 "Can't instantiate a partial template specialization."); 14878 14879 // If this might be a member specialization of a static data member, check 14880 // the specialization is visible. We already did the checks for variable 14881 // template specializations when we created them. 14882 if (NeedDefinition && TSK != TSK_Undeclared && 14883 !isa<VarTemplateSpecializationDecl>(Var)) 14884 SemaRef.checkSpecializationVisibility(Loc, Var); 14885 14886 // Perform implicit instantiation of static data members, static data member 14887 // templates of class templates, and variable template specializations. Delay 14888 // instantiations of variable templates, except for those that could be used 14889 // in a constant expression. 14890 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14891 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 14892 // instantiation declaration if a variable is usable in a constant 14893 // expression (among other cases). 14894 bool TryInstantiating = 14895 TSK == TSK_ImplicitInstantiation || 14896 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 14897 14898 if (TryInstantiating) { 14899 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14900 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14901 if (FirstInstantiation) { 14902 PointOfInstantiation = Loc; 14903 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14904 } 14905 14906 bool InstantiationDependent = false; 14907 bool IsNonDependent = 14908 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14909 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14910 : true; 14911 14912 // Do not instantiate specializations that are still type-dependent. 14913 if (IsNonDependent) { 14914 if (UsableInConstantExpr) { 14915 // Do not defer instantiations of variables that could be used in a 14916 // constant expression. 14917 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14918 } else if (FirstInstantiation || 14919 isa<VarTemplateSpecializationDecl>(Var)) { 14920 // FIXME: For a specialization of a variable template, we don't 14921 // distinguish between "declaration and type implicitly instantiated" 14922 // and "implicit instantiation of definition requested", so we have 14923 // no direct way to avoid enqueueing the pending instantiation 14924 // multiple times. 14925 SemaRef.PendingInstantiations 14926 .push_back(std::make_pair(Var, PointOfInstantiation)); 14927 } 14928 } 14929 } 14930 } 14931 14932 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14933 // the requirements for appearing in a constant expression (5.19) and, if 14934 // it is an object, the lvalue-to-rvalue conversion (4.1) 14935 // is immediately applied." We check the first part here, and 14936 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14937 // Note that we use the C++11 definition everywhere because nothing in 14938 // C++03 depends on whether we get the C++03 version correct. The second 14939 // part does not apply to references, since they are not objects. 14940 if (OdrUseContext && E && 14941 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14942 // A reference initialized by a constant expression can never be 14943 // odr-used, so simply ignore it. 14944 if (!Var->getType()->isReferenceType() || 14945 (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var))) 14946 SemaRef.MaybeODRUseExprs.insert(E); 14947 } else if (OdrUseContext) { 14948 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14949 /*MaxFunctionScopeIndex ptr*/ nullptr); 14950 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14951 // If this is a dependent context, we don't need to mark variables as 14952 // odr-used, but we may still need to track them for lambda capture. 14953 // FIXME: Do we also need to do this inside dependent typeid expressions 14954 // (which are modeled as unevaluated at this point)? 14955 const bool RefersToEnclosingScope = 14956 (SemaRef.CurContext != Var->getDeclContext() && 14957 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14958 if (RefersToEnclosingScope) { 14959 LambdaScopeInfo *const LSI = 14960 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14961 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14962 // If a variable could potentially be odr-used, defer marking it so 14963 // until we finish analyzing the full expression for any 14964 // lvalue-to-rvalue 14965 // or discarded value conversions that would obviate odr-use. 14966 // Add it to the list of potential captures that will be analyzed 14967 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14968 // unless the variable is a reference that was initialized by a constant 14969 // expression (this will never need to be captured or odr-used). 14970 assert(E && "Capture variable should be used in an expression."); 14971 if (!Var->getType()->isReferenceType() || 14972 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14973 LSI->addPotentialCapture(E->IgnoreParens()); 14974 } 14975 } 14976 } 14977 } 14978 14979 /// \brief Mark a variable referenced, and check whether it is odr-used 14980 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14981 /// used directly for normal expressions referring to VarDecl. 14982 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14983 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14984 } 14985 14986 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14987 Decl *D, Expr *E, bool MightBeOdrUse) { 14988 if (SemaRef.isInOpenMPDeclareTargetContext()) 14989 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14990 14991 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14992 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14993 return; 14994 } 14995 14996 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14997 14998 // If this is a call to a method via a cast, also mark the method in the 14999 // derived class used in case codegen can devirtualize the call. 15000 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15001 if (!ME) 15002 return; 15003 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15004 if (!MD) 15005 return; 15006 // Only attempt to devirtualize if this is truly a virtual call. 15007 bool IsVirtualCall = MD->isVirtual() && 15008 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15009 if (!IsVirtualCall) 15010 return; 15011 15012 // If it's possible to devirtualize the call, mark the called function 15013 // referenced. 15014 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15015 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15016 if (DM) 15017 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15018 } 15019 15020 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 15021 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15022 // TODO: update this with DR# once a defect report is filed. 15023 // C++11 defect. The address of a pure member should not be an ODR use, even 15024 // if it's a qualified reference. 15025 bool OdrUse = true; 15026 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15027 if (Method->isVirtual() && 15028 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15029 OdrUse = false; 15030 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15031 } 15032 15033 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 15034 void Sema::MarkMemberReferenced(MemberExpr *E) { 15035 // C++11 [basic.def.odr]p2: 15036 // A non-overloaded function whose name appears as a potentially-evaluated 15037 // expression or a member of a set of candidate functions, if selected by 15038 // overload resolution when referred to from a potentially-evaluated 15039 // expression, is odr-used, unless it is a pure virtual function and its 15040 // name is not explicitly qualified. 15041 bool MightBeOdrUse = true; 15042 if (E->performsVirtualDispatch(getLangOpts())) { 15043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15044 if (Method->isPure()) 15045 MightBeOdrUse = false; 15046 } 15047 SourceLocation Loc = E->getMemberLoc().isValid() ? 15048 E->getMemberLoc() : E->getLocStart(); 15049 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15050 } 15051 15052 /// \brief Perform marking for a reference to an arbitrary declaration. It 15053 /// marks the declaration referenced, and performs odr-use checking for 15054 /// functions and variables. This method should not be used when building a 15055 /// normal expression which refers to a variable. 15056 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15057 bool MightBeOdrUse) { 15058 if (MightBeOdrUse) { 15059 if (auto *VD = dyn_cast<VarDecl>(D)) { 15060 MarkVariableReferenced(Loc, VD); 15061 return; 15062 } 15063 } 15064 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15065 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15066 return; 15067 } 15068 D->setReferenced(); 15069 } 15070 15071 namespace { 15072 // Mark all of the declarations used by a type as referenced. 15073 // FIXME: Not fully implemented yet! We need to have a better understanding 15074 // of when we're entering a context we should not recurse into. 15075 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15076 // TreeTransforms rebuilding the type in a new context. Rather than 15077 // duplicating the TreeTransform logic, we should consider reusing it here. 15078 // Currently that causes problems when rebuilding LambdaExprs. 15079 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15080 Sema &S; 15081 SourceLocation Loc; 15082 15083 public: 15084 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15085 15086 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15087 15088 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15089 }; 15090 } 15091 15092 bool MarkReferencedDecls::TraverseTemplateArgument( 15093 const TemplateArgument &Arg) { 15094 { 15095 // A non-type template argument is a constant-evaluated context. 15096 EnterExpressionEvaluationContext Evaluated( 15097 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15098 if (Arg.getKind() == TemplateArgument::Declaration) { 15099 if (Decl *D = Arg.getAsDecl()) 15100 S.MarkAnyDeclReferenced(Loc, D, true); 15101 } else if (Arg.getKind() == TemplateArgument::Expression) { 15102 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15103 } 15104 } 15105 15106 return Inherited::TraverseTemplateArgument(Arg); 15107 } 15108 15109 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15110 MarkReferencedDecls Marker(*this, Loc); 15111 Marker.TraverseType(T); 15112 } 15113 15114 namespace { 15115 /// \brief Helper class that marks all of the declarations referenced by 15116 /// potentially-evaluated subexpressions as "referenced". 15117 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15118 Sema &S; 15119 bool SkipLocalVariables; 15120 15121 public: 15122 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15123 15124 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15125 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15126 15127 void VisitDeclRefExpr(DeclRefExpr *E) { 15128 // If we were asked not to visit local variables, don't. 15129 if (SkipLocalVariables) { 15130 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15131 if (VD->hasLocalStorage()) 15132 return; 15133 } 15134 15135 S.MarkDeclRefReferenced(E); 15136 } 15137 15138 void VisitMemberExpr(MemberExpr *E) { 15139 S.MarkMemberReferenced(E); 15140 Inherited::VisitMemberExpr(E); 15141 } 15142 15143 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15144 S.MarkFunctionReferenced(E->getLocStart(), 15145 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15146 Visit(E->getSubExpr()); 15147 } 15148 15149 void VisitCXXNewExpr(CXXNewExpr *E) { 15150 if (E->getOperatorNew()) 15151 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15152 if (E->getOperatorDelete()) 15153 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15154 Inherited::VisitCXXNewExpr(E); 15155 } 15156 15157 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15158 if (E->getOperatorDelete()) 15159 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15160 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15161 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15162 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15163 S.MarkFunctionReferenced(E->getLocStart(), 15164 S.LookupDestructor(Record)); 15165 } 15166 15167 Inherited::VisitCXXDeleteExpr(E); 15168 } 15169 15170 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15171 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15172 Inherited::VisitCXXConstructExpr(E); 15173 } 15174 15175 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15176 Visit(E->getExpr()); 15177 } 15178 15179 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15180 Inherited::VisitImplicitCastExpr(E); 15181 15182 if (E->getCastKind() == CK_LValueToRValue) 15183 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15184 } 15185 }; 15186 } 15187 15188 /// \brief Mark any declarations that appear within this expression or any 15189 /// potentially-evaluated subexpressions as "referenced". 15190 /// 15191 /// \param SkipLocalVariables If true, don't mark local variables as 15192 /// 'referenced'. 15193 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15194 bool SkipLocalVariables) { 15195 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15196 } 15197 15198 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15199 /// of the program being compiled. 15200 /// 15201 /// This routine emits the given diagnostic when the code currently being 15202 /// type-checked is "potentially evaluated", meaning that there is a 15203 /// possibility that the code will actually be executable. Code in sizeof() 15204 /// expressions, code used only during overload resolution, etc., are not 15205 /// potentially evaluated. This routine will suppress such diagnostics or, 15206 /// in the absolutely nutty case of potentially potentially evaluated 15207 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15208 /// later. 15209 /// 15210 /// This routine should be used for all diagnostics that describe the run-time 15211 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15212 /// Failure to do so will likely result in spurious diagnostics or failures 15213 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15214 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15215 const PartialDiagnostic &PD) { 15216 switch (ExprEvalContexts.back().Context) { 15217 case ExpressionEvaluationContext::Unevaluated: 15218 case ExpressionEvaluationContext::UnevaluatedList: 15219 case ExpressionEvaluationContext::UnevaluatedAbstract: 15220 case ExpressionEvaluationContext::DiscardedStatement: 15221 // The argument will never be evaluated, so don't complain. 15222 break; 15223 15224 case ExpressionEvaluationContext::ConstantEvaluated: 15225 // Relevant diagnostics should be produced by constant evaluation. 15226 break; 15227 15228 case ExpressionEvaluationContext::PotentiallyEvaluated: 15229 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15230 if (Statement && getCurFunctionOrMethodDecl()) { 15231 FunctionScopes.back()->PossiblyUnreachableDiags. 15232 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15233 return true; 15234 } 15235 15236 // The initializer of a constexpr variable or of the first declaration of a 15237 // static data member is not syntactically a constant evaluated constant, 15238 // but nonetheless is always required to be a constant expression, so we 15239 // can skip diagnosing. 15240 // FIXME: Using the mangling context here is a hack. 15241 if (auto *VD = dyn_cast_or_null<VarDecl>( 15242 ExprEvalContexts.back().ManglingContextDecl)) { 15243 if (VD->isConstexpr() || 15244 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15245 break; 15246 // FIXME: For any other kind of variable, we should build a CFG for its 15247 // initializer and check whether the context in question is reachable. 15248 } 15249 15250 Diag(Loc, PD); 15251 return true; 15252 } 15253 15254 return false; 15255 } 15256 15257 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15258 CallExpr *CE, FunctionDecl *FD) { 15259 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15260 return false; 15261 15262 // If we're inside a decltype's expression, don't check for a valid return 15263 // type or construct temporaries until we know whether this is the last call. 15264 if (ExprEvalContexts.back().IsDecltype) { 15265 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15266 return false; 15267 } 15268 15269 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15270 FunctionDecl *FD; 15271 CallExpr *CE; 15272 15273 public: 15274 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15275 : FD(FD), CE(CE) { } 15276 15277 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15278 if (!FD) { 15279 S.Diag(Loc, diag::err_call_incomplete_return) 15280 << T << CE->getSourceRange(); 15281 return; 15282 } 15283 15284 S.Diag(Loc, diag::err_call_function_incomplete_return) 15285 << CE->getSourceRange() << FD->getDeclName() << T; 15286 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15287 << FD->getDeclName(); 15288 } 15289 } Diagnoser(FD, CE); 15290 15291 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15292 return true; 15293 15294 return false; 15295 } 15296 15297 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15298 // will prevent this condition from triggering, which is what we want. 15299 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15300 SourceLocation Loc; 15301 15302 unsigned diagnostic = diag::warn_condition_is_assignment; 15303 bool IsOrAssign = false; 15304 15305 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15306 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15307 return; 15308 15309 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15310 15311 // Greylist some idioms by putting them into a warning subcategory. 15312 if (ObjCMessageExpr *ME 15313 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15314 Selector Sel = ME->getSelector(); 15315 15316 // self = [<foo> init...] 15317 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15318 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15319 15320 // <foo> = [<bar> nextObject] 15321 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15322 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15323 } 15324 15325 Loc = Op->getOperatorLoc(); 15326 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15327 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15328 return; 15329 15330 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15331 Loc = Op->getOperatorLoc(); 15332 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15333 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15334 else { 15335 // Not an assignment. 15336 return; 15337 } 15338 15339 Diag(Loc, diagnostic) << E->getSourceRange(); 15340 15341 SourceLocation Open = E->getLocStart(); 15342 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15343 Diag(Loc, diag::note_condition_assign_silence) 15344 << FixItHint::CreateInsertion(Open, "(") 15345 << FixItHint::CreateInsertion(Close, ")"); 15346 15347 if (IsOrAssign) 15348 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15349 << FixItHint::CreateReplacement(Loc, "!="); 15350 else 15351 Diag(Loc, diag::note_condition_assign_to_comparison) 15352 << FixItHint::CreateReplacement(Loc, "=="); 15353 } 15354 15355 /// \brief Redundant parentheses over an equality comparison can indicate 15356 /// that the user intended an assignment used as condition. 15357 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15358 // Don't warn if the parens came from a macro. 15359 SourceLocation parenLoc = ParenE->getLocStart(); 15360 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15361 return; 15362 // Don't warn for dependent expressions. 15363 if (ParenE->isTypeDependent()) 15364 return; 15365 15366 Expr *E = ParenE->IgnoreParens(); 15367 15368 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15369 if (opE->getOpcode() == BO_EQ && 15370 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15371 == Expr::MLV_Valid) { 15372 SourceLocation Loc = opE->getOperatorLoc(); 15373 15374 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15375 SourceRange ParenERange = ParenE->getSourceRange(); 15376 Diag(Loc, diag::note_equality_comparison_silence) 15377 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15378 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15379 Diag(Loc, diag::note_equality_comparison_to_assign) 15380 << FixItHint::CreateReplacement(Loc, "="); 15381 } 15382 } 15383 15384 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15385 bool IsConstexpr) { 15386 DiagnoseAssignmentAsCondition(E); 15387 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15388 DiagnoseEqualityWithExtraParens(parenE); 15389 15390 ExprResult result = CheckPlaceholderExpr(E); 15391 if (result.isInvalid()) return ExprError(); 15392 E = result.get(); 15393 15394 if (!E->isTypeDependent()) { 15395 if (getLangOpts().CPlusPlus) 15396 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15397 15398 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15399 if (ERes.isInvalid()) 15400 return ExprError(); 15401 E = ERes.get(); 15402 15403 QualType T = E->getType(); 15404 if (!T->isScalarType()) { // C99 6.8.4.1p1 15405 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15406 << T << E->getSourceRange(); 15407 return ExprError(); 15408 } 15409 CheckBoolLikeConversion(E, Loc); 15410 } 15411 15412 return E; 15413 } 15414 15415 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15416 Expr *SubExpr, ConditionKind CK) { 15417 // Empty conditions are valid in for-statements. 15418 if (!SubExpr) 15419 return ConditionResult(); 15420 15421 ExprResult Cond; 15422 switch (CK) { 15423 case ConditionKind::Boolean: 15424 Cond = CheckBooleanCondition(Loc, SubExpr); 15425 break; 15426 15427 case ConditionKind::ConstexprIf: 15428 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15429 break; 15430 15431 case ConditionKind::Switch: 15432 Cond = CheckSwitchCondition(Loc, SubExpr); 15433 break; 15434 } 15435 if (Cond.isInvalid()) 15436 return ConditionError(); 15437 15438 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15439 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15440 if (!FullExpr.get()) 15441 return ConditionError(); 15442 15443 return ConditionResult(*this, nullptr, FullExpr, 15444 CK == ConditionKind::ConstexprIf); 15445 } 15446 15447 namespace { 15448 /// A visitor for rebuilding a call to an __unknown_any expression 15449 /// to have an appropriate type. 15450 struct RebuildUnknownAnyFunction 15451 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15452 15453 Sema &S; 15454 15455 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15456 15457 ExprResult VisitStmt(Stmt *S) { 15458 llvm_unreachable("unexpected statement!"); 15459 } 15460 15461 ExprResult VisitExpr(Expr *E) { 15462 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15463 << E->getSourceRange(); 15464 return ExprError(); 15465 } 15466 15467 /// Rebuild an expression which simply semantically wraps another 15468 /// expression which it shares the type and value kind of. 15469 template <class T> ExprResult rebuildSugarExpr(T *E) { 15470 ExprResult SubResult = Visit(E->getSubExpr()); 15471 if (SubResult.isInvalid()) return ExprError(); 15472 15473 Expr *SubExpr = SubResult.get(); 15474 E->setSubExpr(SubExpr); 15475 E->setType(SubExpr->getType()); 15476 E->setValueKind(SubExpr->getValueKind()); 15477 assert(E->getObjectKind() == OK_Ordinary); 15478 return E; 15479 } 15480 15481 ExprResult VisitParenExpr(ParenExpr *E) { 15482 return rebuildSugarExpr(E); 15483 } 15484 15485 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15486 return rebuildSugarExpr(E); 15487 } 15488 15489 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15490 ExprResult SubResult = Visit(E->getSubExpr()); 15491 if (SubResult.isInvalid()) return ExprError(); 15492 15493 Expr *SubExpr = SubResult.get(); 15494 E->setSubExpr(SubExpr); 15495 E->setType(S.Context.getPointerType(SubExpr->getType())); 15496 assert(E->getValueKind() == VK_RValue); 15497 assert(E->getObjectKind() == OK_Ordinary); 15498 return E; 15499 } 15500 15501 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15502 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15503 15504 E->setType(VD->getType()); 15505 15506 assert(E->getValueKind() == VK_RValue); 15507 if (S.getLangOpts().CPlusPlus && 15508 !(isa<CXXMethodDecl>(VD) && 15509 cast<CXXMethodDecl>(VD)->isInstance())) 15510 E->setValueKind(VK_LValue); 15511 15512 return E; 15513 } 15514 15515 ExprResult VisitMemberExpr(MemberExpr *E) { 15516 return resolveDecl(E, E->getMemberDecl()); 15517 } 15518 15519 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15520 return resolveDecl(E, E->getDecl()); 15521 } 15522 }; 15523 } 15524 15525 /// Given a function expression of unknown-any type, try to rebuild it 15526 /// to have a function type. 15527 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15528 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15529 if (Result.isInvalid()) return ExprError(); 15530 return S.DefaultFunctionArrayConversion(Result.get()); 15531 } 15532 15533 namespace { 15534 /// A visitor for rebuilding an expression of type __unknown_anytype 15535 /// into one which resolves the type directly on the referring 15536 /// expression. Strict preservation of the original source 15537 /// structure is not a goal. 15538 struct RebuildUnknownAnyExpr 15539 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15540 15541 Sema &S; 15542 15543 /// The current destination type. 15544 QualType DestType; 15545 15546 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15547 : S(S), DestType(CastType) {} 15548 15549 ExprResult VisitStmt(Stmt *S) { 15550 llvm_unreachable("unexpected statement!"); 15551 } 15552 15553 ExprResult VisitExpr(Expr *E) { 15554 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15555 << E->getSourceRange(); 15556 return ExprError(); 15557 } 15558 15559 ExprResult VisitCallExpr(CallExpr *E); 15560 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15561 15562 /// Rebuild an expression which simply semantically wraps another 15563 /// expression which it shares the type and value kind of. 15564 template <class T> ExprResult rebuildSugarExpr(T *E) { 15565 ExprResult SubResult = Visit(E->getSubExpr()); 15566 if (SubResult.isInvalid()) return ExprError(); 15567 Expr *SubExpr = SubResult.get(); 15568 E->setSubExpr(SubExpr); 15569 E->setType(SubExpr->getType()); 15570 E->setValueKind(SubExpr->getValueKind()); 15571 assert(E->getObjectKind() == OK_Ordinary); 15572 return E; 15573 } 15574 15575 ExprResult VisitParenExpr(ParenExpr *E) { 15576 return rebuildSugarExpr(E); 15577 } 15578 15579 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15580 return rebuildSugarExpr(E); 15581 } 15582 15583 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15584 const PointerType *Ptr = DestType->getAs<PointerType>(); 15585 if (!Ptr) { 15586 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15587 << E->getSourceRange(); 15588 return ExprError(); 15589 } 15590 15591 if (isa<CallExpr>(E->getSubExpr())) { 15592 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15593 << E->getSourceRange(); 15594 return ExprError(); 15595 } 15596 15597 assert(E->getValueKind() == VK_RValue); 15598 assert(E->getObjectKind() == OK_Ordinary); 15599 E->setType(DestType); 15600 15601 // Build the sub-expression as if it were an object of the pointee type. 15602 DestType = Ptr->getPointeeType(); 15603 ExprResult SubResult = Visit(E->getSubExpr()); 15604 if (SubResult.isInvalid()) return ExprError(); 15605 E->setSubExpr(SubResult.get()); 15606 return E; 15607 } 15608 15609 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15610 15611 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15612 15613 ExprResult VisitMemberExpr(MemberExpr *E) { 15614 return resolveDecl(E, E->getMemberDecl()); 15615 } 15616 15617 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15618 return resolveDecl(E, E->getDecl()); 15619 } 15620 }; 15621 } 15622 15623 /// Rebuilds a call expression which yielded __unknown_anytype. 15624 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15625 Expr *CalleeExpr = E->getCallee(); 15626 15627 enum FnKind { 15628 FK_MemberFunction, 15629 FK_FunctionPointer, 15630 FK_BlockPointer 15631 }; 15632 15633 FnKind Kind; 15634 QualType CalleeType = CalleeExpr->getType(); 15635 if (CalleeType == S.Context.BoundMemberTy) { 15636 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15637 Kind = FK_MemberFunction; 15638 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15639 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15640 CalleeType = Ptr->getPointeeType(); 15641 Kind = FK_FunctionPointer; 15642 } else { 15643 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15644 Kind = FK_BlockPointer; 15645 } 15646 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15647 15648 // Verify that this is a legal result type of a function. 15649 if (DestType->isArrayType() || DestType->isFunctionType()) { 15650 unsigned diagID = diag::err_func_returning_array_function; 15651 if (Kind == FK_BlockPointer) 15652 diagID = diag::err_block_returning_array_function; 15653 15654 S.Diag(E->getExprLoc(), diagID) 15655 << DestType->isFunctionType() << DestType; 15656 return ExprError(); 15657 } 15658 15659 // Otherwise, go ahead and set DestType as the call's result. 15660 E->setType(DestType.getNonLValueExprType(S.Context)); 15661 E->setValueKind(Expr::getValueKindForType(DestType)); 15662 assert(E->getObjectKind() == OK_Ordinary); 15663 15664 // Rebuild the function type, replacing the result type with DestType. 15665 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15666 if (Proto) { 15667 // __unknown_anytype(...) is a special case used by the debugger when 15668 // it has no idea what a function's signature is. 15669 // 15670 // We want to build this call essentially under the K&R 15671 // unprototyped rules, but making a FunctionNoProtoType in C++ 15672 // would foul up all sorts of assumptions. However, we cannot 15673 // simply pass all arguments as variadic arguments, nor can we 15674 // portably just call the function under a non-variadic type; see 15675 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15676 // However, it turns out that in practice it is generally safe to 15677 // call a function declared as "A foo(B,C,D);" under the prototype 15678 // "A foo(B,C,D,...);". The only known exception is with the 15679 // Windows ABI, where any variadic function is implicitly cdecl 15680 // regardless of its normal CC. Therefore we change the parameter 15681 // types to match the types of the arguments. 15682 // 15683 // This is a hack, but it is far superior to moving the 15684 // corresponding target-specific code from IR-gen to Sema/AST. 15685 15686 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15687 SmallVector<QualType, 8> ArgTypes; 15688 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15689 ArgTypes.reserve(E->getNumArgs()); 15690 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15691 Expr *Arg = E->getArg(i); 15692 QualType ArgType = Arg->getType(); 15693 if (E->isLValue()) { 15694 ArgType = S.Context.getLValueReferenceType(ArgType); 15695 } else if (E->isXValue()) { 15696 ArgType = S.Context.getRValueReferenceType(ArgType); 15697 } 15698 ArgTypes.push_back(ArgType); 15699 } 15700 ParamTypes = ArgTypes; 15701 } 15702 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15703 Proto->getExtProtoInfo()); 15704 } else { 15705 DestType = S.Context.getFunctionNoProtoType(DestType, 15706 FnType->getExtInfo()); 15707 } 15708 15709 // Rebuild the appropriate pointer-to-function type. 15710 switch (Kind) { 15711 case FK_MemberFunction: 15712 // Nothing to do. 15713 break; 15714 15715 case FK_FunctionPointer: 15716 DestType = S.Context.getPointerType(DestType); 15717 break; 15718 15719 case FK_BlockPointer: 15720 DestType = S.Context.getBlockPointerType(DestType); 15721 break; 15722 } 15723 15724 // Finally, we can recurse. 15725 ExprResult CalleeResult = Visit(CalleeExpr); 15726 if (!CalleeResult.isUsable()) return ExprError(); 15727 E->setCallee(CalleeResult.get()); 15728 15729 // Bind a temporary if necessary. 15730 return S.MaybeBindToTemporary(E); 15731 } 15732 15733 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15734 // Verify that this is a legal result type of a call. 15735 if (DestType->isArrayType() || DestType->isFunctionType()) { 15736 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15737 << DestType->isFunctionType() << DestType; 15738 return ExprError(); 15739 } 15740 15741 // Rewrite the method result type if available. 15742 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15743 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15744 Method->setReturnType(DestType); 15745 } 15746 15747 // Change the type of the message. 15748 E->setType(DestType.getNonReferenceType()); 15749 E->setValueKind(Expr::getValueKindForType(DestType)); 15750 15751 return S.MaybeBindToTemporary(E); 15752 } 15753 15754 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15755 // The only case we should ever see here is a function-to-pointer decay. 15756 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15757 assert(E->getValueKind() == VK_RValue); 15758 assert(E->getObjectKind() == OK_Ordinary); 15759 15760 E->setType(DestType); 15761 15762 // Rebuild the sub-expression as the pointee (function) type. 15763 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15764 15765 ExprResult Result = Visit(E->getSubExpr()); 15766 if (!Result.isUsable()) return ExprError(); 15767 15768 E->setSubExpr(Result.get()); 15769 return E; 15770 } else if (E->getCastKind() == CK_LValueToRValue) { 15771 assert(E->getValueKind() == VK_RValue); 15772 assert(E->getObjectKind() == OK_Ordinary); 15773 15774 assert(isa<BlockPointerType>(E->getType())); 15775 15776 E->setType(DestType); 15777 15778 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15779 DestType = S.Context.getLValueReferenceType(DestType); 15780 15781 ExprResult Result = Visit(E->getSubExpr()); 15782 if (!Result.isUsable()) return ExprError(); 15783 15784 E->setSubExpr(Result.get()); 15785 return E; 15786 } else { 15787 llvm_unreachable("Unhandled cast type!"); 15788 } 15789 } 15790 15791 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15792 ExprValueKind ValueKind = VK_LValue; 15793 QualType Type = DestType; 15794 15795 // We know how to make this work for certain kinds of decls: 15796 15797 // - functions 15798 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15799 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15800 DestType = Ptr->getPointeeType(); 15801 ExprResult Result = resolveDecl(E, VD); 15802 if (Result.isInvalid()) return ExprError(); 15803 return S.ImpCastExprToType(Result.get(), Type, 15804 CK_FunctionToPointerDecay, VK_RValue); 15805 } 15806 15807 if (!Type->isFunctionType()) { 15808 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15809 << VD << E->getSourceRange(); 15810 return ExprError(); 15811 } 15812 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15813 // We must match the FunctionDecl's type to the hack introduced in 15814 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15815 // type. See the lengthy commentary in that routine. 15816 QualType FDT = FD->getType(); 15817 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15818 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15819 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15820 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15821 SourceLocation Loc = FD->getLocation(); 15822 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15823 FD->getDeclContext(), 15824 Loc, Loc, FD->getNameInfo().getName(), 15825 DestType, FD->getTypeSourceInfo(), 15826 SC_None, false/*isInlineSpecified*/, 15827 FD->hasPrototype(), 15828 false/*isConstexprSpecified*/); 15829 15830 if (FD->getQualifier()) 15831 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15832 15833 SmallVector<ParmVarDecl*, 16> Params; 15834 for (const auto &AI : FT->param_types()) { 15835 ParmVarDecl *Param = 15836 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15837 Param->setScopeInfo(0, Params.size()); 15838 Params.push_back(Param); 15839 } 15840 NewFD->setParams(Params); 15841 DRE->setDecl(NewFD); 15842 VD = DRE->getDecl(); 15843 } 15844 } 15845 15846 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15847 if (MD->isInstance()) { 15848 ValueKind = VK_RValue; 15849 Type = S.Context.BoundMemberTy; 15850 } 15851 15852 // Function references aren't l-values in C. 15853 if (!S.getLangOpts().CPlusPlus) 15854 ValueKind = VK_RValue; 15855 15856 // - variables 15857 } else if (isa<VarDecl>(VD)) { 15858 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15859 Type = RefTy->getPointeeType(); 15860 } else if (Type->isFunctionType()) { 15861 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15862 << VD << E->getSourceRange(); 15863 return ExprError(); 15864 } 15865 15866 // - nothing else 15867 } else { 15868 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15869 << VD << E->getSourceRange(); 15870 return ExprError(); 15871 } 15872 15873 // Modifying the declaration like this is friendly to IR-gen but 15874 // also really dangerous. 15875 VD->setType(DestType); 15876 E->setType(Type); 15877 E->setValueKind(ValueKind); 15878 return E; 15879 } 15880 15881 /// Check a cast of an unknown-any type. We intentionally only 15882 /// trigger this for C-style casts. 15883 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15884 Expr *CastExpr, CastKind &CastKind, 15885 ExprValueKind &VK, CXXCastPath &Path) { 15886 // The type we're casting to must be either void or complete. 15887 if (!CastType->isVoidType() && 15888 RequireCompleteType(TypeRange.getBegin(), CastType, 15889 diag::err_typecheck_cast_to_incomplete)) 15890 return ExprError(); 15891 15892 // Rewrite the casted expression from scratch. 15893 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15894 if (!result.isUsable()) return ExprError(); 15895 15896 CastExpr = result.get(); 15897 VK = CastExpr->getValueKind(); 15898 CastKind = CK_NoOp; 15899 15900 return CastExpr; 15901 } 15902 15903 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15904 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15905 } 15906 15907 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15908 Expr *arg, QualType ¶mType) { 15909 // If the syntactic form of the argument is not an explicit cast of 15910 // any sort, just do default argument promotion. 15911 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15912 if (!castArg) { 15913 ExprResult result = DefaultArgumentPromotion(arg); 15914 if (result.isInvalid()) return ExprError(); 15915 paramType = result.get()->getType(); 15916 return result; 15917 } 15918 15919 // Otherwise, use the type that was written in the explicit cast. 15920 assert(!arg->hasPlaceholderType()); 15921 paramType = castArg->getTypeAsWritten(); 15922 15923 // Copy-initialize a parameter of that type. 15924 InitializedEntity entity = 15925 InitializedEntity::InitializeParameter(Context, paramType, 15926 /*consumed*/ false); 15927 return PerformCopyInitialization(entity, callLoc, arg); 15928 } 15929 15930 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15931 Expr *orig = E; 15932 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15933 while (true) { 15934 E = E->IgnoreParenImpCasts(); 15935 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15936 E = call->getCallee(); 15937 diagID = diag::err_uncasted_call_of_unknown_any; 15938 } else { 15939 break; 15940 } 15941 } 15942 15943 SourceLocation loc; 15944 NamedDecl *d; 15945 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15946 loc = ref->getLocation(); 15947 d = ref->getDecl(); 15948 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15949 loc = mem->getMemberLoc(); 15950 d = mem->getMemberDecl(); 15951 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15952 diagID = diag::err_uncasted_call_of_unknown_any; 15953 loc = msg->getSelectorStartLoc(); 15954 d = msg->getMethodDecl(); 15955 if (!d) { 15956 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15957 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15958 << orig->getSourceRange(); 15959 return ExprError(); 15960 } 15961 } else { 15962 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15963 << E->getSourceRange(); 15964 return ExprError(); 15965 } 15966 15967 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15968 15969 // Never recoverable. 15970 return ExprError(); 15971 } 15972 15973 /// Check for operands with placeholder types and complain if found. 15974 /// Returns ExprError() if there was an error and no recovery was possible. 15975 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15976 if (!getLangOpts().CPlusPlus) { 15977 // C cannot handle TypoExpr nodes on either side of a binop because it 15978 // doesn't handle dependent types properly, so make sure any TypoExprs have 15979 // been dealt with before checking the operands. 15980 ExprResult Result = CorrectDelayedTyposInExpr(E); 15981 if (!Result.isUsable()) return ExprError(); 15982 E = Result.get(); 15983 } 15984 15985 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15986 if (!placeholderType) return E; 15987 15988 switch (placeholderType->getKind()) { 15989 15990 // Overloaded expressions. 15991 case BuiltinType::Overload: { 15992 // Try to resolve a single function template specialization. 15993 // This is obligatory. 15994 ExprResult Result = E; 15995 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15996 return Result; 15997 15998 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15999 // leaves Result unchanged on failure. 16000 Result = E; 16001 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16002 return Result; 16003 16004 // If that failed, try to recover with a call. 16005 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16006 /*complain*/ true); 16007 return Result; 16008 } 16009 16010 // Bound member functions. 16011 case BuiltinType::BoundMember: { 16012 ExprResult result = E; 16013 const Expr *BME = E->IgnoreParens(); 16014 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16015 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16016 if (isa<CXXPseudoDestructorExpr>(BME)) { 16017 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16018 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16019 if (ME->getMemberNameInfo().getName().getNameKind() == 16020 DeclarationName::CXXDestructorName) 16021 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16022 } 16023 tryToRecoverWithCall(result, PD, 16024 /*complain*/ true); 16025 return result; 16026 } 16027 16028 // ARC unbridged casts. 16029 case BuiltinType::ARCUnbridgedCast: { 16030 Expr *realCast = stripARCUnbridgedCast(E); 16031 diagnoseARCUnbridgedCast(realCast); 16032 return realCast; 16033 } 16034 16035 // Expressions of unknown type. 16036 case BuiltinType::UnknownAny: 16037 return diagnoseUnknownAnyExpr(*this, E); 16038 16039 // Pseudo-objects. 16040 case BuiltinType::PseudoObject: 16041 return checkPseudoObjectRValue(E); 16042 16043 case BuiltinType::BuiltinFn: { 16044 // Accept __noop without parens by implicitly converting it to a call expr. 16045 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16046 if (DRE) { 16047 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16048 if (FD->getBuiltinID() == Builtin::BI__noop) { 16049 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16050 CK_BuiltinFnToFnPtr).get(); 16051 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16052 VK_RValue, SourceLocation()); 16053 } 16054 } 16055 16056 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16057 return ExprError(); 16058 } 16059 16060 // Expressions of unknown type. 16061 case BuiltinType::OMPArraySection: 16062 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16063 return ExprError(); 16064 16065 // Everything else should be impossible. 16066 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16067 case BuiltinType::Id: 16068 #include "clang/Basic/OpenCLImageTypes.def" 16069 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16070 #define PLACEHOLDER_TYPE(Id, SingletonId) 16071 #include "clang/AST/BuiltinTypes.def" 16072 break; 16073 } 16074 16075 llvm_unreachable("invalid placeholder type!"); 16076 } 16077 16078 bool Sema::CheckCaseExpression(Expr *E) { 16079 if (E->isTypeDependent()) 16080 return true; 16081 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16082 return E->getType()->isIntegralOrEnumerationType(); 16083 return false; 16084 } 16085 16086 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16087 ExprResult 16088 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16089 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16090 "Unknown Objective-C Boolean value!"); 16091 QualType BoolT = Context.ObjCBuiltinBoolTy; 16092 if (!Context.getBOOLDecl()) { 16093 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16094 Sema::LookupOrdinaryName); 16095 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16096 NamedDecl *ND = Result.getFoundDecl(); 16097 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16098 Context.setBOOLDecl(TD); 16099 } 16100 } 16101 if (Context.getBOOLDecl()) 16102 BoolT = Context.getBOOLType(); 16103 return new (Context) 16104 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16105 } 16106 16107 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16108 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16109 SourceLocation RParen) { 16110 16111 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16112 16113 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16114 [&](const AvailabilitySpec &Spec) { 16115 return Spec.getPlatform() == Platform; 16116 }); 16117 16118 VersionTuple Version; 16119 if (Spec != AvailSpecs.end()) 16120 Version = Spec->getVersion(); 16121 16122 // The use of `@available` in the enclosing function should be analyzed to 16123 // warn when it's used inappropriately (i.e. not if(@available)). 16124 if (getCurFunctionOrMethodDecl()) 16125 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16126 else if (getCurBlock() || getCurLambda()) 16127 getCurFunction()->HasPotentialAvailabilityViolations = true; 16128 16129 return new (Context) 16130 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16131 } 16132